lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
4c22d138caae4fbbd232387d60931784a0b8fbd4
| 0 |
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder;
import com.intellij.concurrency.JobLauncher;
import com.intellij.ide.IdeBundle;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.ex.util.LayeredTextAttributes;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.impl.source.tree.injected.Place;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.openapi.editor.colors.EditorColors.createInjectedLanguageFragmentKey;
public final class InjectedGeneralHighlightingPass extends GeneralHighlightingPass {
InjectedGeneralHighlightingPass(@NotNull Project project,
@NotNull PsiFile file,
@NotNull Document document,
int startOffset,
int endOffset,
boolean updateAll,
@NotNull ProperTextRange priorityRange,
@Nullable Editor editor,
@NotNull HighlightInfoProcessor highlightInfoProcessor) {
super(project, file, document, startOffset, endOffset, updateAll, priorityRange, editor, highlightInfoProcessor);
}
@Override
protected String getPresentableName() {
return IdeBundle.message("highlighting.pass.injected.presentable.name");
}
@Override
protected void collectInformationWithProgress(@NotNull ProgressIndicator progress) {
if (!Registry.is("editor.injected.highlighting.enabled")) return;
List<Divider.DividedElements> allDivided = new ArrayList<>();
Divider.divideInsideAndOutsideAllRoots(myFile, myRestrictRange, myPriorityRange, SHOULD_HIGHLIGHT_FILTER, new CommonProcessors.CollectProcessor<>(allDivided));
List<PsiElement> allInsideElements = ContainerUtil.concat((List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> d.inside));
List<PsiElement> allOutsideElements = ContainerUtil.concat((List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> d.outside));
// all infos for the "injected fragment for the host which is inside" are indeed inside
// but some of the infos for the "injected fragment for the host which is outside" can be still inside
Set<PsiFile> injected = getInjectedPsiFiles(allInsideElements, allOutsideElements, progress);
Set<HighlightInfo> injectedResult = new HashSet<>();
if (!addInjectedPsiHighlights(injected, progress, Collections.synchronizedSet(injectedResult))) {
throw new ProcessCanceledException();
}
Set<HighlightInfo> result;
synchronized (injectedResult) {
// sync here because all writes happened in another thread
result = injectedResult.isEmpty() ? Collections.emptySet(): new HashSet<>(injectedResult);
}
Set<HighlightInfo> gotHighlights = new HashSet<>(100);
List<HighlightInfo> injectionsOutside = new ArrayList<>(gotHighlights.size());
for (HighlightInfo info : result) {
if (myRestrictRange.contains(info)) {
gotHighlights.add(info);
}
else {
// nonconditionally apply injected results regardless whether they are in myStartOffset,myEndOffset
injectionsOutside.add(info);
}
}
if (!injectionsOutside.isEmpty()) {
boolean priorityIntersectionHasElements = myPriorityRange.intersectsStrict(myRestrictRange);
if ((!allInsideElements.isEmpty() || !gotHighlights.isEmpty()) && priorityIntersectionHasElements) { // do not apply when there were no elements to highlight
// clear infos found in visible area to avoid applying them twice
List<HighlightInfo> toApplyInside = new ArrayList<>(gotHighlights);
myHighlights.addAll(toApplyInside);
gotHighlights.clear();
myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, getEditor(), toApplyInside, myPriorityRange, myRestrictRange,
getId());
}
List<HighlightInfo> toApply = new ArrayList<>();
for (HighlightInfo info : gotHighlights) {
if (!myRestrictRange.contains(info)) continue;
if (!myPriorityRange.contains(info)) {
toApply.add(info);
}
}
toApply.addAll(injectionsOutside);
myHighlightInfoProcessor.highlightsOutsideVisiblePartAreProduced(myHighlightingSession, getEditor(), toApply, myRestrictRange, new ProperTextRange(0, myDocument.getTextLength()),
getId());
}
else {
// else apply only result (by default apply command) and only within inside
myHighlights.addAll(gotHighlights);
myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, getEditor(), myHighlights, myRestrictRange, myRestrictRange,
getId());
}
}
@NotNull
private Set<PsiFile> getInjectedPsiFiles(@NotNull List<? extends PsiElement> elements1,
@NotNull List<? extends PsiElement> elements2,
@NotNull ProgressIndicator progress) {
ApplicationManager.getApplication().assertReadAccessAllowed();
List<DocumentWindow> injected = InjectedLanguageManager.getInstance(myProject).getCachedInjectedDocumentsInRange(myFile, myFile.getTextRange());
Collection<PsiElement> hosts = new HashSet<>(elements1.size() + elements2.size() + injected.size());
//rehighlight all injected PSI regardless the range,
//since change in one place can lead to invalidation of injected PSI in (completely) other place.
for (DocumentWindow documentRange : injected) {
ProgressManager.checkCanceled();
if (!documentRange.isValid()) continue;
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(documentRange);
if (file == null) continue;
PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file);
if (context != null
&& context.isValid()
&& !file.getProject().isDisposed()
&& (myUpdateAll || myRestrictRange.intersects(context.getTextRange()))) {
hosts.add(context);
}
}
InjectedLanguageManagerImpl injectedLanguageManager = InjectedLanguageManagerImpl.getInstanceImpl(myProject);
final boolean probeUp = false;
Processor<PsiElement> collectInjectableProcessor = new CommonProcessors.CollectProcessor<>(hosts) {
@Override
public boolean process(PsiElement t) {
ProgressManager.checkCanceled();
if (InjectedLanguageUtil.isInjectable(t, probeUp)) {
super.process(t);
}
return true;
}
};
injectedLanguageManager.processInjectableElements(elements1, collectInjectableProcessor);
injectedLanguageManager.processInjectableElements(elements2, collectInjectableProcessor);
Set<PsiFile> outInjected = new HashSet<>();
PsiLanguageInjectionHost.InjectedPsiVisitor visitor = (injectedPsi, places) -> {
synchronized (outInjected) {
ProgressManager.checkCanceled();
outInjected.add(injectedPsi);
}
};
// the most expensive process is running injectors for these hosts, comparing to highlighting the resulting injected fragments,
// so instead of showing "highlighted 1% of injected fragments", show "ran injectors for 1% of hosts"
setProgressLimit(hosts.size());
if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(
new ArrayList<>(hosts), progress, element -> {
ApplicationManager.getApplication().assertReadAccessAllowed();
injectedLanguageManager.enumerateEx(element, myFile, probeUp, visitor);
advanceProgress(1);
return true;
})) {
throw new ProcessCanceledException();
}
synchronized (outInjected) {
return outInjected.isEmpty() ? Collections.emptySet() : new HashSet<>(outInjected);
}
}
// returns false if canceled
private boolean addInjectedPsiHighlights(@NotNull Set<? extends PsiFile> injectedFiles,
@NotNull ProgressIndicator progress,
@NotNull Collection<? super HighlightInfo> outInfos) {
if (injectedFiles.isEmpty()) return true;
InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(myProject);
TextAttributesKey fragmentKey = createInjectedLanguageFragmentKey(myFile.getLanguage());
return JobLauncher.getInstance()
.invokeConcurrentlyUnderProgress(new ArrayList<>(injectedFiles), progress,
injectedPsi -> addInjectedPsiHighlights(injectedPsi, fragmentKey, outInfos,
injectedLanguageManager));
}
@Override
protected void queueInfoToUpdateIncrementally(@NotNull HighlightInfo info) {
// do not send info to highlight immediately - we need to convert its offsets first
// see addPatchedInfos()
}
private boolean addInjectedPsiHighlights(@NotNull PsiFile injectedPsi,
TextAttributesKey attributesKey,
@NotNull Collection<? super HighlightInfo> outInfos,
@NotNull InjectedLanguageManager injectedLanguageManager) {
DocumentWindow documentWindow = (DocumentWindow)PsiDocumentManager.getInstance(myProject).getCachedDocument(injectedPsi);
if (documentWindow == null) return true;
Place places = InjectedLanguageUtil.getShreds(injectedPsi);
boolean addTooltips = places.size() < 100;
for (PsiLanguageInjectionHost.Shred place : places) {
PsiLanguageInjectionHost host = place.getHost();
if (host == null) continue;
TextRange textRange = place.getRangeInsideHost().shiftRight(host.getTextRange().getStartOffset());
if (textRange.isEmpty()) continue;
HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_BACKGROUND).range(textRange);
if (attributesKey != null && InjectedLanguageUtil.isHighlightInjectionBackground(host)) {
builder.textAttributes(attributesKey);
}
if (addTooltips) {
String desc = injectedPsi.getLanguage().getDisplayName() + ": " + injectedPsi.getText();
builder.unescapedToolTip(desc);
}
HighlightInfo info = builder.createUnconditionally();
info.setFromInjection(true);
outInfos.add(info);
}
HighlightInfoHolder holder = createInfoHolder(injectedPsi);
runHighlightVisitorsForInjected(injectedPsi, holder);
for (int i = 0; i < holder.size(); i++) {
HighlightInfo info = holder.get(i);
int startOffset = documentWindow.injectedToHost(info.startOffset);
TextRange fixedTextRange = getFixedTextRange(documentWindow, startOffset);
addPatchedInfos(info, injectedPsi, documentWindow, injectedLanguageManager, fixedTextRange, outInfos);
}
int injectedStart = holder.size();
highlightInjectedSyntax(injectedPsi, holder);
for (int i = injectedStart; i < holder.size(); i++) {
HighlightInfo info = holder.get(i);
int startOffset = info.startOffset;
TextRange fixedTextRange = getFixedTextRange(documentWindow, startOffset);
if (fixedTextRange == null) {
info.setFromInjection(true);
outInfos.add(info);
}
else {
HighlightInfo patched =
new HighlightInfo(info.forcedTextAttributes, info.forcedTextAttributesKey,
info.type, fixedTextRange.getStartOffset(),
fixedTextRange.getEndOffset(),
info.getDescription(), info.getToolTip(), info.getSeverity(),
info.isAfterEndOfLine(), null, false, 0, info.getProblemGroup(), info.getInspectionToolId(), info.getGutterIconRenderer(), info.getGroup());
patched.setFromInjection(true);
outInfos.add(patched);
}
}
if (!isDumbMode()) {
List<HighlightInfo> todos = new ArrayList<>();
highlightTodos(injectedPsi, injectedPsi.getText(), 0, injectedPsi.getTextLength(), myPriorityRange, todos, todos);
for (HighlightInfo info : todos) {
addPatchedInfos(info, injectedPsi, documentWindow, injectedLanguageManager, null, outInfos);
}
}
return true;
}
@Nullable("null means invalid")
private static TextRange getFixedTextRange(@NotNull DocumentWindow documentWindow, int startOffset) {
TextRange fixedTextRange;
TextRange textRange = documentWindow.getHostRange(startOffset);
if (textRange == null) {
// todo[cdr] check this fix. prefix/suffix code annotation case
textRange = findNearestTextRange(documentWindow, startOffset);
if (textRange == null) return null;
boolean isBefore = startOffset < textRange.getStartOffset();
fixedTextRange = new ProperTextRange(isBefore ? textRange.getStartOffset() - 1 : textRange.getEndOffset(),
isBefore ? textRange.getStartOffset() : textRange.getEndOffset() + 1);
}
else {
fixedTextRange = null;
}
return fixedTextRange;
}
private static void addPatchedInfos(@NotNull HighlightInfo info,
@NotNull PsiFile injectedPsi,
@NotNull DocumentWindow documentWindow,
@NotNull InjectedLanguageManager injectedLanguageManager,
@Nullable TextRange fixedTextRange,
@NotNull Collection<? super HighlightInfo> out) {
ProperTextRange textRange = new ProperTextRange(info.startOffset, info.endOffset);
List<TextRange> editables = injectedLanguageManager.intersectWithAllEditableFragments(injectedPsi, textRange);
for (TextRange editable : editables) {
TextRange hostRange = fixedTextRange == null ? documentWindow.injectedToHost(editable) : fixedTextRange;
boolean isAfterEndOfLine = info.isAfterEndOfLine();
if (isAfterEndOfLine) {
// convert injected afterEndOfLine to either host' afterEndOfLine or not-afterEndOfLine highlight of the injected fragment boundary
int hostEndOffset = hostRange.getEndOffset();
int lineNumber = documentWindow.getDelegate().getLineNumber(hostEndOffset);
int hostLineEndOffset = documentWindow.getDelegate().getLineEndOffset(lineNumber);
if (hostEndOffset < hostLineEndOffset) {
// convert to non-afterEndOfLine
isAfterEndOfLine = false;
hostRange = new ProperTextRange(hostRange.getStartOffset(), hostEndOffset+1);
}
}
HighlightInfo patched =
new HighlightInfo(info.forcedTextAttributes, info.forcedTextAttributesKey, info.type,
hostRange.getStartOffset(), hostRange.getEndOffset(),
info.getDescription(), info.getToolTip(), info.getSeverity(), isAfterEndOfLine, null,
false, 0, info.getProblemGroup(), info.getInspectionToolId(), info.getGutterIconRenderer(), info.getGroup());
patched.setHint(info.hasHint());
if (info.quickFixActionRanges != null) {
for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) {
TextRange quickfixTextRange = pair.getSecond();
List<TextRange> editableQF = injectedLanguageManager.intersectWithAllEditableFragments(injectedPsi, quickfixTextRange);
for (TextRange editableRange : editableQF) {
HighlightInfo.IntentionActionDescriptor descriptor = pair.getFirst();
if (patched.quickFixActionRanges == null) patched.quickFixActionRanges = new ArrayList<>();
TextRange hostEditableRange = documentWindow.injectedToHost(editableRange);
patched.quickFixActionRanges.add(Pair.create(descriptor, hostEditableRange));
}
}
}
patched.setFromInjection(true);
out.add(patched);
}
}
// finds the first nearest text range
@Nullable("null means invalid")
private static TextRange findNearestTextRange(DocumentWindow documentWindow, int startOffset) {
TextRange textRange = null;
for (Segment marker : documentWindow.getHostRanges()) {
TextRange curRange = ProperTextRange.create(marker);
if (curRange.getStartOffset() > startOffset && textRange != null) break;
textRange = curRange;
}
return textRange;
}
private void runHighlightVisitorsForInjected(@NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
HighlightVisitor[] filtered = getHighlightVisitors(injectedPsi);
try {
List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(injectedPsi, 0, injectedPsi.getTextLength());
for (HighlightVisitor visitor : filtered) {
visitor.analyze(injectedPsi, true, holder, () -> {
for (PsiElement element : elements) {
ProgressManager.checkCanceled();
visitor.visit(element);
}
});
}
}
finally {
incVisitorUsageCount(-1);
}
}
private void highlightInjectedSyntax(@NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
List<InjectedLanguageUtil.TokenInfo> tokens = InjectedLanguageUtil.getHighlightTokens(injectedPsi);
if (tokens == null) return;
Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
int shredIndex = -1;
int injectionHostTextRangeStart = -1;
for (InjectedLanguageUtil.TokenInfo token : tokens) {
ProgressManager.checkCanceled();
TextRange range = token.rangeInsideInjectionHost;
if (range.getLength() == 0) continue;
if (shredIndex != token.shredIndex) {
shredIndex = token.shredIndex;
PsiLanguageInjectionHost.Shred shred = shreds.get(shredIndex);
PsiLanguageInjectionHost host = shred.getHost();
if (host == null) return;
injectionHostTextRangeStart = host.getTextRange().getStartOffset();
}
TextRange shiftedRange = range.shiftRight(injectionHostTextRangeStart);
holder.addAll(overrideDefaultHighlights(myGlobalScheme, shiftedRange, token.textAttributesKeys));
}
}
@Override
protected void applyInformationWithProgress() {
}
@NotNull
public static List<HighlightInfo> overrideDefaultHighlights(@NotNull EditorColorsScheme scheme,
@NotNull TextRange range,
TextAttributesKey @NotNull [] keys) {
List<HighlightInfo> result = new ArrayList<>();
if (range.isEmpty()) {
return result;
}
// erase marker to override hosts colors
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
.range(range)
.textAttributes(TextAttributes.ERASE_MARKER)
.createUnconditionally();
result.add(info);
LayeredTextAttributes injectedAttributes = LayeredTextAttributes.create(scheme, keys);
if (injectedAttributes.isEmpty() || keys.length == 1 && keys[0] == HighlighterColors.TEXT) {
// nothing to add
return result;
}
HighlightInfo injectedInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
.range(range)
.textAttributes(injectedAttributes)
.createUnconditionally();
result.add(injectedInfo);
return result;
}
}
|
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder;
import com.intellij.concurrency.JobLauncher;
import com.intellij.ide.IdeBundle;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.ex.util.LayeredTextAttributes;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.impl.source.tree.injected.Place;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.openapi.editor.colors.EditorColors.createInjectedLanguageFragmentKey;
public final class InjectedGeneralHighlightingPass extends GeneralHighlightingPass {
InjectedGeneralHighlightingPass(@NotNull Project project,
@NotNull PsiFile file,
@NotNull Document document,
int startOffset,
int endOffset,
boolean updateAll,
@NotNull ProperTextRange priorityRange,
@Nullable Editor editor,
@NotNull HighlightInfoProcessor highlightInfoProcessor) {
super(project, file, document, startOffset, endOffset, updateAll, priorityRange, editor, highlightInfoProcessor);
}
@Override
protected String getPresentableName() {
return IdeBundle.message("highlighting.pass.injected.presentable.name");
}
@Override
protected void collectInformationWithProgress(@NotNull ProgressIndicator progress) {
if (!Registry.is("editor.injected.highlighting.enabled")) return;
List<Divider.DividedElements> allDivided = new ArrayList<>();
Divider.divideInsideAndOutsideAllRoots(myFile, myRestrictRange, myPriorityRange, SHOULD_HIGHLIGHT_FILTER, new CommonProcessors.CollectProcessor<>(allDivided));
List<PsiElement> allInsideElements = ContainerUtil.concat((List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> d.inside));
List<PsiElement> allOutsideElements = ContainerUtil.concat((List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> d.outside));
// all infos for the "injected fragment for the host which is inside" are indeed inside
// but some of the infos for the "injected fragment for the host which is outside" can be still inside
Set<PsiFile> injected = getInjectedPsiFiles(allInsideElements, allOutsideElements, progress);
Set<HighlightInfo> injectedResult = new HashSet<>();
if (!addInjectedPsiHighlights(injected, progress, Collections.synchronizedSet(injectedResult))) {
throw new ProcessCanceledException();
}
Set<HighlightInfo> result;
synchronized (injectedResult) {
// sync here because all writes happened in another thread
result = injectedResult.isEmpty() ? Collections.emptySet(): new HashSet<>(injectedResult);
}
Set<HighlightInfo> gotHighlights = new HashSet<>(100);
List<HighlightInfo> injectionsOutside = new ArrayList<>(gotHighlights.size());
for (HighlightInfo info : result) {
if (myRestrictRange.contains(info)) {
gotHighlights.add(info);
}
else {
// nonconditionally apply injected results regardless whether they are in myStartOffset,myEndOffset
injectionsOutside.add(info);
}
}
if (!injectionsOutside.isEmpty()) {
boolean priorityIntersectionHasElements = myPriorityRange.intersectsStrict(myRestrictRange);
if ((!allInsideElements.isEmpty() || !gotHighlights.isEmpty()) && priorityIntersectionHasElements) { // do not apply when there were no elements to highlight
// clear infos found in visible area to avoid applying them twice
List<HighlightInfo> toApplyInside = new ArrayList<>(gotHighlights);
myHighlights.addAll(toApplyInside);
gotHighlights.clear();
myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, getEditor(), toApplyInside, myPriorityRange, myRestrictRange,
getId());
}
List<HighlightInfo> toApply = new ArrayList<>();
for (HighlightInfo info : gotHighlights) {
if (!myRestrictRange.contains(info)) continue;
if (!myPriorityRange.contains(info)) {
toApply.add(info);
}
}
toApply.addAll(injectionsOutside);
myHighlightInfoProcessor.highlightsOutsideVisiblePartAreProduced(myHighlightingSession, getEditor(), toApply, myRestrictRange, new ProperTextRange(0, myDocument.getTextLength()),
getId());
}
else {
// else apply only result (by default apply command) and only within inside
myHighlights.addAll(gotHighlights);
myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, getEditor(), myHighlights, myRestrictRange, myRestrictRange,
getId());
}
}
@NotNull
private Set<PsiFile> getInjectedPsiFiles(@NotNull List<? extends PsiElement> elements1,
@NotNull List<? extends PsiElement> elements2,
@NotNull ProgressIndicator progress) {
ApplicationManager.getApplication().assertReadAccessAllowed();
List<DocumentWindow> injected = InjectedLanguageManager.getInstance(myProject).getCachedInjectedDocumentsInRange(myFile, myFile.getTextRange());
Collection<PsiElement> hosts = new HashSet<>(elements1.size() + elements2.size() + injected.size());
//rehighlight all injected PSI regardless the range,
//since change in one place can lead to invalidation of injected PSI in (completely) other place.
for (DocumentWindow documentRange : injected) {
ProgressManager.checkCanceled();
if (!documentRange.isValid()) continue;
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(documentRange);
if (file == null) continue;
PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file);
if (context != null
&& context.isValid()
&& !file.getProject().isDisposed()
&& (myUpdateAll || myRestrictRange.intersects(context.getTextRange()))) {
hosts.add(context);
}
}
InjectedLanguageManagerImpl injectedLanguageManager = InjectedLanguageManagerImpl.getInstanceImpl(myProject);
final boolean probeUp = false;
Processor<PsiElement> collectInjectableProcessor = new CommonProcessors.CollectProcessor<>(hosts) {
@Override
public boolean process(PsiElement t) {
ProgressManager.checkCanceled();
if (InjectedLanguageUtil.isInjectable(t, probeUp)) {
super.process(t);
}
return true;
}
};
injectedLanguageManager.processInjectableElements(elements1, collectInjectableProcessor);
injectedLanguageManager.processInjectableElements(elements2, collectInjectableProcessor);
Set<PsiFile> outInjected = new HashSet<>();
PsiLanguageInjectionHost.InjectedPsiVisitor visitor = (injectedPsi, places) -> {
synchronized (outInjected) {
ProgressManager.checkCanceled();
outInjected.add(injectedPsi);
}
};
// the most expensive process is running injectors for these hosts, comparing to highlighting the resulting injected fragments,
// so instead of showing "highlighted 1% of injected fragments", show "ran injectors for 1% of hosts"
setProgressLimit(hosts.size());
if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(
new ArrayList<>(hosts), progress, element -> {
ApplicationManager.getApplication().assertReadAccessAllowed();
injectedLanguageManager.enumerateEx(element, myFile, probeUp, visitor);
advanceProgress(1);
return true;
})) {
throw new ProcessCanceledException();
}
synchronized (outInjected) {
return outInjected.isEmpty() ? Collections.emptySet() : new HashSet<>(outInjected);
}
}
// returns false if canceled
private boolean addInjectedPsiHighlights(@NotNull Set<? extends PsiFile> injectedFiles,
@NotNull ProgressIndicator progress,
@NotNull Collection<? super HighlightInfo> outInfos) {
if (injectedFiles.isEmpty()) return true;
InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(myProject);
TextAttributesKey fragmentKey = createInjectedLanguageFragmentKey(myFile.getLanguage());
return JobLauncher.getInstance()
.invokeConcurrentlyUnderProgress(new ArrayList<>(injectedFiles), progress,
injectedPsi -> addInjectedPsiHighlights(injectedPsi, fragmentKey, outInfos,
injectedLanguageManager));
}
@Override
protected void queueInfoToUpdateIncrementally(@NotNull HighlightInfo info) {
// do not send info to highlight immediately - we need to convert its offsets first
// see addPatchedInfos()
}
private boolean addInjectedPsiHighlights(@NotNull PsiFile injectedPsi,
TextAttributesKey attributesKey,
@NotNull Collection<? super HighlightInfo> outInfos,
@NotNull InjectedLanguageManager injectedLanguageManager) {
DocumentWindow documentWindow = (DocumentWindow)PsiDocumentManager.getInstance(myProject).getCachedDocument(injectedPsi);
if (documentWindow == null) return true;
Place places = InjectedLanguageUtil.getShreds(injectedPsi);
boolean addTooltips = places.size() < 100;
for (PsiLanguageInjectionHost.Shred place : places) {
PsiLanguageInjectionHost host = place.getHost();
if (host == null) continue;
TextRange textRange = place.getRangeInsideHost().shiftRight(host.getTextRange().getStartOffset());
if (textRange.isEmpty()) continue;
HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_BACKGROUND).range(textRange);
if (attributesKey != null && InjectedLanguageUtil.isHighlightInjectionBackground(host)) {
builder.textAttributes(attributesKey);
}
if (addTooltips) {
String desc = injectedPsi.getLanguage().getDisplayName() + ": " + injectedPsi.getText();
builder.unescapedToolTip(desc);
}
HighlightInfo info = builder.createUnconditionally();
info.setFromInjection(true);
outInfos.add(info);
}
HighlightInfoHolder holder = createInfoHolder(injectedPsi);
runHighlightVisitorsForInjected(injectedPsi, holder);
for (int i = 0; i < holder.size(); i++) {
HighlightInfo info = holder.get(i);
int startOffset = documentWindow.injectedToHost(info.startOffset);
TextRange fixedTextRange = getFixedTextRange(documentWindow, startOffset);
addPatchedInfos(info, injectedPsi, documentWindow, injectedLanguageManager, fixedTextRange, outInfos);
}
int injectedStart = holder.size();
highlightInjectedSyntax(injectedPsi, holder);
for (int i = injectedStart; i < holder.size(); i++) {
HighlightInfo info = holder.get(i);
int startOffset = info.startOffset;
TextRange fixedTextRange = getFixedTextRange(documentWindow, startOffset);
if (fixedTextRange == null) {
info.setFromInjection(true);
outInfos.add(info);
}
else {
HighlightInfo patched =
new HighlightInfo(info.forcedTextAttributes, info.forcedTextAttributesKey,
info.type, fixedTextRange.getStartOffset(),
fixedTextRange.getEndOffset(),
info.getDescription(), info.getToolTip(), info.type.getSeverity(null),
info.isAfterEndOfLine(), null, false, 0, info.getProblemGroup(), info.getInspectionToolId(), info.getGutterIconRenderer(), info.getGroup());
patched.setFromInjection(true);
outInfos.add(patched);
}
}
if (!isDumbMode()) {
List<HighlightInfo> todos = new ArrayList<>();
highlightTodos(injectedPsi, injectedPsi.getText(), 0, injectedPsi.getTextLength(), myPriorityRange, todos, todos);
for (HighlightInfo info : todos) {
addPatchedInfos(info, injectedPsi, documentWindow, injectedLanguageManager, null, outInfos);
}
}
return true;
}
@Nullable("null means invalid")
private static TextRange getFixedTextRange(@NotNull DocumentWindow documentWindow, int startOffset) {
TextRange fixedTextRange;
TextRange textRange = documentWindow.getHostRange(startOffset);
if (textRange == null) {
// todo[cdr] check this fix. prefix/suffix code annotation case
textRange = findNearestTextRange(documentWindow, startOffset);
if (textRange == null) return null;
boolean isBefore = startOffset < textRange.getStartOffset();
fixedTextRange = new ProperTextRange(isBefore ? textRange.getStartOffset() - 1 : textRange.getEndOffset(),
isBefore ? textRange.getStartOffset() : textRange.getEndOffset() + 1);
}
else {
fixedTextRange = null;
}
return fixedTextRange;
}
private static void addPatchedInfos(@NotNull HighlightInfo info,
@NotNull PsiFile injectedPsi,
@NotNull DocumentWindow documentWindow,
@NotNull InjectedLanguageManager injectedLanguageManager,
@Nullable TextRange fixedTextRange,
@NotNull Collection<? super HighlightInfo> out) {
ProperTextRange textRange = new ProperTextRange(info.startOffset, info.endOffset);
List<TextRange> editables = injectedLanguageManager.intersectWithAllEditableFragments(injectedPsi, textRange);
for (TextRange editable : editables) {
TextRange hostRange = fixedTextRange == null ? documentWindow.injectedToHost(editable) : fixedTextRange;
boolean isAfterEndOfLine = info.isAfterEndOfLine();
if (isAfterEndOfLine) {
// convert injected afterEndOfLine to either host' afterEndOfLine or not-afterEndOfLine highlight of the injected fragment boundary
int hostEndOffset = hostRange.getEndOffset();
int lineNumber = documentWindow.getDelegate().getLineNumber(hostEndOffset);
int hostLineEndOffset = documentWindow.getDelegate().getLineEndOffset(lineNumber);
if (hostEndOffset < hostLineEndOffset) {
// convert to non-afterEndOfLine
isAfterEndOfLine = false;
hostRange = new ProperTextRange(hostRange.getStartOffset(), hostEndOffset+1);
}
}
HighlightInfo patched =
new HighlightInfo(info.forcedTextAttributes, info.forcedTextAttributesKey, info.type,
hostRange.getStartOffset(), hostRange.getEndOffset(),
info.getDescription(), info.getToolTip(), info.type.getSeverity(null), isAfterEndOfLine, null,
false, 0, info.getProblemGroup(), info.getInspectionToolId(), info.getGutterIconRenderer(), info.getGroup());
patched.setHint(info.hasHint());
if (info.quickFixActionRanges != null) {
for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) {
TextRange quickfixTextRange = pair.getSecond();
List<TextRange> editableQF = injectedLanguageManager.intersectWithAllEditableFragments(injectedPsi, quickfixTextRange);
for (TextRange editableRange : editableQF) {
HighlightInfo.IntentionActionDescriptor descriptor = pair.getFirst();
if (patched.quickFixActionRanges == null) patched.quickFixActionRanges = new ArrayList<>();
TextRange hostEditableRange = documentWindow.injectedToHost(editableRange);
patched.quickFixActionRanges.add(Pair.create(descriptor, hostEditableRange));
}
}
}
patched.setFromInjection(true);
out.add(patched);
}
}
// finds the first nearest text range
@Nullable("null means invalid")
private static TextRange findNearestTextRange(DocumentWindow documentWindow, int startOffset) {
TextRange textRange = null;
for (Segment marker : documentWindow.getHostRanges()) {
TextRange curRange = ProperTextRange.create(marker);
if (curRange.getStartOffset() > startOffset && textRange != null) break;
textRange = curRange;
}
return textRange;
}
private void runHighlightVisitorsForInjected(@NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
HighlightVisitor[] filtered = getHighlightVisitors(injectedPsi);
try {
List<PsiElement> elements = CollectHighlightsUtil.getElementsInRange(injectedPsi, 0, injectedPsi.getTextLength());
for (HighlightVisitor visitor : filtered) {
visitor.analyze(injectedPsi, true, holder, () -> {
for (PsiElement element : elements) {
ProgressManager.checkCanceled();
visitor.visit(element);
}
});
}
}
finally {
incVisitorUsageCount(-1);
}
}
private void highlightInjectedSyntax(@NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
List<InjectedLanguageUtil.TokenInfo> tokens = InjectedLanguageUtil.getHighlightTokens(injectedPsi);
if (tokens == null) return;
Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
int shredIndex = -1;
int injectionHostTextRangeStart = -1;
for (InjectedLanguageUtil.TokenInfo token : tokens) {
ProgressManager.checkCanceled();
TextRange range = token.rangeInsideInjectionHost;
if (range.getLength() == 0) continue;
if (shredIndex != token.shredIndex) {
shredIndex = token.shredIndex;
PsiLanguageInjectionHost.Shred shred = shreds.get(shredIndex);
PsiLanguageInjectionHost host = shred.getHost();
if (host == null) return;
injectionHostTextRangeStart = host.getTextRange().getStartOffset();
}
TextRange shiftedRange = range.shiftRight(injectionHostTextRangeStart);
holder.addAll(overrideDefaultHighlights(myGlobalScheme, shiftedRange, token.textAttributesKeys));
}
}
@Override
protected void applyInformationWithProgress() {
}
@NotNull
public static List<HighlightInfo> overrideDefaultHighlights(@NotNull EditorColorsScheme scheme,
@NotNull TextRange range,
TextAttributesKey @NotNull [] keys) {
List<HighlightInfo> result = new ArrayList<>();
if (range.isEmpty()) {
return result;
}
// erase marker to override hosts colors
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
.range(range)
.textAttributes(TextAttributes.ERASE_MARKER)
.createUnconditionally();
result.add(info);
LayeredTextAttributes injectedAttributes = LayeredTextAttributes.create(scheme, keys);
if (injectedAttributes.isEmpty() || keys.length == 1 && keys[0] == HighlighterColors.TEXT) {
// nothing to add
return result;
}
HighlightInfo injectedInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
.range(range)
.textAttributes(injectedAttributes)
.createUnconditionally();
result.add(injectedInfo);
return result;
}
}
|
WEB-48856: use own HighlightInfo severity in injections
(cherry picked from commit 157fca72e61fa1d4b1e2b2e1a1e6d85838a8c8c1)
IDEA-CR-70002
GitOrigin-RevId: b685c5d75bbee065641101b8c00532d0580ebbb9
|
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java
|
WEB-48856: use own HighlightInfo severity in injections
|
<ide><path>latform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java
<ide> new HighlightInfo(info.forcedTextAttributes, info.forcedTextAttributesKey,
<ide> info.type, fixedTextRange.getStartOffset(),
<ide> fixedTextRange.getEndOffset(),
<del> info.getDescription(), info.getToolTip(), info.type.getSeverity(null),
<add> info.getDescription(), info.getToolTip(), info.getSeverity(),
<ide> info.isAfterEndOfLine(), null, false, 0, info.getProblemGroup(), info.getInspectionToolId(), info.getGutterIconRenderer(), info.getGroup());
<ide> patched.setFromInjection(true);
<ide> outInfos.add(patched);
<ide> HighlightInfo patched =
<ide> new HighlightInfo(info.forcedTextAttributes, info.forcedTextAttributesKey, info.type,
<ide> hostRange.getStartOffset(), hostRange.getEndOffset(),
<del> info.getDescription(), info.getToolTip(), info.type.getSeverity(null), isAfterEndOfLine, null,
<add> info.getDescription(), info.getToolTip(), info.getSeverity(), isAfterEndOfLine, null,
<ide> false, 0, info.getProblemGroup(), info.getInspectionToolId(), info.getGutterIconRenderer(), info.getGroup());
<ide> patched.setHint(info.hasHint());
<ide>
|
|
JavaScript
|
apache-2.0
|
242a6258dc552e27e49961a9bb7b4a0a040c1fac
| 0 |
AnimatedRNG/cesium,AnalyticalGraphicsInc/cesium,jason-crow/cesium,omh1280/cesium,progsung/cesium,wallw-bits/cesium,esraerik/cesium,NaderCHASER/cesium,likangning93/cesium,josh-bernstein/cesium,wallw-bits/cesium,CesiumGS/cesium,NaderCHASER/cesium,esraerik/cesium,oterral/cesium,aelatgt/cesium,oterral/cesium,hodbauer/cesium,YonatanKra/cesium,ggetz/cesium,AnimatedRNG/cesium,aelatgt/cesium,omh1280/cesium,CesiumGS/cesium,likangning93/cesium,wallw-bits/cesium,kiselev-dv/cesium,aelatgt/cesium,ggetz/cesium,denverpierce/cesium,CesiumGS/cesium,hodbauer/cesium,denverpierce/cesium,emackey/cesium,esraerik/cesium,ggetz/cesium,denverpierce/cesium,jason-crow/cesium,CesiumGS/cesium,omh1280/cesium,YonatanKra/cesium,denverpierce/cesium,soceur/cesium,CesiumGS/cesium,likangning93/cesium,esraerik/cesium,jason-crow/cesium,jasonbeverage/cesium,geoscan/cesium,kiselev-dv/cesium,kaktus40/cesium,AnalyticalGraphicsInc/cesium,soceur/cesium,AnimatedRNG/cesium,soceur/cesium,jason-crow/cesium,kaktus40/cesium,likangning93/cesium,ggetz/cesium,emackey/cesium,kiselev-dv/cesium,emackey/cesium,kiselev-dv/cesium,jasonbeverage/cesium,aelatgt/cesium,wallw-bits/cesium,YonatanKra/cesium,oterral/cesium,hodbauer/cesium,progsung/cesium,NaderCHASER/cesium,likangning93/cesium,josh-bernstein/cesium,omh1280/cesium,AnimatedRNG/cesium,YonatanKra/cesium,geoscan/cesium,emackey/cesium
|
/*global define*/
define([
'../Core/BoundingRectangle',
'../Core/Color',
'../Core/defined',
'../Core/destroyObject',
'../Core/PixelFormat',
'../Renderer/ClearCommand',
'../Renderer/Framebuffer',
'../Renderer/PixelDatatype',
'../Renderer/RenderState',
'../Renderer/ShaderProgram',
'../Renderer/ShaderSource',
'../Renderer/Texture',
'../Renderer/WebGLConstants',
'../Shaders/AdjustTranslucentFS',
'../Shaders/CompositeOITFS',
'./BlendEquation',
'./BlendFunction'
], function(
BoundingRectangle,
Color,
defined,
destroyObject,
PixelFormat,
ClearCommand,
Framebuffer,
PixelDatatype,
RenderState,
ShaderProgram,
ShaderSource,
Texture,
WebGLConstants,
AdjustTranslucentFS,
CompositeOITFS,
BlendEquation,
BlendFunction) {
'use strict';
/**
* @private
*/
function OIT(context) {
// We support multipass for the Chrome D3D9 backend and ES 2.0 on mobile.
this._translucentMultipassSupport = false;
this._translucentMRTSupport = false;
var extensionsSupported = context.floatingPointTexture && context.depthTexture;
this._translucentMRTSupport = context.drawBuffers && extensionsSupported;
this._translucentMultipassSupport = !this._translucentMRTSupport && extensionsSupported;
this._opaqueFBO = undefined;
this._opaqueTexture = undefined;
this._depthStencilTexture = undefined;
this._accumulationTexture = undefined;
this._translucentFBO = undefined;
this._alphaFBO = undefined;
this._adjustTranslucentFBO = undefined;
this._adjustAlphaFBO = undefined;
this._opaqueClearCommand = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 0.0),
owner : this
});
this._translucentMRTClearCommand = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 1.0),
owner : this
});
this._translucentMultipassClearCommand = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 0.0),
owner : this
});
this._alphaClearCommand = new ClearCommand({
color : new Color(1.0, 1.0, 1.0, 1.0),
owner : this
});
this._translucentRenderStateCache = {};
this._alphaRenderStateCache = {};
this._translucentShaderCache = {};
this._alphaShaderCache = {};
this._compositeCommand = undefined;
this._adjustTranslucentCommand = undefined;
this._adjustAlphaCommand = undefined;
this._viewport = new BoundingRectangle();
this._rs = undefined;
}
function destroyTextures(oit) {
oit._accumulationTexture = oit._accumulationTexture && !oit._accumulationTexture.isDestroyed() && oit._accumulationTexture.destroy();
oit._revealageTexture = oit._revealageTexture && !oit._revealageTexture.isDestroyed() && oit._revealageTexture.destroy();
}
function destroyFramebuffers(oit) {
oit._translucentFBO = oit._translucentFBO && !oit._translucentFBO.isDestroyed() && oit._translucentFBO.destroy();
oit._alphaFBO = oit._alphaFBO && !oit._alphaFBO.isDestroyed() && oit._alphaFBO.destroy();
oit._adjustTranslucentFBO = oit._adjustTranslucentFBO && !oit._adjustTranslucentFBO.isDestroyed() && oit._adjustTranslucentFBO.destroy();
oit._adjustAlphaFBO = oit._adjustAlphaFBO && !oit._adjustAlphaFBO.isDestroyed() && oit._adjustAlphaFBO.destroy();
}
function destroyResources(oit) {
destroyTextures(oit);
destroyFramebuffers(oit);
}
function updateTextures(oit, context, width, height) {
destroyTextures(oit);
oit._accumulationTexture = new Texture({
context : context,
width : width,
height : height,
pixelFormat : PixelFormat.RGBA,
pixelDatatype : PixelDatatype.FLOAT
});
oit._revealageTexture = new Texture({
context : context,
width : width,
height : height,
pixelFormat : PixelFormat.RGBA,
pixelDatatype : PixelDatatype.FLOAT
});
}
function updateFramebuffers(oit, context) {
destroyFramebuffers(oit);
var completeFBO = WebGLConstants.FRAMEBUFFER_COMPLETE;
var supported = true;
// if MRT is supported, attempt to make an FBO with multiple color attachments
if (oit._translucentMRTSupport) {
oit._translucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture, oit._revealageTexture],
depthStencilTexture : oit._depthStencilTexture,
destroyAttachments : false
});
oit._adjustTranslucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture, oit._revealageTexture],
destroyAttachments : false
});
if (oit._translucentFBO.status !== completeFBO || oit._adjustTranslucentFBO.status !== completeFBO) {
destroyFramebuffers(oit);
oit._translucentMRTSupport = false;
}
}
// either MRT isn't supported or FBO creation failed, attempt multipass
if (!oit._translucentMRTSupport) {
oit._translucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture],
depthStencilTexture : oit._depthStencilTexture,
destroyAttachments : false
});
oit._alphaFBO = new Framebuffer({
context : context,
colorTextures : [oit._revealageTexture],
depthStencilTexture : oit._depthStencilTexture,
destroyAttachments : false
});
oit._adjustTranslucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture],
destroyAttachments : false
});
oit._adjustAlphaFBO = new Framebuffer({
context : context,
colorTextures : [oit._revealageTexture],
destroyAttachments : false
});
var translucentComplete = oit._translucentFBO.status === completeFBO;
var alphaComplete = oit._alphaFBO.status === completeFBO;
var adjustTranslucentComplete = oit._adjustTranslucentFBO.status === completeFBO;
var adjustAlphaComplete = oit._adjustAlphaFBO.status === completeFBO;
if (!translucentComplete || !alphaComplete || !adjustTranslucentComplete || !adjustAlphaComplete) {
destroyResources(oit);
oit._translucentMultipassSupport = false;
supported = false;
}
}
return supported;
}
OIT.prototype.update = function(context, framebuffer) {
if (!this.isSupported()) {
return;
}
this._opaqueFBO = framebuffer;
this._opaqueTexture = framebuffer.getColorTexture(0);
this._depthStencilTexture = framebuffer.depthStencilTexture;
var width = this._opaqueTexture.width;
var height = this._opaqueTexture.height;
var accumulationTexture = this._accumulationTexture;
var textureChanged = !defined(accumulationTexture) || accumulationTexture.width !== width || accumulationTexture.height !== height;
if (textureChanged) {
updateTextures(this, context, width, height);
}
if (!defined(this._translucentFBO) || textureChanged) {
if (!updateFramebuffers(this, context)) {
// framebuffer creation failed
return;
}
}
var that = this;
var fs;
var uniformMap;
if (!defined(this._compositeCommand)) {
fs = new ShaderSource({
sources : [CompositeOITFS]
});
if (this._translucentMRTSupport) {
fs.defines.push('MRT');
}
uniformMap = {
u_opaque : function() {
return that._opaqueTexture;
},
u_accumulation : function() {
return that._accumulationTexture;
},
u_revealage : function() {
return that._revealageTexture;
}
};
this._compositeCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
}
if (!defined(this._adjustTranslucentCommand)) {
if (this._translucentMRTSupport) {
fs = new ShaderSource({
defines : ['MRT'],
sources : [AdjustTranslucentFS]
});
uniformMap = {
u_bgColor : function() {
return that._translucentMRTClearCommand.color;
},
u_depthTexture : function() {
return that._depthStencilTexture;
}
};
this._adjustTranslucentCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
} else if (this._translucentMultipassSupport) {
fs = new ShaderSource({
sources : [AdjustTranslucentFS]
});
uniformMap = {
u_bgColor : function() {
return that._translucentMultipassClearCommand.color;
},
u_depthTexture : function() {
return that._depthStencilTexture;
}
};
this._adjustTranslucentCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
uniformMap = {
u_bgColor : function() {
return that._alphaClearCommand.color;
},
u_depthTexture : function() {
return that._depthStencilTexture;
}
};
this._adjustAlphaCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
}
}
this._viewport.width = width;
this._viewport.height = height;
if (!defined(this._rs) || !BoundingRectangle.equals(this._viewport, this._rs.viewport)) {
this._rs = RenderState.fromCache({
viewport : this._viewport
});
}
if (defined(this._compositeCommand)) {
this._compositeCommand.renderState = this._rs;
}
if (this._adjustTranslucentCommand) {
this._adjustTranslucentCommand.renderState = this._rs;
}
if (defined(this._adjustAlphaCommand)) {
this._adjustAlphaCommand.renderState = this._rs;
}
};
var translucentMRTBlend = {
enabled : true,
color : new Color(0.0, 0.0, 0.0, 0.0),
equationRgb : BlendEquation.ADD,
equationAlpha : BlendEquation.ADD,
functionSourceRgb : BlendFunction.ONE,
functionDestinationRgb : BlendFunction.ONE,
functionSourceAlpha : BlendFunction.ZERO,
functionDestinationAlpha : BlendFunction.ONE_MINUS_SOURCE_ALPHA
};
var translucentColorBlend = {
enabled : true,
color : new Color(0.0, 0.0, 0.0, 0.0),
equationRgb : BlendEquation.ADD,
equationAlpha : BlendEquation.ADD,
functionSourceRgb : BlendFunction.ONE,
functionDestinationRgb : BlendFunction.ONE,
functionSourceAlpha : BlendFunction.ONE,
functionDestinationAlpha : BlendFunction.ONE
};
var translucentAlphaBlend = {
enabled : true,
color : new Color(0.0, 0.0, 0.0, 0.0),
equationRgb : BlendEquation.ADD,
equationAlpha : BlendEquation.ADD,
functionSourceRgb : BlendFunction.ZERO,
functionDestinationRgb : BlendFunction.ONE_MINUS_SOURCE_ALPHA,
functionSourceAlpha : BlendFunction.ZERO,
functionDestinationAlpha : BlendFunction.ONE_MINUS_SOURCE_ALPHA
};
function getTranslucentRenderState(context, translucentBlending, cache, renderState) {
var translucentState = cache[renderState.id];
if (!defined(translucentState)) {
var rs = RenderState.getState(renderState);
rs.depthMask = false;
rs.blending = translucentBlending;
translucentState = RenderState.fromCache(rs);
cache[renderState.id] = translucentState;
}
return translucentState;
}
function getTranslucentMRTRenderState(oit, context, renderState) {
return getTranslucentRenderState(context, translucentMRTBlend, oit._translucentRenderStateCache, renderState);
}
function getTranslucentColorRenderState(oit, context, renderState) {
return getTranslucentRenderState(context, translucentColorBlend, oit._translucentRenderStateCache, renderState);
}
function getTranslucentAlphaRenderState(oit, context, renderState) {
return getTranslucentRenderState(context, translucentAlphaBlend, oit._alphaRenderStateCache, renderState);
}
var mrtShaderSource =
' vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n' +
' float ai = czm_gl_FragColor.a;\n' +
' float wzi = czm_alphaWeight(ai);\n' +
' gl_FragData[0] = vec4(Ci * wzi, ai);\n' +
' gl_FragData[1] = vec4(ai * wzi);\n';
var colorShaderSource =
' vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n' +
' float ai = czm_gl_FragColor.a;\n' +
' float wzi = czm_alphaWeight(ai);\n' +
' gl_FragColor = vec4(Ci, ai) * wzi;\n';
var alphaShaderSource =
' float ai = czm_gl_FragColor.a;\n' +
' gl_FragColor = vec4(ai);\n';
function getTranslucentShaderProgram(context, shaderProgram, cache, source) {
var id = shaderProgram.id;
var shader = cache[id];
if (!defined(shader)) {
var attributeLocations = shaderProgram._attributeLocations;
var fs = shaderProgram.fragmentShaderSource.clone();
fs.sources = fs.sources.map(function(source) {
source = ShaderSource.replaceMain(source, 'czm_translucent_main');
source = source.replace(/gl_FragColor/g, 'czm_gl_FragColor');
source = source.replace(/\bdiscard\b/g, 'czm_discard = true');
source = source.replace(/czm_phong/g, 'czm_translucentPhong');
return source;
});
// Discarding the fragment in main is a workaround for ANGLE D3D9
// shader compilation errors.
fs.sources.splice(0, 0,
(source.indexOf('gl_FragData') !== -1 ? '#extension GL_EXT_draw_buffers : enable \n' : '') +
'vec4 czm_gl_FragColor;\n' +
'bool czm_discard = false;\n');
fs.sources.push(
'void main()\n' +
'{\n' +
' czm_translucent_main();\n' +
' if (czm_discard)\n' +
' {\n' +
' discard;\n' +
' }\n' +
source +
'}\n');
shader = ShaderProgram.fromCache({
context : context,
vertexShaderSource : shaderProgram.vertexShaderSource,
fragmentShaderSource : fs,
attributeLocations : attributeLocations
});
cache[id] = shader;
}
return shader;
}
function getTranslucentMRTShaderProgram(oit, context, shaderProgram) {
return getTranslucentShaderProgram(context, shaderProgram, oit._translucentShaderCache, mrtShaderSource);
}
function getTranslucentColorShaderProgram(oit, context, shaderProgram) {
return getTranslucentShaderProgram(context, shaderProgram, oit._translucentShaderCache, colorShaderSource);
}
function getTranslucentAlphaShaderProgram(oit, context, shaderProgram) {
return getTranslucentShaderProgram(context, shaderProgram, oit._alphaShaderCache, alphaShaderSource);
}
function executeTranslucentCommandsSortedMultipass(oit, scene, executeFunction, passState, commands) {
var command;
var renderState;
var shaderProgram;
var j;
var context = scene.context;
var framebuffer = passState.framebuffer;
var length = commands.length;
passState.framebuffer = oit._adjustTranslucentFBO;
oit._adjustTranslucentCommand.execute(context, passState);
passState.framebuffer = oit._adjustAlphaFBO;
oit._adjustAlphaCommand.execute(context, passState);
var debugFramebuffer = oit._opaqueFBO;
passState.framebuffer = oit._translucentFBO;
for (j = 0; j < length; ++j) {
command = commands[j];
if (!defined(command.oit) || command.shaderProgram.id !== command.oit.shaderProgramId) {
command.oit = {
colorRenderState : getTranslucentColorRenderState(oit, context, command.renderState),
alphaRenderState : getTranslucentAlphaRenderState(oit, context, command.renderState),
colorShaderProgram : getTranslucentColorShaderProgram(oit, context, command.shaderProgram),
alphaShaderProgram : getTranslucentAlphaShaderProgram(oit, context, command.shaderProgram),
shaderProgramId : command.shaderProgram.id
};
}
renderState = command.oit.colorRenderState;
shaderProgram = command.oit.colorShaderProgram;
executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer);
}
passState.framebuffer = oit._alphaFBO;
for (j = 0; j < length; ++j) {
command = commands[j];
renderState = command.oit.alphaRenderState;
shaderProgram = command.oit.alphaShaderProgram;
executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer);
}
passState.framebuffer = framebuffer;
}
function executeTranslucentCommandsSortedMRT(oit, scene, executeFunction, passState, commands) {
var context = scene.context;
var framebuffer = passState.framebuffer;
var length = commands.length;
passState.framebuffer = oit._adjustTranslucentFBO;
oit._adjustTranslucentCommand.execute(context, passState);
var debugFramebuffer = oit._opaqueFBO;
passState.framebuffer = oit._translucentFBO;
for (var j = 0; j < length; ++j) {
var command = commands[j];
if (!defined(command.oit) || command.shaderProgram.id !== command.oit.shaderProgramId) {
command.oit = {
translucentRenderState : getTranslucentMRTRenderState(oit, context, command.renderState),
translucentShaderProgram : getTranslucentMRTShaderProgram(oit, context, command.shaderProgram),
shaderProgramId : command.shaderProgram.id
};
}
var renderState = command.oit.translucentRenderState;
var shaderProgram = command.oit.translucentShaderProgram;
executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer);
}
passState.framebuffer = framebuffer;
}
OIT.prototype.executeCommands = function(scene, executeFunction, passState, commands) {
if (this._translucentMRTSupport) {
executeTranslucentCommandsSortedMRT(this, scene, executeFunction, passState, commands);
return;
}
executeTranslucentCommandsSortedMultipass(this, scene, executeFunction, passState, commands);
};
OIT.prototype.execute = function(context, passState) {
this._compositeCommand.execute(context, passState);
};
OIT.prototype.clear = function(context, passState, clearColor) {
var framebuffer = passState.framebuffer;
passState.framebuffer = this._opaqueFBO;
Color.clone(clearColor, this._opaqueClearCommand.color);
this._opaqueClearCommand.execute(context, passState);
passState.framebuffer = this._translucentFBO;
var translucentClearCommand = this._translucentMRTSupport ? this._translucentMRTClearCommand : this._translucentMultipassClearCommand;
translucentClearCommand.execute(context, passState);
if (this._translucentMultipassSupport) {
passState.framebuffer = this._alphaFBO;
this._alphaClearCommand.execute(context, passState);
}
passState.framebuffer = framebuffer;
};
OIT.prototype.isSupported = function() {
return this._translucentMRTSupport || this._translucentMultipassSupport;
};
OIT.prototype.isDestroyed = function() {
return false;
};
OIT.prototype.destroy = function() {
destroyResources(this);
if (defined(this._compositeCommand)) {
this._compositeCommand.shaderProgram = this._compositeCommand.shaderProgram && this._compositeCommand.shaderProgram.destroy();
}
if (defined(this._adjustTranslucentCommand)) {
this._adjustTranslucentCommand.shaderProgram = this._adjustTranslucentCommand.shaderProgram && this._adjustTranslucentCommand.shaderProgram.destroy();
}
if (defined(this._adjustAlphaCommand)) {
this._adjustAlphaCommand.shaderProgram = this._adjustAlphaCommand.shaderProgram && this._adjustAlphaCommand.shaderProgram.destroy();
}
var name;
var cache = this._translucentShaderCache;
for (name in cache) {
if (cache.hasOwnProperty(name) && defined(cache[name])) {
cache[name].destroy();
}
}
this._translucentShaderCache = {};
cache = this._alphaShaderCache;
for (name in cache) {
if (cache.hasOwnProperty(name) && defined(cache[name])) {
cache[name].destroy();
}
}
this._alphaShaderCache = {};
return destroyObject(this);
};
return OIT;
});
|
Source/Scene/OIT.js
|
/*global define*/
define([
'../Core/BoundingRectangle',
'../Core/Color',
'../Core/defined',
'../Core/destroyObject',
'../Core/PixelFormat',
'../Renderer/ClearCommand',
'../Renderer/Framebuffer',
'../Renderer/PixelDatatype',
'../Renderer/RenderState',
'../Renderer/ShaderProgram',
'../Renderer/ShaderSource',
'../Renderer/Texture',
'../Renderer/WebGLConstants',
'../Shaders/AdjustTranslucentFS',
'../Shaders/CompositeOITFS',
'./BlendEquation',
'./BlendFunction'
], function(
BoundingRectangle,
Color,
defined,
destroyObject,
PixelFormat,
ClearCommand,
Framebuffer,
PixelDatatype,
RenderState,
ShaderProgram,
ShaderSource,
Texture,
WebGLConstants,
AdjustTranslucentFS,
CompositeOITFS,
BlendEquation,
BlendFunction) {
'use strict';
/**
* @private
*/
function OIT(context) {
// We support multipass for the Chrome D3D9 backend and ES 2.0 on mobile.
this._translucentMultipassSupport = false;
this._translucentMRTSupport = false;
var extensionsSupported = context.floatingPointTexture && context.depthTexture;
this._translucentMRTSupport = context.drawBuffers && extensionsSupported;
this._translucentMultipassSupport = !this._translucentMRTSupport && extensionsSupported;
this._opaqueFBO = undefined;
this._opaqueTexture = undefined;
this._depthStencilTexture = undefined;
this._accumulationTexture = undefined;
this._translucentFBO = undefined;
this._alphaFBO = undefined;
this._adjustTranslucentFBO = undefined;
this._adjustAlphaFBO = undefined;
this._opaqueClearCommand = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 0.0),
owner : this
});
this._translucentMRTClearCommand = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 1.0),
owner : this
});
this._translucentMultipassClearCommand = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 0.0),
owner : this
});
this._alphaClearCommand = new ClearCommand({
color : new Color(1.0, 1.0, 1.0, 1.0),
owner : this
});
this._translucentRenderStateCache = {};
this._alphaRenderStateCache = {};
this._translucentShaderCache = {};
this._alphaShaderCache = {};
this._compositeCommand = undefined;
this._adjustTranslucentCommand = undefined;
this._adjustAlphaCommand = undefined;
this._viewport = new BoundingRectangle();
this._rs = undefined;
}
function destroyTextures(oit) {
oit._accumulationTexture = oit._accumulationTexture && !oit._accumulationTexture.isDestroyed() && oit._accumulationTexture.destroy();
oit._revealageTexture = oit._revealageTexture && !oit._revealageTexture.isDestroyed() && oit._revealageTexture.destroy();
}
function destroyFramebuffers(oit) {
oit._translucentFBO = oit._translucentFBO && !oit._translucentFBO.isDestroyed() && oit._translucentFBO.destroy();
oit._alphaFBO = oit._alphaFBO && !oit._alphaFBO.isDestroyed() && oit._alphaFBO.destroy();
oit._adjustTranslucentFBO = oit._adjustTranslucentFBO && !oit._adjustTranslucentFBO.isDestroyed() && oit._adjustTranslucentFBO.destroy();
oit._adjustAlphaFBO = oit._adjustAlphaFBO && !oit._adjustAlphaFBO.isDestroyed() && oit._adjustAlphaFBO.destroy();
}
function destroyResources(oit) {
destroyTextures(oit);
destroyFramebuffers(oit);
}
function updateTextures(oit, context, width, height) {
destroyTextures(oit);
oit._accumulationTexture = new Texture({
context : context,
width : width,
height : height,
pixelFormat : PixelFormat.RGBA,
pixelDatatype : PixelDatatype.FLOAT
});
oit._revealageTexture = new Texture({
context : context,
width : width,
height : height,
pixelFormat : PixelFormat.RGBA,
pixelDatatype : PixelDatatype.FLOAT
});
}
function updateFramebuffers(oit, context) {
destroyFramebuffers(oit);
var completeFBO = WebGLConstants.FRAMEBUFFER_COMPLETE;
var supported = true;
// if MRT is supported, attempt to make an FBO with multiple color attachments
if (oit._translucentMRTSupport) {
oit._translucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture, oit._revealageTexture],
depthStencilTexture : oit._depthStencilTexture,
destroyAttachments : false
});
oit._adjustTranslucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture, oit._revealageTexture],
destroyAttachments : false
});
if (oit._translucentFBO.status !== completeFBO || oit._adjustTranslucentFBO.status !== completeFBO) {
destroyFramebuffers(oit);
oit._translucentMRTSupport = false;
}
}
// either MRT isn't supported or FBO creation failed, attempt multipass
if (!oit._translucentMRTSupport) {
oit._translucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture],
depthStencilTexture : oit._depthStencilTexture,
destroyAttachments : false
});
oit._alphaFBO = new Framebuffer({
context : context,
colorTextures : [oit._revealageTexture],
depthStencilTexture : oit._depthStencilTexture,
destroyAttachments : false
});
oit._adjustTranslucentFBO = new Framebuffer({
context : context,
colorTextures : [oit._accumulationTexture],
destroyAttachments : false
});
oit._adjustAlphaFBO = new Framebuffer({
context : context,
colorTextures : [oit._revealageTexture],
destroyAttachments : false
});
var translucentComplete = oit._translucentFBO.status === completeFBO;
var alphaComplete = oit._alphaFBO.status === completeFBO;
var adjustTranslucentComplete = oit._adjustTranslucentFBO.status === completeFBO;
var adjustAlphaComplete = oit._adjustAlphaFBO.status === completeFBO;
if (!translucentComplete || !alphaComplete || !adjustTranslucentComplete || !adjustAlphaComplete) {
destroyResources(oit);
oit._translucentMultipassSupport = false;
supported = false;
}
}
return supported;
}
OIT.prototype.update = function(context, framebuffer) {
if (!this.isSupported()) {
return;
}
this._opaqueFBO = framebuffer;
this._opaqueTexture = framebuffer.getColorTexture(0);
this._depthStencilTexture = framebuffer.depthStencilTexture;
var width = this._opaqueTexture.width;
var height = this._opaqueTexture.height;
var accumulationTexture = this._accumulationTexture;
var textureChanged = !defined(accumulationTexture) || accumulationTexture.width !== width || accumulationTexture.height !== height;
if (textureChanged) {
updateTextures(this, context, width, height);
}
if (!defined(this._translucentFBO) || textureChanged) {
if (!updateFramebuffers(this, context)) {
// framebuffer creation failed
return;
}
}
var that = this;
var fs;
var uniformMap;
if (!defined(this._compositeCommand)) {
fs = new ShaderSource({
sources : [CompositeOITFS]
});
if (this._translucentMRTSupport) {
fs.defines.push('MRT');
}
uniformMap = {
u_opaque : function() {
return that._opaqueTexture;
},
u_accumulation : function() {
return that._accumulationTexture;
},
u_revealage : function() {
return that._revealageTexture;
}
};
this._compositeCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
}
if (!defined(this._adjustTranslucentCommand)) {
if (this._translucentMRTSupport) {
fs = new ShaderSource({
defines : ['MRT'],
sources : [AdjustTranslucentFS]
});
uniformMap = {
u_bgColor : function() {
return that._translucentMRTClearCommand.color;
},
u_depthTexture : function() {
return that._depthStencilTexture;
}
};
this._adjustTranslucentCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
} else if (this._translucentMultipassSupport) {
fs = new ShaderSource({
sources : [AdjustTranslucentFS]
});
uniformMap = {
u_bgColor : function() {
return that._translucentMultipassClearCommand.color;
},
u_depthTexture : function() {
return that._depthStencilTexture;
}
};
this._adjustTranslucentCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
uniformMap = {
u_bgColor : function() {
return that._alphaClearCommand.color;
},
u_depthTexture : function() {
return that._depthStencilTexture;
}
};
this._adjustAlphaCommand = context.createViewportQuadCommand(fs, {
uniformMap : uniformMap,
owner : this
});
}
}
this._viewport.width = width;
this._viewport.height = height;
if (!defined(this._rs) || !BoundingRectangle.equals(this._viewport, this._rs.viewport)) {
this._rs = RenderState.fromCache({
viewport : this._viewport
});
}
if (defined(this._compositeCommand)) {
this._compositeCommand.renderState = this._rs;
}
if (this._adjustTranslucentCommand) {
this._adjustTranslucentCommand.renderstate = this._rs;
}
if (defined(this._adjustAlphaCommand)) {
this._adjustAlphaCommand.renderState = this._rs;
}
};
var translucentMRTBlend = {
enabled : true,
color : new Color(0.0, 0.0, 0.0, 0.0),
equationRgb : BlendEquation.ADD,
equationAlpha : BlendEquation.ADD,
functionSourceRgb : BlendFunction.ONE,
functionDestinationRgb : BlendFunction.ONE,
functionSourceAlpha : BlendFunction.ZERO,
functionDestinationAlpha : BlendFunction.ONE_MINUS_SOURCE_ALPHA
};
var translucentColorBlend = {
enabled : true,
color : new Color(0.0, 0.0, 0.0, 0.0),
equationRgb : BlendEquation.ADD,
equationAlpha : BlendEquation.ADD,
functionSourceRgb : BlendFunction.ONE,
functionDestinationRgb : BlendFunction.ONE,
functionSourceAlpha : BlendFunction.ONE,
functionDestinationAlpha : BlendFunction.ONE
};
var translucentAlphaBlend = {
enabled : true,
color : new Color(0.0, 0.0, 0.0, 0.0),
equationRgb : BlendEquation.ADD,
equationAlpha : BlendEquation.ADD,
functionSourceRgb : BlendFunction.ZERO,
functionDestinationRgb : BlendFunction.ONE_MINUS_SOURCE_ALPHA,
functionSourceAlpha : BlendFunction.ZERO,
functionDestinationAlpha : BlendFunction.ONE_MINUS_SOURCE_ALPHA
};
function getTranslucentRenderState(context, translucentBlending, cache, renderState) {
var translucentState = cache[renderState.id];
if (!defined(translucentState)) {
var rs = RenderState.getState(renderState);
rs.depthMask = false;
rs.blending = translucentBlending;
translucentState = RenderState.fromCache(rs);
cache[renderState.id] = translucentState;
}
return translucentState;
}
function getTranslucentMRTRenderState(oit, context, renderState) {
return getTranslucentRenderState(context, translucentMRTBlend, oit._translucentRenderStateCache, renderState);
}
function getTranslucentColorRenderState(oit, context, renderState) {
return getTranslucentRenderState(context, translucentColorBlend, oit._translucentRenderStateCache, renderState);
}
function getTranslucentAlphaRenderState(oit, context, renderState) {
return getTranslucentRenderState(context, translucentAlphaBlend, oit._alphaRenderStateCache, renderState);
}
var mrtShaderSource =
' vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n' +
' float ai = czm_gl_FragColor.a;\n' +
' float wzi = czm_alphaWeight(ai);\n' +
' gl_FragData[0] = vec4(Ci * wzi, ai);\n' +
' gl_FragData[1] = vec4(ai * wzi);\n';
var colorShaderSource =
' vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n' +
' float ai = czm_gl_FragColor.a;\n' +
' float wzi = czm_alphaWeight(ai);\n' +
' gl_FragColor = vec4(Ci, ai) * wzi;\n';
var alphaShaderSource =
' float ai = czm_gl_FragColor.a;\n' +
' gl_FragColor = vec4(ai);\n';
function getTranslucentShaderProgram(context, shaderProgram, cache, source) {
var id = shaderProgram.id;
var shader = cache[id];
if (!defined(shader)) {
var attributeLocations = shaderProgram._attributeLocations;
var fs = shaderProgram.fragmentShaderSource.clone();
fs.sources = fs.sources.map(function(source) {
source = ShaderSource.replaceMain(source, 'czm_translucent_main');
source = source.replace(/gl_FragColor/g, 'czm_gl_FragColor');
source = source.replace(/\bdiscard\b/g, 'czm_discard = true');
source = source.replace(/czm_phong/g, 'czm_translucentPhong');
return source;
});
// Discarding the fragment in main is a workaround for ANGLE D3D9
// shader compilation errors.
fs.sources.splice(0, 0,
(source.indexOf('gl_FragData') !== -1 ? '#extension GL_EXT_draw_buffers : enable \n' : '') +
'vec4 czm_gl_FragColor;\n' +
'bool czm_discard = false;\n');
fs.sources.push(
'void main()\n' +
'{\n' +
' czm_translucent_main();\n' +
' if (czm_discard)\n' +
' {\n' +
' discard;\n' +
' }\n' +
source +
'}\n');
shader = ShaderProgram.fromCache({
context : context,
vertexShaderSource : shaderProgram.vertexShaderSource,
fragmentShaderSource : fs,
attributeLocations : attributeLocations
});
cache[id] = shader;
}
return shader;
}
function getTranslucentMRTShaderProgram(oit, context, shaderProgram) {
return getTranslucentShaderProgram(context, shaderProgram, oit._translucentShaderCache, mrtShaderSource);
}
function getTranslucentColorShaderProgram(oit, context, shaderProgram) {
return getTranslucentShaderProgram(context, shaderProgram, oit._translucentShaderCache, colorShaderSource);
}
function getTranslucentAlphaShaderProgram(oit, context, shaderProgram) {
return getTranslucentShaderProgram(context, shaderProgram, oit._alphaShaderCache, alphaShaderSource);
}
function executeTranslucentCommandsSortedMultipass(oit, scene, executeFunction, passState, commands) {
var command;
var renderState;
var shaderProgram;
var j;
var context = scene.context;
var framebuffer = passState.framebuffer;
var length = commands.length;
passState.framebuffer = oit._adjustTranslucentFBO;
oit._adjustTranslucentCommand.execute(context, passState);
passState.framebuffer = oit._adjustAlphaFBO;
oit._adjustAlphaCommand.execute(context, passState);
var debugFramebuffer = oit._opaqueFBO;
passState.framebuffer = oit._translucentFBO;
for (j = 0; j < length; ++j) {
command = commands[j];
if (!defined(command.oit) || command.shaderProgram.id !== command.oit.shaderProgramId) {
command.oit = {
colorRenderState : getTranslucentColorRenderState(oit, context, command.renderState),
alphaRenderState : getTranslucentAlphaRenderState(oit, context, command.renderState),
colorShaderProgram : getTranslucentColorShaderProgram(oit, context, command.shaderProgram),
alphaShaderProgram : getTranslucentAlphaShaderProgram(oit, context, command.shaderProgram),
shaderProgramId : command.shaderProgram.id
};
}
renderState = command.oit.colorRenderState;
shaderProgram = command.oit.colorShaderProgram;
executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer);
}
passState.framebuffer = oit._alphaFBO;
for (j = 0; j < length; ++j) {
command = commands[j];
renderState = command.oit.alphaRenderState;
shaderProgram = command.oit.alphaShaderProgram;
executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer);
}
passState.framebuffer = framebuffer;
}
function executeTranslucentCommandsSortedMRT(oit, scene, executeFunction, passState, commands) {
var context = scene.context;
var framebuffer = passState.framebuffer;
var length = commands.length;
passState.framebuffer = oit._adjustTranslucentFBO;
oit._adjustTranslucentCommand.execute(context, passState);
var debugFramebuffer = oit._opaqueFBO;
passState.framebuffer = oit._translucentFBO;
for (var j = 0; j < length; ++j) {
var command = commands[j];
if (!defined(command.oit) || command.shaderProgram.id !== command.oit.shaderProgramId) {
command.oit = {
translucentRenderState : getTranslucentMRTRenderState(oit, context, command.renderState),
translucentShaderProgram : getTranslucentMRTShaderProgram(oit, context, command.shaderProgram),
shaderProgramId : command.shaderProgram.id
};
}
var renderState = command.oit.translucentRenderState;
var shaderProgram = command.oit.translucentShaderProgram;
executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer);
}
passState.framebuffer = framebuffer;
}
OIT.prototype.executeCommands = function(scene, executeFunction, passState, commands) {
if (this._translucentMRTSupport) {
executeTranslucentCommandsSortedMRT(this, scene, executeFunction, passState, commands);
return;
}
executeTranslucentCommandsSortedMultipass(this, scene, executeFunction, passState, commands);
};
OIT.prototype.execute = function(context, passState) {
this._compositeCommand.execute(context, passState);
};
OIT.prototype.clear = function(context, passState, clearColor) {
var framebuffer = passState.framebuffer;
passState.framebuffer = this._opaqueFBO;
Color.clone(clearColor, this._opaqueClearCommand.color);
this._opaqueClearCommand.execute(context, passState);
passState.framebuffer = this._translucentFBO;
var translucentClearCommand = this._translucentMRTSupport ? this._translucentMRTClearCommand : this._translucentMultipassClearCommand;
translucentClearCommand.execute(context, passState);
if (this._translucentMultipassSupport) {
passState.framebuffer = this._alphaFBO;
this._alphaClearCommand.execute(context, passState);
}
passState.framebuffer = framebuffer;
};
OIT.prototype.isSupported = function() {
return this._translucentMRTSupport || this._translucentMultipassSupport;
};
OIT.prototype.isDestroyed = function() {
return false;
};
OIT.prototype.destroy = function() {
destroyResources(this);
if (defined(this._compositeCommand)) {
this._compositeCommand.shaderProgram = this._compositeCommand.shaderProgram && this._compositeCommand.shaderProgram.destroy();
}
if (defined(this._adjustTranslucentCommand)) {
this._adjustTranslucentCommand.shaderProgram = this._adjustTranslucentCommand.shaderProgram && this._adjustTranslucentCommand.shaderProgram.destroy();
}
if (defined(this._adjustAlphaCommand)) {
this._adjustAlphaCommand.shaderProgram = this._adjustAlphaCommand.shaderProgram && this._adjustAlphaCommand.shaderProgram.destroy();
}
var name;
var cache = this._translucentShaderCache;
for (name in cache) {
if (cache.hasOwnProperty(name) && defined(cache[name])) {
cache[name].destroy();
}
}
this._translucentShaderCache = {};
cache = this._alphaShaderCache;
for (name in cache) {
if (cache.hasOwnProperty(name) && defined(cache[name])) {
cache[name].destroy();
}
}
this._alphaShaderCache = {};
return destroyObject(this);
};
return OIT;
});
|
Fix typo setting a render state for OIT.
|
Source/Scene/OIT.js
|
Fix typo setting a render state for OIT.
|
<ide><path>ource/Scene/OIT.js
<ide> }
<ide>
<ide> if (this._adjustTranslucentCommand) {
<del> this._adjustTranslucentCommand.renderstate = this._rs;
<add> this._adjustTranslucentCommand.renderState = this._rs;
<ide> }
<ide>
<ide> if (defined(this._adjustAlphaCommand)) {
|
|
JavaScript
|
mit
|
cc9c018e1de524f55ecbe499375feb4700efdf72
| 0 |
pogosandbox/pogobuf
|
/* eslint no-underscore-dangle: ["error", { "allow": ["_eventId"] }] */
const request = require('request');
const Promise = require('bluebird');
const querystring = require('querystring');
const url = require('url');
const PTC_CLIENT_SECRET = 'w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR';
/**
* Pokémon Trainer Club login client.
* @class PTCLogin
* @memberof pogobuf
*/
function PTCLogin() {
if (!(this instanceof PTCLogin)) {
return new PTCLogin();
}
const self = this;
this.proxy = undefined;
this.cookies = undefined;
/**
* Reset login so it can be reused
*/
this.reset = function() {
self.cookies = request.jar();
self.request = request.defaults({
headers: {
'Accept': '*/*',
'User-Agent': 'pokemongo/0 CFNetwork/811.5.4 Darwin/16.7.0',
'Accept-Language': 'en-us',
'Accept-Encoding': 'gzip, deflate',
'X-Unity-Version': '2017.1.2f1',
},
gzip: true,
jar: self.cookies,
});
Promise.promisifyAll(self.request);
};
this.reset();
/**
* Performs the PTC login process and returns a Promise that will be resolved with the
* auth token.
* @param {string} username
* @param {string} password
* @return {Promise}
*/
this.login = function(username, password) {
return self.init()
.then(data => self.auth(data, username, password))
.then(data => self.getAccessToken(data));
};
this.init = function() {
return self.request.getAsync({
url: 'https://sso.pokemon.com/sso/login',
qs: {
service: 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize',
locale: 'en_US',
},
proxy: self.proxy,
})
.then(response => {
if (response.statusCode !== 200) {
throw new Error(`Status ${response.statusCode} received from PTC login`);
}
let sessionResponse = null;
try {
sessionResponse = JSON.parse(response.body);
} catch (e) {
throw new Error('Unexpected response received from PTC login (invalid json)');
}
if (!sessionResponse || !sessionResponse.lt && !sessionResponse.execution) {
throw new Error('No session data received from PTC login');
}
return sessionResponse;
});
};
this.auth = function(sessionData, username, password) {
sessionData._eventId = 'submit';
sessionData.username = username;
sessionData.password = password;
sessionData.locale = 'en_US';
return self.request.postAsync({
url: 'https://sso.pokemon.com/sso/login',
qs: {
service: 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize',
locale: 'en_US',
},
form: sessionData,
proxy: self.proxy,
}).then(response => {
if (response.statusCode === 302 && response.headers.location) {
const ticketURL = url.parse(response.headers.location, true);
if (!ticketURL || !ticketURL.query.ticket) {
throw new Error('No login ticket received from PTC login');
}
return ticketURL.query.ticket;
} else {
let data = {};
try {
data = JSON.parse(response.body);
} catch (e) { /* nothing */ }
if (data.errors) {
throw new Error(data.errors[0]);
} else {
throw new Error('Incorrect response from PTC.');
}
}
});
};
this.getAccessToken = function(ticket) {
return self.request.postAsync({
url: 'https://sso.pokemon.com/sso/oauth2.0/accessToken',
form: {
client_id: 'mobile-app_pokemon-go',
redirect_uri: 'https://www.nianticlabs.com/pokemongo/error',
client_secret: PTC_CLIENT_SECRET,
grant_type: 'refresh_token',
code: ticket,
},
proxy: self.proxy,
}).then(response => {
if (response.statusCode !== 200) {
throw new Error(`Status ${response.statusCode} received from PTC login`);
}
const resp = querystring.parse(response.body);
return resp.access_token;
});
};
/**
* Sets a proxy address to use for PTC logins.
* @param {string} proxy
*/
this.setProxy = function(proxy) {
self.proxy = proxy;
};
}
module.exports = PTCLogin;
|
pogobuf/pogobuf.ptclogin.js
|
/* eslint no-underscore-dangle: ["error", { "allow": ["_eventId"] }] */
const request = require('request');
const Promise = require('bluebird');
const querystring = require('querystring');
const PTC_CLIENT_SECRET = 'w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR';
/**
* Pokémon Trainer Club login client.
* @class PTCLogin
* @memberof pogobuf
*/
function PTCLogin() {
if (!(this instanceof PTCLogin)) {
return new PTCLogin();
}
const self = this;
this.proxy = undefined;
this.cookies = undefined;
/**
* Reset login so it can be reused
*/
this.reset = function() {
self.cookies = request.jar();
self.request = request.defaults({
headers: {
'Accept': '*/*',
'User-Agent': 'pokemongo/0 CFNetwork/811.5.4 Darwin/16.7.0',
'Accept-Language': 'en-us',
'Accept-Encoding': 'gzip, deflate',
'X-Unity-Version': '2017.1.2f1',
},
gzip: true,
jar: self.cookies,
});
Promise.promisifyAll(self.request);
};
this.reset();
/**
* Performs the PTC login process and returns a Promise that will be resolved with the
* auth token.
* @param {string} username
* @param {string} password
* @return {Promise}
*/
this.login = function(username, password) {
// return self.getSession()
// .then(sessionData => self.getTicket(sessionData, username, password));
return self.init()
.then(data => self.auth(data, username, password))
.then(data => self.getAccessToken(data));
};
/**
* Starts a session on the PTC website and returns a Promise that will be resolved with
* the session parameters lt and execution.
* @private
* @return {Promise}
*/
this.getSession = function() {
return self.request.getAsync({
url: 'https://sso.pokemon.com/sso/oauth2.0/authorize',
qs: {
client_id: 'mobile-app_pokemon-go',
redirect_uri: 'https://www.nianticlabs.com/pokemongo/error',
locale: 'en_US',
},
proxy: self.proxy,
})
.then(response => {
if (response.statusCode !== 200) {
throw new Error(`Status ${response.statusCode} received from PTC login`);
}
let sessionResponse = null;
try {
sessionResponse = JSON.parse(response.body);
} catch (e) {
throw new Error('Unexpected response received from PTC login (invalid json)');
}
if (!sessionResponse || !sessionResponse.lt && !sessionResponse.execution) {
throw new Error('No session data received from PTC login');
}
return sessionResponse;
});
};
/**
* Performs the actual login on the PTC website and returns a Promise that will be resolved
* with a login ticket.
* @private
* @param {Object} sessionData - Session parameters from the {@link #getSession} method
* @param {string} username
* @param {string} password
* @return {Promise}
*/
this.getTicket = function(sessionData, username, password) {
sessionData._eventId = 'submit';
sessionData.username = username;
sessionData.password = password;
sessionData.locale = 'en_US';
return self.request.postAsync({
url: 'https://sso.pokemon.com/sso/login',
qs: {
service: 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize',
},
form: sessionData,
proxy: self.proxy,
})
.then(response => {
if (response.headers['set-cookie'] && response.headers['set-cookie'].length > 0) {
var cookieString = response.headers['set-cookie'].filter(c => c.startsWith('CASTGC'));
if (cookieString && cookieString.length > 0) {
const cookie = request.cookie(cookieString[0]);
return cookie.value;
}
}
// something went wrong
if (response.body) {
if (response.body.indexOf('password is incorrect') >= 0) {
throw new Error('Invalid PTC login or password.');
} if (response.body.indexOf('failed to log in correctly too many times') >= 0) {
throw new Error('Account temporarily disabled, please check your password.');
}
}
// don't know what happend
throw new Error('Something went wrong during PTC login.');
});
};
this.init = function() {
return self.request.getAsync({
url: 'https://sso.pokemon.com/sso/login',
qs: {
service: 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize',
locale: 'en_US',
},
proxy: self.proxy,
})
.then(response => {
if (response.statusCode !== 200) {
throw new Error(`Status ${response.statusCode} received from PTC login`);
}
let sessionResponse = null;
try {
sessionResponse = JSON.parse(response.body);
} catch (e) {
throw new Error('Unexpected response received from PTC login (invalid json)');
}
if (!sessionResponse || !sessionResponse.lt && !sessionResponse.execution) {
throw new Error('No session data received from PTC login');
}
return sessionResponse;
});
};
this.auth = function(sessionData, username, password) {
sessionData._eventId = 'submit';
sessionData.username = username;
sessionData.password = password;
sessionData.locale = 'en_US';
return self.request.postAsync({
url: 'https://sso.pokemon.com/sso/login',
qs: {
service: 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize',
locale: 'en_US',
},
form: sessionData,
proxy: self.proxy,
}).then(response => {
if (response.statusCode === 302 && response.headers) {
const location = response.headers.location;
return location.substring(location.indexOf('?ticket=') + '?ticket='.length);
} else {
let data;
try {
data = JSON.parse(response.body);
} catch (e) {
throw new Error('Incorrect response from PTC.');
}
if (data.errors) {
throw new Error(data.errors[0]);
} else {
throw new Error('Incorrect response from PTC.');
}
}
});
};
this.getAccessToken = function(ticket) {
return self.request.postAsync({
url: 'https://sso.pokemon.com/sso/oauth2.0/accessToken',
form: {
client_id: 'mobile-app_pokemon-go',
redirect_uri: 'https://www.nianticlabs.com/pokemongo/error',
client_secret: PTC_CLIENT_SECRET,
grant_type: 'refresh_token',
code: ticket,
},
proxy: self.proxy,
}).then(response => {
if (response.statusCode !== 200) {
throw new Error(`Status ${response.statusCode} received from PTC login`);
}
const resp = querystring.parse(response.body);
return resp.access_token;
});
};
/**
* Sets a proxy address to use for PTC logins.
* @param {string} proxy
*/
this.setProxy = function(proxy) {
self.proxy = proxy;
};
}
module.exports = PTCLogin;
|
ptc login clean up
|
pogobuf/pogobuf.ptclogin.js
|
ptc login clean up
|
<ide><path>ogobuf/pogobuf.ptclogin.js
<ide> const request = require('request');
<ide> const Promise = require('bluebird');
<ide> const querystring = require('querystring');
<add>const url = require('url');
<ide>
<ide> const PTC_CLIENT_SECRET = 'w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR';
<ide>
<ide> * @return {Promise}
<ide> */
<ide> this.login = function(username, password) {
<del> // return self.getSession()
<del> // .then(sessionData => self.getTicket(sessionData, username, password));
<ide> return self.init()
<ide> .then(data => self.auth(data, username, password))
<ide> .then(data => self.getAccessToken(data));
<del> };
<del>
<del> /**
<del> * Starts a session on the PTC website and returns a Promise that will be resolved with
<del> * the session parameters lt and execution.
<del> * @private
<del> * @return {Promise}
<del> */
<del> this.getSession = function() {
<del> return self.request.getAsync({
<del> url: 'https://sso.pokemon.com/sso/oauth2.0/authorize',
<del> qs: {
<del> client_id: 'mobile-app_pokemon-go',
<del> redirect_uri: 'https://www.nianticlabs.com/pokemongo/error',
<del> locale: 'en_US',
<del> },
<del> proxy: self.proxy,
<del> })
<del> .then(response => {
<del> if (response.statusCode !== 200) {
<del> throw new Error(`Status ${response.statusCode} received from PTC login`);
<del> }
<del>
<del> let sessionResponse = null;
<del> try {
<del> sessionResponse = JSON.parse(response.body);
<del> } catch (e) {
<del> throw new Error('Unexpected response received from PTC login (invalid json)');
<del> }
<del>
<del> if (!sessionResponse || !sessionResponse.lt && !sessionResponse.execution) {
<del> throw new Error('No session data received from PTC login');
<del> }
<del>
<del> return sessionResponse;
<del> });
<del> };
<del>
<del> /**
<del> * Performs the actual login on the PTC website and returns a Promise that will be resolved
<del> * with a login ticket.
<del> * @private
<del> * @param {Object} sessionData - Session parameters from the {@link #getSession} method
<del> * @param {string} username
<del> * @param {string} password
<del> * @return {Promise}
<del> */
<del> this.getTicket = function(sessionData, username, password) {
<del> sessionData._eventId = 'submit';
<del> sessionData.username = username;
<del> sessionData.password = password;
<del> sessionData.locale = 'en_US';
<del>
<del> return self.request.postAsync({
<del> url: 'https://sso.pokemon.com/sso/login',
<del> qs: {
<del> service: 'https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize',
<del> },
<del> form: sessionData,
<del> proxy: self.proxy,
<del> })
<del> .then(response => {
<del> if (response.headers['set-cookie'] && response.headers['set-cookie'].length > 0) {
<del> var cookieString = response.headers['set-cookie'].filter(c => c.startsWith('CASTGC'));
<del> if (cookieString && cookieString.length > 0) {
<del> const cookie = request.cookie(cookieString[0]);
<del> return cookie.value;
<del> }
<del> }
<del>
<del> // something went wrong
<del> if (response.body) {
<del> if (response.body.indexOf('password is incorrect') >= 0) {
<del> throw new Error('Invalid PTC login or password.');
<del> } if (response.body.indexOf('failed to log in correctly too many times') >= 0) {
<del> throw new Error('Account temporarily disabled, please check your password.');
<del> }
<del> }
<del>
<del> // don't know what happend
<del> throw new Error('Something went wrong during PTC login.');
<del> });
<ide> };
<ide>
<ide> this.init = function() {
<ide> form: sessionData,
<ide> proxy: self.proxy,
<ide> }).then(response => {
<del> if (response.statusCode === 302 && response.headers) {
<del> const location = response.headers.location;
<del> return location.substring(location.indexOf('?ticket=') + '?ticket='.length);
<add> if (response.statusCode === 302 && response.headers.location) {
<add> const ticketURL = url.parse(response.headers.location, true);
<add> if (!ticketURL || !ticketURL.query.ticket) {
<add> throw new Error('No login ticket received from PTC login');
<add> }
<add> return ticketURL.query.ticket;
<ide> } else {
<del> let data;
<add> let data = {};
<ide> try {
<ide> data = JSON.parse(response.body);
<del> } catch (e) {
<del> throw new Error('Incorrect response from PTC.');
<del> }
<add> } catch (e) { /* nothing */ }
<ide> if (data.errors) {
<ide> throw new Error(data.errors[0]);
<ide> } else {
|
|
JavaScript
|
mit
|
591593dd493c1552fd81a0a386d21be635d7e901
| 0 |
hinaloe/jqm-demo-ja,arschmitz/uglymongrel-jquery-mobile,arschmitz/uglymongrel-jquery-mobile,startxfr/jquery-mobile,arschmitz/jquery-mobile,rwaldron/jquery-mobile,startxfr/jquery-mobile,hinaloe/jqm-demo-ja,arschmitz/jquery-mobile,hinaloe/jqm-demo-ja,arschmitz/jquery-mobile,rwaldron/jquery-mobile,npmcomponent/cbou-jquery-mobile,npmcomponent/cbou-jquery-mobile,startxfr/jquery-mobile,npmcomponent/cbou-jquery-mobile,arschmitz/uglymongrel-jquery-mobile
|
/*
* jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt,
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined ) {
//define vars for interal use
var $window = $(window),
$html = $('html'),
$head = $('head'),
//url path helpers for use in relative url management
path = {
//get path from current hash, or from a file path
get: function( newPath ){
if( newPath == undefined ){
newPath = location.hash;
}
return path.stripHash( newPath ).replace(/[^\/]*\.[^\/*]+$/, '');
},
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ){
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//set location hash to path
set: function( path ){
location.hash = path;
},
//location pathname from intial directory request
origin: '',
setOrigin: function(){
path.origin = path.get( location.protocol + '//' + location.host + location.pathname );
},
//prefix a relative url with the current path
makeAbsolute: function( url ){
return path.get() + url;
},
//return a url path with the window's location protocol/hostname removed
clean: function( url ){
return url.replace( location.protocol + "//" + location.host, "");
},
//just return the url without an initial #
stripHash: function( url ){
return url.replace( /^#/, "" );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ){
return path.hasProtocol( path.clean( url ) );
},
hasProtocol: function( url ){
return /^(:?\w+:)/.test( url );
},
//check if the url is relative
isRelative: function( url ){
return /^[^\/|#]/.test( url ) && !path.hasProtocol( url );
},
isEmbeddedPage: function( url ){
return /^#/.test( url );
}
},
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = {
//array of pages that are visited during a single page load. each has a url and optional transition
stack: [],
//maintain an index number for the active page in the stack
activeIndex: 0,
//get active
getActive: function(){
return urlHistory.stack[ urlHistory.activeIndex ];
},
getPrev: function(){
return urlHistory.stack[ urlHistory.activeIndex - 1 ];
},
getNext: function(){
return urlHistory.stack[ urlHistory.activeIndex + 1 ];
},
// addNew is used whenever a new page is added
addNew: function( url, transition ){
//if there's forward history, wipe it
if( urlHistory.getNext() ){
urlHistory.clearForward();
}
urlHistory.stack.push( {url : url, transition: transition } );
urlHistory.activeIndex = urlHistory.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function(){
urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
},
//enable/disable hashchange event listener
//toggled internally when location.hash is updated to match the url of a successful page load
listeningEnabled: true
},
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//contains role for next page, if defined on clicked link via data-rel
nextPageRole = null,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog";
//existing base tag?
var $base = $head.children("base"),
hostURL = location.protocol + '//' + location.host,
docLocation = path.get( hostURL + location.pathname ),
docBase = docLocation;
if ($base.length){
var href = $base.attr("href");
if (href){
if (href.search(/^[^:/]+:\/\/[^/]+\/?/) == -1){
//the href is not absolute, we need to turn it into one
//so that we can turn paths stored in our location hash into
//relative paths.
if (href.charAt(0) == '/'){
//site relative url
docBase = hostURL + href;
}
else {
//the href is a document relative url
docBase = docLocation + href;
//XXX: we need some code here to calculate the final path
// just in case the docBase contains up-level (../) references.
}
}
else {
//the href is an absolute url
docBase = href;
}
}
//make sure docBase ends with a slash
docBase = docBase + (docBase.charAt(docBase.length - 1) == '/' ? ' ' : '/');
}
//base element management, defined depending on dynamic base tag support
base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ($base.length ? $base : $("<base>", { href: docBase }).prependTo( $head )),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ){
base.element.attr('href', docBase + path.get( href ));
},
//set the generated BASE element's href attribute to a new page's base path
reset: function(){
base.element.attr('href', docBase );
}
} : undefined;
//set location pathname from intial directory request
path.setOrigin();
/*
internal utility functions
--------------------------------------*/
//direct focus to the page title, or otherwise first focusable element
function reFocus( page ){
var pageTitle = page.find( ".ui-title:eq(0)" );
if( pageTitle.length ){
pageTitle.focus();
}
else{
page.find( focusable ).eq(0).focus();
}
};
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ){
if( !!$activeClickedLink && (!$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval )){
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
};
//animation complete callback
$.fn.animationComplete = function( callback ){
if($.support.cssTransitions){
return $(this).one('webkitAnimationEnd', callback);
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout(callback, 0);
}
};
/* exposed $.mobile methods */
//update location.hash, with or without triggering hashchange event
//TODO - deprecate this one at 1.0
$.mobile.updateHash = path.set;
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//url stack, useful when plugins need to be aware of previous pages viewed
//TODO: deprecate this one at 1.0
$.mobile.urlstack = urlHistory.stack;
//history stack
$.mobile.urlHistory = urlHistory;
// changepage function
// TODO : consider moving args to an object hash
$.mobile.changePage = function( to, transition, reverse, changeHash, fromHashChange ){
//from is always the currently viewed page
var toIsArray = $.type(to) === "array",
toIsObject = $.type(to) === "object",
from = toIsArray ? to[0] : $.mobile.activePage,
to = toIsArray ? to[1] : to,
url = fileUrl = $.type(to) === "string" ? path.stripHash( to ) : "",
data = undefined,
type = 'get',
isFormRequest = false,
duplicateCachedPage = null,
currPage = urlHistory.getActive(),
back = false,
forward = false;
// If we are trying to transition to the same page that we are currently on ignore the request.
// an illegal same page request is defined by the current page being the same as the url, as long as there's history
// and to is not an array or object (those are allowed to be "same")
if( currPage && urlHistory.stack.length > 1 && currPage.url === url && !toIsArray && !toIsObject ) {
return;
}
// if the changePage was sent from a hashChange event
// guess if it came from the history menu
if( fromHashChange ){
// check if url is in history and if it's ahead or behind current page
$.each( urlHistory.stack, function( i ){
//if the url is in the stack, it's a forward or a back
if( this.url == url ){
urlIndex = i;
//define back and forward by whether url is older or newer than current page
back = i < urlHistory.activeIndex;
//forward set to opposite of back
forward = !back;
//reset activeIndex to this one
urlHistory.activeIndex = i;
}
});
//if it's a back, use reverse animation
if( back ){
reverse = true;
transition = transition || currPage.transition;
}
else if ( forward ){
transition = transition || urlHistory.getActive().transition;
}
}
if( toIsObject && to.url ){
url = to.url,
data = to.data,
type = to.type,
isFormRequest = true;
//make get requests bookmarkable
if( data && type == 'get' ){
if($.type( data ) == "object" ){
data = $.param(data);
}
url += "?" + data;
data = undefined;
}
}
//reset base to pathname for new request
if(base){ base.reset(); }
//kill the keyboard
$( window.document.activeElement ).add(':focus').blur();
function defaultTransition(){
if(transition === undefined){
transition = $.mobile.defaultTransition;
}
}
//function for transitioning between two existing pages
function transitionPages() {
$.mobile.silentScroll();
//get current scroll distance
var currScroll = $window.scrollTop(),
perspectiveTransitions = ["flip"],
pageContainerClasses = [];
//support deep-links to generated sub-pages
if( url.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ){
to = $( "[data-url='" + url + "']" );
}
//set as data for returning to that spot
from.data('lastScroll', currScroll);
//trigger before show/hide events
from.data("page")._trigger("beforehide", {nextPage: to});
to.data("page")._trigger("beforeshow", {prevPage: from});
function loadComplete(){
if( changeHash !== false && url ){
if( !back ){
urlHistory.listeningEnabled = false;
}
path.set( url );
urlHistory.listeningEnabled = true;
}
//add page to history stack if it's not back or forward
if( !back && !forward ){
urlHistory.addNew( url, transition );
}
removeActiveLinkClass();
//jump to top or prev scroll, sometimes on iOS the page has not rendered yet. I could only get by this with a setTimeout, but would like to avoid that.
$.mobile.silentScroll( to.data( 'lastScroll' ) );
reFocus( to );
//trigger show/hide events, allow preventing focus change through return false
from.data("page")._trigger("hide", null, {nextPage: to});
if( to.data("page")._trigger("show", null, {prevPage: from}) !== false ){
$.mobile.activePage = to;
}
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if (duplicateCachedPage != null) {
duplicateCachedPage.remove();
}
};
function addContainerClass(className){
$.mobile.pageContainer.addClass(className);
pageContainerClasses.push(className);
};
function removeContainerClasses(){
$.mobile
.pageContainer
.removeClass(pageContainerClasses.join(" "));
pageContainerClasses = [];
};
if(transition && (transition !== 'none')){
$.mobile.pageLoading( true );
if( $.inArray(transition, perspectiveTransitions) >= 0 ){
addContainerClass('ui-mobile-viewport-perspective');
}
addContainerClass('ui-mobile-viewport-transitioning');
/* animate in / out
* This is in a setTimeout because we were often seeing pages in not animate across but rather go straight to
* the 'to' page. The loadComplete would still fire, so the browser thought it was applying the animation. From
* what I could tell this was a problem with the classes not being applied yet.
*/
setTimeout(function() { from.addClass( transition + " out " + ( reverse ? "reverse" : "" ) );
to.addClass( $.mobile.activePageClass + " " + transition +
" in " + ( reverse ? "reverse" : "" ) ); } , 0);
// callback - remove classes, etc
to.animationComplete(function() {
from.add( to ).removeClass("out in reverse " + transition );
from.removeClass( $.mobile.activePageClass );
loadComplete();
removeContainerClasses();
});
}
else{
$.mobile.pageLoading( true );
from.removeClass( $.mobile.activePageClass );
to.addClass( $.mobile.activePageClass );
loadComplete();
}
};
//shared page enhancements
function enhancePage(){
//set next page role, if defined
if ( nextPageRole || to.data('role') == 'dialog' ) {
url = urlHistory.getActive().url + dialogHashKey;
if(nextPageRole){
to.attr( "data-role", nextPageRole );
nextPageRole = null;
}
}
//run page plugin
to.page();
};
//if url is a string
if( url ){
to = $( "[data-url='" + url + "']" );
fileUrl = path.getFilePath(url);
}
else{ //find base url of element, if avail
var toID = to.attr('data-url'),
toIDfileurl = path.getFilePath(toID);
if(toID != toIDfileurl){
fileUrl = toIDfileurl;
}
}
// ensure a transition has been set where pop is undefined
defaultTransition();
// find the "to" page, either locally existing in the dom or by creating it through ajax
if ( to.length && !isFormRequest ) {
if( fileUrl && base ){
base.set( fileUrl );
}
enhancePage();
transitionPages();
} else {
//if to exists in DOM, save a reference to it in duplicateCachedPage for removal after page change
if( to.length ){
duplicateCachedPage = to;
}
$.mobile.pageLoading();
$.ajax({
url: fileUrl,
type: type,
data: data,
success: function( html ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var redirectLoc = / data-url="(.*)"/.test( html ) && RegExp.$1;
if( redirectLoc ){
if(base){
base.set( redirectLoc );
}
url = fileUrl = path.makeAbsolute( path.getFilePath( redirectLoc ) );
}
else {
if(base){
base.set(fileUrl);
}
}
var all = $("<div></div>");
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
to = all.find('[data-role="page"], [data-role="dialog"]').first();
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ){
var newPath = path.get( fileUrl );
to.find('[src],link[href]').each(function(){
var thisAttr = $(this).is('[href]') ? 'href' : 'src',
thisUrl = $(this).attr(thisAttr);
//if full path exists and is same, chop it - helps IE out
thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test(thisUrl) ){
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
//append to page and enhance
to
.attr( "data-url", fileUrl )
.appendTo( $.mobile.pageContainer );
enhancePage();
transitionPages();
},
error: function() {
$.mobile.pageLoading( true );
removeActiveLinkClass(true);
base.set(path.get());
$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>Error Loading Page</h1></div>")
.css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100 })
.appendTo( $.mobile.pageContainer )
.delay( 800 )
.fadeOut( 400, function(){
$(this).remove();
});
}
});
}
};
/* Event Bindings - hashchange, submit, and click */
//bind to form submit events, handle with Ajax
$( "form[data-ajax!='false']" ).live('submit', function(event){
if( !$.mobile.ajaxEnabled ||
//TODO: deprecated - remove at 1.0
!$.mobile.ajaxFormsEnabled ){ return; }
var type = $(this).attr("method"),
url = path.clean( $(this).attr( "action" ) );
//external submits use regular HTTP
if( path.isExternal( url ) ){
return;
}
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
$.mobile.changePage({
url: url,
type: type,
data: $(this).serialize()
},
undefined,
undefined,
true
);
event.preventDefault();
});
//click routing - direct to HTTP or Ajax, accordingly
$( "a" ).live( "click", function(event) {
var $this = $(this),
//get href, remove same-domain protocol and host
url = path.clean( $this.attr( "href" ) ),
//rel set to external
isRelExternal = $this.is( "[rel='external']" ),
//rel set to external
isEmbeddedPage = path.isEmbeddedPage( url ),
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = path.isExternal( url ) || isRelExternal && !isEmbeddedPage,
//if target attr is specified we mimic _blank... for now
hasTarget = $this.is( "[target]" );
//if there's a data-rel=back attr, go back in history
if( $this.is( "[data-rel='back']" ) ){
window.history.back();
return false;
}
if( url === "#" ){
//for links created purely for interaction - ignore
return false;
}
$activeClickedLink = $this.closest( ".ui-btn" ).addClass( $.mobile.activeBtnClass );
if( isExternal || hasTarget || !$.mobile.ajaxEnabled ||
// TODO: deprecated - remove at 1.0
!$.mobile.ajaxLinksEnabled ){
//remove active link class if external (then it won't be there if you come back)
removeActiveLinkClass(true);
//deliberately redirect, in case click was triggered
if( hasTarget ){
window.open( url );
}
else{
location.href = url;
}
}
else {
//use ajax
var transition = $this.data( "transition" ),
direction = $this.data("direction"),
reverse = direction && direction == "reverse" ||
// deprecated - remove by 1.0
$this.data( "back" );
//this may need to be more specific as we use data-rel more
nextPageRole = $this.attr( "data-rel" );
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
url = path.stripHash( url );
$.mobile.changePage( url, transition, reverse);
}
event.preventDefault();
});
//hashchange event handler
$window.bind( "hashchange", function(e, triggered) {
if( !triggered && ( !urlHistory.listeningEnabled || !$.mobile.ajaxEnabled ||
// TODO: deprecated - remove at 1.0
// only links need to be checked here, as forms don't trigger a hashchange event (they just silently update the hash)
!$.mobile.ajaxLinksEnabled ) ){
return;
}
var to = path.stripHash( location.hash ),
transition = triggered ? false : undefined;
//make sure that hash changes that produce a dialog url do nothing
if( urlHistory.stack.length > 1 &&
to.indexOf( dialogHashKey ) > -1 &&
!$.mobile.activePage.is( ".ui-dialog" ) ){
return;
}
//if to is defined, use it
if ( to ){
$.mobile.changePage( to, transition, undefined, false, true );
}
//there's no hash, the active page is not the start page, and it's not manually triggered hashchange
//we probably backed out to the first page visited
else if( $.mobile.activePage.length && $.mobile.startPage[0] !== $.mobile.activePage[0] && !triggered ) {
$.mobile.changePage( $.mobile.startPage, transition, true, false, true );
}
//probably the first page - show it
else{
urlHistory.addNew( "" );
$.mobile.startPage.trigger("pagebeforeshow", {prevPage: $('')});
$.mobile.startPage.addClass( $.mobile.activePageClass );
$.mobile.pageLoading( true );
if( $.mobile.startPage.trigger("pageshow", {prevPage: $('')}) !== false ){
reFocus($.mobile.startPage);
}
}
});
})( jQuery );
|
js/jquery.mobile.navigation.js
|
/*
* jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt,
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined ) {
//define vars for interal use
var $window = $(window),
$html = $('html'),
$head = $('head'),
//url path helpers for use in relative url management
path = {
//get path from current hash, or from a file path
get: function( newPath ){
if( newPath == undefined ){
newPath = location.hash;
}
return path.stripHash( newPath ).replace(/[^\/]*\.[^\/*]+$/, '');
},
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ){
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//set location hash to path
set: function( path ){
location.hash = path;
},
//location pathname from intial directory request
origin: '',
setOrigin: function(){
path.origin = path.get( location.protocol + '//' + location.host + location.pathname );
},
//prefix a relative url with the current path
makeAbsolute: function( url ){
return path.get() + url;
},
//return a url path with the window's location protocol/hostname removed
clean: function( url ){
return url.replace( location.protocol + "//" + location.host, "");
},
//just return the url without an initial #
stripHash: function( url ){
return url.replace( /^#/, "" );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ){
return path.hasProtocol( path.clean( url ) );
},
hasProtocol: function( url ){
return /^(:?\w+:)/.test( url );
},
//check if the url is relative
isRelative: function( url ){
return /^[^\/|#]/.test( url ) && !path.hasProtocol( url );
},
isEmbeddedPage: function( url ){
return /^#/.test( url );
}
},
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = {
//array of pages that are visited during a single page load. each has a url and optional transition
stack: [],
//maintain an index number for the active page in the stack
activeIndex: 0,
//get active
getActive: function(){
return urlHistory.stack[ urlHistory.activeIndex ];
},
getPrev: function(){
return urlHistory.stack[ urlHistory.activeIndex - 1 ];
},
getNext: function(){
return urlHistory.stack[ urlHistory.activeIndex + 1 ];
},
// addNew is used whenever a new page is added
addNew: function( url, transition ){
//if there's forward history, wipe it
if( urlHistory.getNext() ){
urlHistory.clearForward();
}
urlHistory.stack.push( {url : url, transition: transition } );
urlHistory.activeIndex = urlHistory.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function(){
urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
},
//enable/disable hashchange event listener
//toggled internally when location.hash is updated to match the url of a successful page load
listeningEnabled: true
},
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//contains role for next page, if defined on clicked link via data-rel
nextPageRole = null,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog";
//existing base tag?
var $base = $head.children("base"),
hostURL = location.protocol + '//' + location.host,
docLocation = path.get( hostURL + location.pathname ),
docBase = docLocation;
if ($base.length){
var href = $base.attr("href");
if (href){
if (href.search(/^[^:/]+:\/\/[^/]+\/?/) == -1){
//the href is not absolute, we need to turn it into one
//so that we can turn paths stored in our location hash into
//relative paths.
if (href.charAt(0) == '/'){
//site relative url
docBase = hostURL + href;
}
else {
//the href is a document relative url
docBase = docLocation + href;
//XXX: we need some code here to calculate the final path
// just in case the docBase contains up-level (../) references.
}
}
else {
//the href is an absolute url
docBase = href;
}
}
//make sure docBase ends with a slash
docBase = docBase + (docBase.charAt(docBase.length - 1) == '/' ? ' ' : '/');
}
//base element management, defined depending on dynamic base tag support
base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ($base.length ? $base : $("<base>", { href: docBase }).prependTo( $head )),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ){
base.element.attr('href', docBase + path.get( href ));
},
//set the generated BASE element's href attribute to a new page's base path
reset: function(){
base.element.attr('href', docBase );
}
} : undefined;
//set location pathname from intial directory request
path.setOrigin();
/*
internal utility functions
--------------------------------------*/
//direct focus to the page title, or otherwise first focusable element
function reFocus( page ){
var pageTitle = page.find( ".ui-title:eq(0)" );
if( pageTitle.length ){
pageTitle.focus();
}
else{
page.find( focusable ).eq(0).focus();
}
};
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ){
if( !!$activeClickedLink && (!$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval )){
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
};
//animation complete callback
$.fn.animationComplete = function( callback ){
if($.support.cssTransitions){
return $(this).one('webkitAnimationEnd', callback);
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout(callback, 0);
}
};
/* exposed $.mobile methods */
//update location.hash, with or without triggering hashchange event
//TODO - deprecate this one at 1.0
$.mobile.updateHash = path.set;
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//url stack, useful when plugins need to be aware of previous pages viewed
//TODO: deprecate this one at 1.0
$.mobile.urlstack = urlHistory.stack;
//history stack
$.mobile.urlHistory = urlHistory;
// changepage function
// TODO : consider moving args to an object hash
$.mobile.changePage = function( to, transition, reverse, changeHash, fromHashChange ){
//from is always the currently viewed page
var toIsArray = $.type(to) === "array",
toIsObject = $.type(to) === "object",
from = toIsArray ? to[0] : $.mobile.activePage,
to = toIsArray ? to[1] : to,
url = fileUrl = $.type(to) === "string" ? path.stripHash( to ) : "",
data = undefined,
type = 'get',
isFormRequest = false,
duplicateCachedPage = null,
currPage = urlHistory.getActive(),
back = false,
forward = false;
// If we are trying to transition to the same page that we are currently on ignore the request.
// an illegal same page request is defined by the current page being the same as the url, as long as there's history
// and to is not an array or object (those are allowed to be "same")
if( currPage && urlHistory.stack.length > 1 && currPage.url === url && !toIsArray && !toIsObject ) {
return;
}
// if the changePage was sent from a hashChange event
// guess if it came from the history menu
if( fromHashChange ){
// check if url is in history and if it's ahead or behind current page
$.each( urlHistory.stack, function( i ){
//if the url is in the stack, it's a forward or a back
if( this.url == url ){
urlIndex = i;
//define back and forward by whether url is older or newer than current page
back = i < urlHistory.activeIndex;
//forward set to opposite of back
forward = !back;
//reset activeIndex to this one
urlHistory.activeIndex = i;
}
});
//if it's a back, use reverse animation
if( back ){
reverse = true;
transition = transition || currPage.transition;
}
else if ( forward ){
transition = transition || urlHistory.getActive().transition;
}
}
if( toIsObject && to.url ){
url = to.url,
data = to.data,
type = to.type,
isFormRequest = true;
//make get requests bookmarkable
if( data && type == 'get' ){
if($.type( data ) == "object" ){
data = $.param(data);
}
url += "?" + data;
data = undefined;
}
}
//reset base to pathname for new request
if(base){ base.reset(); }
//kill the keyboard
$( window.document.activeElement ).add(':focus').blur();
function defaultTransition(){
if(transition === undefined){
transition = $.mobile.defaultTransition;
}
}
//function for transitioning between two existing pages
function transitionPages() {
$.mobile.silentScroll();
//get current scroll distance
var currScroll = $window.scrollTop(),
perspectiveTransitions = ["flip"],
pageContainerClasses = [];
//support deep-links to generated sub-pages
if( url.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ){
to = $( "[data-url='" + url + "']" );
}
//set as data for returning to that spot
from.data('lastScroll', currScroll);
//trigger before show/hide events
from.data("page")._trigger("beforehide", {nextPage: to});
to.data("page")._trigger("beforeshow", {prevPage: from});
function loadComplete(){
if( changeHash !== false && url ){
if( !back ){
urlHistory.listeningEnabled = false;
}
path.set( url );
urlHistory.listeningEnabled = true;
}
//add page to history stack if it's not back or forward
if( !back && !forward ){
urlHistory.addNew( url, transition );
}
removeActiveLinkClass();
//jump to top or prev scroll, sometimes on iOS the page has not rendered yet. I could only get by this with a setTimeout, but would like to avoid that.
$.mobile.silentScroll( to.data( 'lastScroll' ) );
reFocus( to );
//trigger show/hide events, allow preventing focus change through return false
from.data("page")._trigger("hide", null, {nextPage: to});
if( to.data("page")._trigger("show", null, {prevPage: from}) !== false ){
$.mobile.activePage = to;
}
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if (duplicateCachedPage != null) {
duplicateCachedPage.remove();
}
};
function addContainerClass(className){
$.mobile.pageContainer.addClass(className);
pageContainerClasses.push(className);
};
function removeContainerClasses(){
$.mobile
.pageContainer
.removeClass(pageContainerClasses.join(" "));
pageContainerClasses = [];
};
if(transition && (transition !== 'none')){
$.mobile.pageLoading( true );
if( $.inArray(transition, perspectiveTransitions) >= 0 ){
addContainerClass('ui-mobile-viewport-perspective');
}
addContainerClass('ui-mobile-viewport-transitioning');
/* animate in / out
* This is in a setTimeout because we were often seeing pages in not animate across but rather go straight to
* the 'to' page. The loadComplete would still fire, so the browser thought it was applying the animation. From
* what I could tell this was a problem with the classes not being applied yet.
*/
setTimeout(function() { from.addClass( transition + " out " + ( reverse ? "reverse" : "" ) );
to.addClass( $.mobile.activePageClass + " " + transition +
" in " + ( reverse ? "reverse" : "" ) ); } , 0);
// callback - remove classes, etc
to.animationComplete(function() {
from.add( to ).removeClass("out in reverse " + transition );
from.removeClass( $.mobile.activePageClass );
loadComplete();
removeContainerClasses();
});
}
else{
$.mobile.pageLoading( true );
from.removeClass( $.mobile.activePageClass );
to.addClass( $.mobile.activePageClass );
loadComplete();
}
};
//shared page enhancements
function enhancePage(){
//set next page role, if defined
if ( nextPageRole || to.data('role') == 'dialog' ) {
url = urlHistory.getActive().url + dialogHashKey;
if(nextPageRole){
to.attr( "data-role", nextPageRole );
nextPageRole = null;
}
}
//run page plugin
to.page();
};
//if url is a string
if( url ){
to = $( "[data-url='" + url + "']" );
fileUrl = path.getFilePath(url);
}
else{ //find base url of element, if avail
var toID = to.attr('data-url'),
toIDfileurl = path.getFilePath(toID);
if(toID != toIDfileurl){
fileUrl = toIDfileurl;
}
}
// ensure a transition has been set where pop is undefined
defaultTransition();
// find the "to" page, either locally existing in the dom or by creating it through ajax
if ( to.length && !isFormRequest ) {
if( fileUrl && base ){
base.set( fileUrl );
}
enhancePage();
transitionPages();
} else {
//if to exists in DOM, save a reference to it in duplicateCachedPage for removal after page change
if( to.length ){
duplicateCachedPage = to;
}
$.mobile.pageLoading();
$.ajax({
url: fileUrl,
type: type,
data: data,
success: function( html ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var redirectLoc = / data-url="(.*)"/.test( html ) && RegExp.$1;
if( redirectLoc ){
if(base){
base.set( redirectLoc );
}
url = fileUrl = path.makeAbsolute( path.getFilePath( redirectLoc ) );
}
else {
if(base){
base.set(fileUrl);
}
}
var all = $("<div></div>");
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
to = all.find('[data-role="page"], [data-role="dialog"]').first();
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ){
var newPath = path.get( fileUrl );
to.find('[src],link[href]').each(function(){
var thisAttr = $(this).is('[href]') ? 'href' : 'src',
thisUrl = $(this).attr(thisAttr);
//if full path exists and is same, chop it - helps IE out
thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test(thisUrl) ){
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
//append to page and enhance
to
.attr( "data-url", fileUrl )
.appendTo( $.mobile.pageContainer );
enhancePage();
transitionPages();
},
error: function() {
$.mobile.pageLoading( true );
removeActiveLinkClass(true);
base.set(path.get());
$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>Error Loading Page</h1></div>")
.css({ "display": "block", "opacity": 0.96, "top": $(window).scrollTop() + 100 })
.appendTo( $.mobile.pageContainer )
.delay( 800 )
.fadeOut( 400, function(){
$(this).remove();
});
}
});
}
};
/* Event Bindings - hashchange, submit, and click */
//bind to form submit events, handle with Ajax
$( "form[data-ajax!='false']" ).live('submit', function(event){
if( !$.mobile.ajaxEnabled ||
//TODO: deprecated - remove at 1.0
!$.mobile.ajaxFormsEnabled ){ return; }
var type = $(this).attr("method"),
url = path.clean( $(this).attr( "action" ) );
//external submits use regular HTTP
if( path.isExternal( url ) ){
return;
}
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
$.mobile.changePage({
url: url,
type: type,
data: $(this).serialize()
},
undefined,
undefined,
true
);
event.preventDefault();
});
//click routing - direct to HTTP or Ajax, accordingly
$( "a" ).live( "click", function(event) {
var $this = $(this),
//get href, remove same-domain protocol and host
url = path.clean( $this.attr( "href" ) ),
//rel set to external
isRelExternal = $this.is( "[rel='external']" ),
//rel set to external
isEmbeddedPage = path.isEmbeddedPage( url ),
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = path.isExternal( url ) || isRelExternal && !isEmbeddedPage;
//if target attr is specified we mimic _blank... for now
hasTarget = $this.is( "[target]" );
//if there's a data-rel=back attr, go back in history
if( $this.is( "[data-rel='back']" ) ){
window.history.back();
return false;
}
if( url === "#" ){
//for links created purely for interaction - ignore
return false;
}
$activeClickedLink = $this.closest( ".ui-btn" ).addClass( $.mobile.activeBtnClass );
if( isExternal || hasTarget || !$.mobile.ajaxEnabled ||
// TODO: deprecated - remove at 1.0
!$.mobile.ajaxLinksEnabled ){
//remove active link class if external (then it won't be there if you come back)
removeActiveLinkClass(true);
//deliberately redirect, in case click was triggered
if( hasTarget ){
window.open( url );
}
else{
location.href = url;
}
}
else {
//use ajax
var transition = $this.data( "transition" ),
direction = $this.data("direction"),
reverse = direction && direction == "reverse" ||
// deprecated - remove by 1.0
$this.data( "back" );
//this may need to be more specific as we use data-rel more
nextPageRole = $this.attr( "data-rel" );
//if it's a relative href, prefix href with base url
if( path.isRelative( url ) ){
url = path.makeAbsolute( url );
}
url = path.stripHash( url );
$.mobile.changePage( url, transition, reverse);
}
event.preventDefault();
});
//hashchange event handler
$window.bind( "hashchange", function(e, triggered) {
if( !triggered && ( !urlHistory.listeningEnabled || !$.mobile.ajaxEnabled ||
// TODO: deprecated - remove at 1.0
// only links need to be checked here, as forms don't trigger a hashchange event (they just silently update the hash)
!$.mobile.ajaxLinksEnabled ) ){
return;
}
var to = path.stripHash( location.hash ),
transition = triggered ? false : undefined;
//make sure that hash changes that produce a dialog url do nothing
if( urlHistory.stack.length > 1 &&
to.indexOf( dialogHashKey ) > -1 &&
!$.mobile.activePage.is( ".ui-dialog" ) ){
return;
}
//if to is defined, use it
if ( to ){
$.mobile.changePage( to, transition, undefined, false, true );
}
//there's no hash, the active page is not the start page, and it's not manually triggered hashchange
//we probably backed out to the first page visited
else if( $.mobile.activePage.length && $.mobile.startPage[0] !== $.mobile.activePage[0] && !triggered ) {
$.mobile.changePage( $.mobile.startPage, transition, true, false, true );
}
//probably the first page - show it
else{
urlHistory.addNew( "" );
$.mobile.startPage.trigger("pagebeforeshow", {prevPage: $('')});
$.mobile.startPage.addClass( $.mobile.activePageClass );
$.mobile.pageLoading( true );
if( $.mobile.startPage.trigger("pageshow", {prevPage: $('')}) !== false ){
reFocus($.mobile.startPage);
}
}
});
})( jQuery );
|
misplaced semicolon
|
js/jquery.mobile.navigation.js
|
misplaced semicolon
|
<ide><path>s/jquery.mobile.navigation.js
<ide> //check for protocol or rel and its not an embedded page
<ide> //TODO overlap in logic from isExternal, rel=external check should be
<ide> // moved into more comprehensive isExternalLink
<del> isExternal = path.isExternal( url ) || isRelExternal && !isEmbeddedPage;
<add> isExternal = path.isExternal( url ) || isRelExternal && !isEmbeddedPage,
<ide>
<ide> //if target attr is specified we mimic _blank... for now
<ide> hasTarget = $this.is( "[target]" );
|
|
JavaScript
|
mit
|
889ca4d89b2e0d918fe7a5fee84334632c3bea74
| 0 |
ministryofjustice/advocate-defence-payments,ministryofjustice/advocate-defence-payments,ministryofjustice/advocate-defence-payments,ministryofjustice/advocate-defence-payments
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.remotipart
//= require select2
//= require cocoon
//= require dropzone
//= require moj
//= require modules/moj.cookie-message
//= require_tree .
/*For JSHint to ignore ADP object*/
/* globals adp */
/* globals rorData */
var moj = moj || {};
moj.Modules.devs.init = function(){};
$('#claim-accordion h2').each(function(){
$(this).next('section').hide();
$(this).click(function(){
$(this).toggleClass('open').next('section').slideToggle('slow');
});
});
$('#claim-accordion h2:first-of-type').addClass('open').next('section').show();
function initialise(){
moj.Modules.CookieMessage.init();
$('.select2').select2();
adp.newClaim.init();
adp.crackedTrial.init();
adp.messaging.init();
adp.trialFieldsDisplay.init();
adp.feeSectionDisplay.init();
adp.feeCalculator.init('expenses');
adp.determination.init('determinations');
adp.dropzone.init();
moj.Modules.fileUpload.init();
moj.Modules.judicialApportionment.init();
moj.Modules.amountAssessed.init();
$('#fixed-fees, #misc-fees, #expenses, #documents').on('cocoon:after-insert', function(e,insertedItem) {
$(insertedItem).find('.select2').select2();
});
moj.Modules.selectAll.init();
moj.Modules.allocationFilterSubmit.init();
}
$( document ).ready(function() {
initialise();
//Stops the form from submitting when the user presses 'Enter' key
$("#claim-form form").on("keypress", function (e) {
if (e.keyCode === 13) {
return false;
}
});
});
|
app/assets/javascripts/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.remotipart
//= require select2
//= require cocoon
//= require dropzone
//= require moj
//= require_tree .
/*For JSHint to ignore ADP object*/
/* globals adp */
/* globals rorData */
var moj = moj || {};
moj.Modules.devs.init = function(){};
$('#claim-accordion h2').each(function(){
$(this).next('section').hide();
$(this).click(function(){
$(this).toggleClass('open').next('section').slideToggle('slow');
});
});
$('#claim-accordion h2:first-of-type').addClass('open').next('section').show();
function initialise(){
$('.select2').select2();
adp.newClaim.init();
adp.crackedTrial.init();
adp.messaging.init();
adp.trialFieldsDisplay.init();
adp.feeSectionDisplay.init();
adp.feeCalculator.init('expenses');
adp.determination.init('determinations');
adp.dropzone.init();
moj.Modules.fileUpload.init();
moj.Modules.judicialApportionment.init();
moj.Modules.amountAssessed.init();
$('#fixed-fees, #misc-fees, #expenses, #documents').on('cocoon:after-insert', function(e,insertedItem) {
$(insertedItem).find('.select2').select2();
});
moj.Modules.selectAll.init();
moj.Modules.allocationFilterSubmit.init();
}
$( document ).ready(function() {
initialise();
//Stops the form from submitting when the user presses 'Enter' key
$("#claim-form form").on("keypress", function (e) {
if (e.keyCode === 13) {
return false;
}
});
});
|
Add moj cookie message
|
app/assets/javascripts/application.js
|
Add moj cookie message
|
<ide><path>pp/assets/javascripts/application.js
<ide> //= require cocoon
<ide> //= require dropzone
<ide> //= require moj
<add>//= require modules/moj.cookie-message
<ide> //= require_tree .
<ide>
<ide> /*For JSHint to ignore ADP object*/
<ide> $('#claim-accordion h2:first-of-type').addClass('open').next('section').show();
<ide>
<ide> function initialise(){
<add> moj.Modules.CookieMessage.init();
<ide> $('.select2').select2();
<ide> adp.newClaim.init();
<ide> adp.crackedTrial.init();
|
|
Java
|
apache-2.0
|
fbe2157b0986eaf4ec4be5b53c1805d2bf2f8d74
| 0 |
pavolloffay/hawkular-inventory,pavolloffay/hawkular-inventory,metlos/hawkular-inventory,hawkular/hawkular-inventory,jpkrohling/hawkular-inventory,jpkrohling/hawkular-inventory,tsegismont/hawkular-inventory,hawkular/hawkular-inventory,metlos/hawkular-inventory,jkandasa/hawkular-inventory,jkandasa/hawkular-inventory,tsegismont/hawkular-inventory
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.inventory.rest.exception.mappers;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.spi.BadRequestException;
/**
* Exception mapper for any exception thrown by RESTEasy when HTTP Bad Request (400) is encountered.
* <p>
* This mapper let us reply to the user with a pre-determined message format if, for example, a {@link
* javax.ws.rs.ext.ParamConverter} throws an {@link java.lang.IllegalArgumentException}.
*
* @author Thomas Segismont
*/
@Provider
public class BadRequestExceptionMapper implements ExceptionMapper<BadRequestException> {
@Override
public Response toResponse(BadRequestException exception) {
return ExceptionMapperUtils.buildResponse(exception, Response.Status.BAD_REQUEST);
}
}
|
rest-servlet/src/main/java/org/hawkular/inventory/rest/exception/mappers/BadRequestExceptionMapper.java
|
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.metrics.api.jaxrs.exception.mappers;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.hawkular.inventory.rest.exception.mappers.ExceptionMapperUtils;
import org.jboss.resteasy.spi.BadRequestException;
/**
* Exception mapper for any exception thrown by RESTEasy when HTTP Bad Request (400) is encountered.
* <p>
* This mapper let us reply to the user with a pre-determined message format if, for example, a {@link
* javax.ws.rs.ext.ParamConverter} throws an {@link java.lang.IllegalArgumentException}.
*
* @author Thomas Segismont
*/
@Provider
public class BadRequestExceptionMapper implements ExceptionMapper<BadRequestException> {
@Override
public Response toResponse(BadRequestException exception) {
return ExceptionMapperUtils.buildResponse(exception, Response.Status.BAD_REQUEST);
}
}
|
Fix package name and redundant import in BadRequestExceptionMapper
|
rest-servlet/src/main/java/org/hawkular/inventory/rest/exception/mappers/BadRequestExceptionMapper.java
|
Fix package name and redundant import in BadRequestExceptionMapper
|
<ide><path>est-servlet/src/main/java/org/hawkular/inventory/rest/exception/mappers/BadRequestExceptionMapper.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.hawkular.metrics.api.jaxrs.exception.mappers;
<add>package org.hawkular.inventory.rest.exception.mappers;
<ide>
<ide> import javax.ws.rs.core.Response;
<ide> import javax.ws.rs.ext.ExceptionMapper;
<ide> import javax.ws.rs.ext.Provider;
<ide>
<del>import org.hawkular.inventory.rest.exception.mappers.ExceptionMapperUtils;
<ide> import org.jboss.resteasy.spi.BadRequestException;
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
99b38c74058979fc80675bd58a02b508f74cb99d
| 0 |
JayH5/hons-simulator
|
package za.redbridge.simulator.sensor;
import za.redbridge.simulator.object.ResourceObject;
import za.redbridge.simulator.object.RobotObject;
import za.redbridge.simulator.object.TargetAreaObject;
import za.redbridge.simulator.object.WallObject;
import za.redbridge.simulator.physics.FilterConstants;
import za.redbridge.simulator.portrayal.ConePortrayal;
import za.redbridge.simulator.portrayal.Portrayal;
import za.redbridge.simulator.sensor.sensedobjects.SensedObject;
import java.awt.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Created by shsu on 2014/09/15.
*/
//Object types are analogous to colours
public class ThresholdedObjectProximityAgentSensor extends AdjustableSensitivityAgentSensor {
protected static final int readingSize = 1;
protected double sensitivity;
protected String sensitiveClass;
protected Class senseClass;
protected Color paint;
public ThresholdedObjectProximityAgentSensor() {
super();
sensitivity = 0;
try {
senseClass = Class.forName("za.redbridge.simulator.object.ResourceObject");
}
catch (ClassNotFoundException c) {
System.out.println("Class not found.");
}
}
public ThresholdedObjectProximityAgentSensor(float bearing, float orientation, float range, float fieldOfView) {
super(bearing, orientation, range, fieldOfView);
}
public ThresholdedObjectProximityAgentSensor(float bearing, String sensitiveClassName) {
super(bearing, 0.0f, 30.0f, 0.1f);
try {
this.senseClass = Class.forName(sensitiveClassName);
}catch(ClassNotFoundException e){}
}
protected void setPaint () {
int red = 0;
int blue = 0;
int green = 0;
float value = 1f-((float) sensitivity);
int alpha = (int) (value*255f);
String className = senseClass.getName();
if (className.equals("za.redbridge.simulator.object.RobotObject")) {
blue = 34;
green = 255;
}
else if (className.equals("za.redbridge.simulator.object.ResourceObject")) {
red = 255;
blue = 208;
}
else if (className.equals("za.redbridge.simulator.object.TargetAreaObject")) {
red = 69;
blue = 138;
}
else if (className.equals("za.redbridge.simulator.object.WallObject")) {
red = 69;
blue = 0;
green = 138;
}
paint = new Color(red, blue, green, alpha);
}
@Override
protected Paint getPaint() {
if (paint == null)
setPaint();
return paint;
}
@Override
protected void provideObjectReading(List<SensedObject> objects, List<Double> output) {
double reading = 0.0;
for(SensedObject o : objects){
if(o.getObject().getClass().equals(senseClass)){
reading = 1 - Math.min(o.getDistance() / range, 1.0);
break;
}
}
//threshold
if (reading >= (1-sensitivity)) {
output.add(reading);
}
else {
output.add(0.0);
}
}
@Override
public void readAdditionalConfigs(Map<String, Object> map) throws ParseException {
additionalConfigs = map;
if (map == null) {
System.out.println("No additional configs found.");
return;
}
String sensitive = (String) map.get("sensitiveClass");
if (checkFieldPresent(sensitive, "sensitiveClass")) {
try {
senseClass = Class.forName(sensitive);
sensitiveClass = sensitive;
}
catch (ClassNotFoundException c) {
System.out.println("Specified sensitive class not found.");
System.exit(-1);
}
}
else {
throw new ParseException("No sensitive class found for ThresholdedObjectProximityAgentSensor.", 0);
}
Number sens = (Number) map.get("sensitivity");
if (checkFieldPresent(sens, "sensitivity")) {
double sensValue = sens.doubleValue();
if (sensValue > 1 || sensValue < 0) {
throw new ParseException("Sensitivity value for ThresholdedObjectProximityAgentSensor must be between 0 and 1", 0);
}
this.sensitivity = sensValue;
}
else {
throw new ParseException("No sensitivity value found for ThresholdedObjectProximityAgentSensor.", 0);
}
this.setPaint();
}
@Override
protected int getFilterCategoryBits() {
if (senseClass.getSimpleName().contains("TargetAreaObject")) {
return FilterConstants.CategoryBits.TARGET_AREA_SENSOR;
}
return FilterConstants.CategoryBits.AGENT_SENSOR;
}
@Override
protected int getFilterMaskBits() {
String className = senseClass.getSimpleName();
if (className.equals("RobotObject")) {
return FilterConstants.CategoryBits.ROBOT;
}
else if (className.equals("ResourceObject")) {
return FilterConstants.CategoryBits.RESOURCE;
}
else if (className.equals("TargetAreaObject")) {
return FilterConstants.CategoryBits.TARGET_AREA;
}
else if (className.equals("WallObject")) {
return FilterConstants.CategoryBits.WALL;
}
else {
return FilterConstants.CategoryBits.DEFAULT;
}
}
@Override
public int getReadingSize() { return readingSize; }
@Override
public ThresholdedObjectProximityAgentSensor clone() {
ThresholdedObjectProximityAgentSensor cloned =
new ThresholdedObjectProximityAgentSensor(bearing, orientation, range, fieldOfView);
try {
cloned.readAdditionalConfigs(additionalConfigs);
}
catch (ParseException p) {
System.out.println("Clone failed.");
p.printStackTrace();
System.exit(-1);
}
return cloned;
}
@Override
public void setSensitivity(double sensitivity) { this.sensitivity = sensitivity; }
@Override
public double getSensitivity() { return sensitivity; }
public String getSensitiveClass() { return senseClass.getSimpleName(); }
@Override
public Map<String,Object> getAdditionalConfigs() { return additionalConfigs; }
}
|
src/main/java/za/redbridge/simulator/sensor/ThresholdedObjectProximityAgentSensor.java
|
package za.redbridge.simulator.sensor;
import za.redbridge.simulator.object.ResourceObject;
import za.redbridge.simulator.object.RobotObject;
import za.redbridge.simulator.object.TargetAreaObject;
import za.redbridge.simulator.object.WallObject;
import za.redbridge.simulator.physics.FilterConstants;
import za.redbridge.simulator.portrayal.ConePortrayal;
import za.redbridge.simulator.portrayal.Portrayal;
import za.redbridge.simulator.sensor.sensedobjects.SensedObject;
import java.awt.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Created by shsu on 2014/09/15.
*/
//Object types are analogous to colours
public class ThresholdedObjectProximityAgentSensor extends AdjustableSensitivityAgentSensor {
protected static final int readingSize = 1;
protected double sensitivity;
protected Class senseClass;
protected Color paint;
public ThresholdedObjectProximityAgentSensor() {
super();
sensitivity = 0;
try {
senseClass = Class.forName("za.redbridge.simulator.object.ResourceObject");
}
catch (ClassNotFoundException c) {
System.out.println("Class not found.");
}
}
public ThresholdedObjectProximityAgentSensor(float bearing, float orientation, float range, float fieldOfView) {
super(bearing, orientation, range, fieldOfView);
}
public ThresholdedObjectProximityAgentSensor(float bearing, String sensitiveClassName) {
super(bearing, 0.0f, 30.0f, 0.1f);
try {
this.senseClass = Class.forName(sensitiveClassName);
}catch(ClassNotFoundException e){}
}
@Override
protected int getFilterCategoryBits() {
if (senseClass.getSimpleName().contains("TargetAreaObject")) {
return FilterConstants.CategoryBits.TARGET_AREA_SENSOR;
}
return FilterConstants.CategoryBits.AGENT_SENSOR;
}
@Override
protected int getFilterMaskBits() {
String className = senseClass.getSimpleName();
if (className.equals("RobotObject")) {
return FilterConstants.CategoryBits.ROBOT;
}
else if (className.equals("ResourceObject")) {
return FilterConstants.CategoryBits.RESOURCE;
}
else if (className.equals("TargetAreaObject")) {
return FilterConstants.CategoryBits.TARGET_AREA;
}
else if (className.equals("WallObject")) {
return FilterConstants.CategoryBits.WALL;
}
else {
return FilterConstants.CategoryBits.DEFAULT;
}
}
protected void setPaint () {
int red = 0;
int blue = 0;
int green = 0;
float value = 1f-((float) sensitivity);
int alpha = (int) (value*255f);
String className = senseClass.getSimpleName();
if (className.equals("RobotObject")) {
blue = 34;
green = 255;
}
else if (className.equals("ResourceObject")) {
red = 255;
blue = 208;
}
else if (className.equals("TargetAreaObject")) {
red = 69;
blue = 138;
}
else if (className.equals("WallObject")) {
red = 69;
blue = 0;
green = 138;
}
paint = new Color(red, blue, green, alpha);
}
@Override
protected Paint getPaint() {
if (paint == null)
setPaint();
return paint;
}
@Override
protected void provideObjectReading(List<SensedObject> objects, List<Double> output) {
double reading = 0.0;
for(SensedObject o : objects){
if(o.getObject().getClass().equals(senseClass)){
reading = 1 - Math.min(o.getDistance() / range, 1.0);
break;
}
}
//threshold
if (reading >= (1-sensitivity)) {
output.add(reading);
}
else {
output.add(0.0);
}
}
@Override
public void readAdditionalConfigs(Map<String, Object> map) throws ParseException {
additionalConfigs = map;
if (map == null) {
System.out.println("No additional configs found.");
return;
}
String sensitive = (String) map.get("sensitiveClass");
if (checkFieldPresent(sensitive, "sensitiveClass")) {
try {
senseClass = Class.forName(sensitive);
}
catch (ClassNotFoundException c) {
System.out.println("Specified sensitive class not found.");
System.exit(-1);
}
}
else {
throw new ParseException("No sensitive class found for ThresholdedObjectProximityAgentSensor.", 0);
}
Number sens = (Number) map.get("sensitivity");
if (checkFieldPresent(sens, "sensitivity")) {
double sensValue = sens.doubleValue();
if (sensValue > 1 || sensValue < 0) {
throw new ParseException("Sensitivity value for ThresholdedObjectProximityAgentSensor must be between 0 and 1", 0);
}
this.sensitivity = sensValue;
}
else {
throw new ParseException("No sensitivity value found for ThresholdedObjectProximityAgentSensor.", 0);
}
this.setPaint();
}
@Override
public int getReadingSize() { return readingSize; }
@Override
public ThresholdedObjectProximityAgentSensor clone() {
ThresholdedObjectProximityAgentSensor cloned =
new ThresholdedObjectProximityAgentSensor(bearing, orientation, range, fieldOfView);
try {
cloned.readAdditionalConfigs(additionalConfigs);
}
catch (ParseException p) {
System.out.println("Clone failed.");
p.printStackTrace();
System.exit(-1);
}
return cloned;
}
@Override
public void setSensitivity(double sensitivity) { this.sensitivity = sensitivity; }
@Override
public double getSensitivity() { return sensitivity; }
public String getSensitiveClass() { return senseClass.getSimpleName(); }
@Override
public Map<String,Object> getAdditionalConfigs() { return additionalConfigs; }
}
|
Allows a class to which this sensor is sensitive to be specified. If thresholding is not needed, sensitivity value should be set to 1.
|
src/main/java/za/redbridge/simulator/sensor/ThresholdedObjectProximityAgentSensor.java
|
Allows a class to which this sensor is sensitive to be specified. If thresholding is not needed, sensitivity value should be set to 1.
|
<ide><path>rc/main/java/za/redbridge/simulator/sensor/ThresholdedObjectProximityAgentSensor.java
<ide> protected static final int readingSize = 1;
<ide> protected double sensitivity;
<ide>
<add> protected String sensitiveClass;
<add>
<ide> protected Class senseClass;
<add>
<ide> protected Color paint;
<del>
<del>
<ide>
<ide> public ThresholdedObjectProximityAgentSensor() {
<ide> super();
<ide> public ThresholdedObjectProximityAgentSensor(float bearing, String sensitiveClassName) {
<ide> super(bearing, 0.0f, 30.0f, 0.1f);
<ide>
<del> try {
<del> this.senseClass = Class.forName(sensitiveClassName);
<del> }catch(ClassNotFoundException e){}
<del>
<del> }
<del>
<del> @Override
<del> protected int getFilterCategoryBits() {
<del> if (senseClass.getSimpleName().contains("TargetAreaObject")) {
<del> return FilterConstants.CategoryBits.TARGET_AREA_SENSOR;
<del> }
<del>
<del> return FilterConstants.CategoryBits.AGENT_SENSOR;
<del> }
<del>
<del> @Override
<del> protected int getFilterMaskBits() {
<del>
<del> String className = senseClass.getSimpleName();
<del>
<del> if (className.equals("RobotObject")) {
<del> return FilterConstants.CategoryBits.ROBOT;
<del> }
<del> else if (className.equals("ResourceObject")) {
<del> return FilterConstants.CategoryBits.RESOURCE;
<del> }
<del> else if (className.equals("TargetAreaObject")) {
<del> return FilterConstants.CategoryBits.TARGET_AREA;
<del> }
<del> else if (className.equals("WallObject")) {
<del> return FilterConstants.CategoryBits.WALL;
<del> }
<del> else {
<del> return FilterConstants.CategoryBits.DEFAULT;
<del> }
<add> try {
<add> this.senseClass = Class.forName(sensitiveClassName);
<add> }catch(ClassNotFoundException e){}
<add>
<ide> }
<ide>
<ide> protected void setPaint () {
<ide>
<del> int red = 0;
<add> int red = 0;
<ide> int blue = 0;
<ide> int green = 0;
<ide>
<ide> float value = 1f-((float) sensitivity);
<ide> int alpha = (int) (value*255f);
<ide>
<del> String className = senseClass.getSimpleName();
<del>
<del> if (className.equals("RobotObject")) {
<add> String className = senseClass.getName();
<add>
<add> if (className.equals("za.redbridge.simulator.object.RobotObject")) {
<ide> blue = 34;
<ide> green = 255;
<ide> }
<del> else if (className.equals("ResourceObject")) {
<add> else if (className.equals("za.redbridge.simulator.object.ResourceObject")) {
<ide>
<ide> red = 255;
<ide> blue = 208;
<ide> }
<del> else if (className.equals("TargetAreaObject")) {
<add> else if (className.equals("za.redbridge.simulator.object.TargetAreaObject")) {
<ide>
<ide> red = 69;
<ide> blue = 138;
<ide> }
<del> else if (className.equals("WallObject")) {
<add> else if (className.equals("za.redbridge.simulator.object.WallObject")) {
<ide>
<ide> red = 69;
<ide> blue = 0;
<ide> String sensitive = (String) map.get("sensitiveClass");
<ide>
<ide> if (checkFieldPresent(sensitive, "sensitiveClass")) {
<del> try {
<del> senseClass = Class.forName(sensitive);
<del> }
<del> catch (ClassNotFoundException c) {
<del> System.out.println("Specified sensitive class not found.");
<del> System.exit(-1);
<del> }
<add> try {
<add> senseClass = Class.forName(sensitive);
<add> sensitiveClass = sensitive;
<add> }
<add> catch (ClassNotFoundException c) {
<add> System.out.println("Specified sensitive class not found.");
<add> System.exit(-1);
<add> }
<ide> }
<ide> else {
<ide> throw new ParseException("No sensitive class found for ThresholdedObjectProximityAgentSensor.", 0);
<ide>
<ide> this.setPaint();
<ide> }
<add>
<add> @Override
<add> protected int getFilterCategoryBits() {
<add> if (senseClass.getSimpleName().contains("TargetAreaObject")) {
<add> return FilterConstants.CategoryBits.TARGET_AREA_SENSOR;
<add> }
<add>
<add> return FilterConstants.CategoryBits.AGENT_SENSOR;
<add> }
<add>
<add> @Override
<add> protected int getFilterMaskBits() {
<add>
<add> String className = senseClass.getSimpleName();
<add>
<add> if (className.equals("RobotObject")) {
<add> return FilterConstants.CategoryBits.ROBOT;
<add> }
<add> else if (className.equals("ResourceObject")) {
<add> return FilterConstants.CategoryBits.RESOURCE;
<add> }
<add> else if (className.equals("TargetAreaObject")) {
<add> return FilterConstants.CategoryBits.TARGET_AREA;
<add> }
<add> else if (className.equals("WallObject")) {
<add> return FilterConstants.CategoryBits.WALL;
<add> }
<add> else {
<add> return FilterConstants.CategoryBits.DEFAULT;
<add> }
<add> }
<add>
<ide>
<ide> @Override
<ide> public int getReadingSize() { return readingSize; }
|
|
Java
|
apache-2.0
|
7164191d1789fb88d2dc09f36425ea117f3b17b9
| 0 |
DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel
|
package org.reldb.rel.v0.engine;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import org.reldb.rel.exceptions.DatabaseFormatVersionException;
import org.reldb.rel.exceptions.ExceptionFatal;
import org.reldb.rel.exceptions.ExceptionSemantic;
import org.reldb.rel.v0.interpreter.ClassPathHack;
import org.reldb.rel.v0.interpreter.Instance;
import org.reldb.rel.v0.interpreter.Interpreter;
import org.reldb.rel.v0.interpreter.ParseExceptionPrinter;
import org.reldb.rel.v0.languages.tutoriald.parser.ParseException;
import org.reldb.rel.v0.languages.tutoriald.parser.TokenMgrError;
import org.reldb.rel.v0.version.Version;
/** Convenient access point for running an embedded or stand-alone interpreter. */
public class Rel {
private Interpreter interpreter;
private PipedInputStream input;
private PrintStream output;
private static void buildClasspath() throws IOException {
ClassPathHack.addFile(Version.getBerkeleyDbJarFilename());
ClassPathHack.addFile("relshared.jar");
ClassPathHack.addFile("ecj-4.4.2.jar");
}
/** Convenient runner for a stand-alone Rel interpreter.
* @throws IOException */
public static void main(String[] args) throws IOException {
buildClasspath();
org.reldb.rel.v0.interpreter.Instance.main(args);
}
/** Open this database and back it up to the named file. */
public static void backup(String databaseDir, String backupFileName) throws IOException, ParseException, DatabaseFormatVersionException {
buildClasspath();
PrintStream output = new PrintStream(backupFileName);
Instance instance = new Instance(databaseDir, false, output);
Interpreter interpreter = new Interpreter(instance.getDatabase(), output);
interpreter.interpret("BACKUP;");
output.close();
instance.close();
}
/** Convert this database to the latest format, if necessary. Throw exception if not necessary. Normally only needed if invoking
* the constructor throws DatabaseFormatVersionException. */
public static void convertToLatestFormat(String databaseDir, PrintStream conversionOutput, String[] additionalJars) throws DatabaseFormatVersionException, IOException {
buildClasspath();
Instance.convertToLatestFormat(new File(databaseDir), conversionOutput, additionalJars);
}
/** Establish a connection with this server. */
public Rel(String databaseDir, boolean createDbAllowed, String[] additionalJars) throws IOException, DatabaseFormatVersionException {
buildClasspath();
input = new PipedInputStream();
PipedOutputStream pipeOutput = new PipedOutputStream(input);
output = new PrintStream(pipeOutput, true);
Instance instance = new Instance(databaseDir, createDbAllowed, output, additionalJars);
interpreter = new Interpreter(instance.getDatabase(), output);
instance.announceActive(output);
output.println("<EOT>");
}
public InputStream getServerResponseInputStream() throws IOException {
return input;
}
private static abstract class Action {
public abstract void execute() throws ParseException;
}
private void send(Action action) throws IOException, ExceptionFatal {
try {
action.execute();
} catch (ParseException pe) {
interpreter.reset();
output.println("ERROR: " + ParseExceptionPrinter.getParseExceptionMessage(pe));
} catch (TokenMgrError tme) {
interpreter.reset();
output.println("ERROR: " + tme.getMessage());
} catch (ExceptionSemantic es) {
interpreter.reset();
output.println("ERROR: " + es.getMessage());
} catch (ExceptionFatal et) {
interpreter.reset();
output.println("ERROR: " + et.getMessage());
et.printStackTrace(output);
et.printStackTrace();
throw et;
} catch (Throwable t) {
interpreter.reset();
output.println("ERROR: " + t);
t.printStackTrace(output);
t.printStackTrace();
throw t;
}
output.println("<EOT>");
}
public void sendEvaluate(final String source) throws IOException {
send(new Action() {
public void execute() throws ParseException {
interpreter.evaluate(source).toStream(output);
output.println();
}
});
}
public void sendExecute(final String source) throws IOException {
send(new Action() {
public void execute() throws ParseException {
interpreter.interpret(source);
output.println("\nOk.");
}
});
}
public void reset() {
interpreter.reset();
output.println();
output.println("Cancel.");
}
}
|
ServerV0000/src/org/reldb/rel/v0/engine/Rel.java
|
package org.reldb.rel.v0.engine;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import org.reldb.rel.exceptions.DatabaseFormatVersionException;
import org.reldb.rel.exceptions.ExceptionFatal;
import org.reldb.rel.exceptions.ExceptionSemantic;
import org.reldb.rel.v0.interpreter.ClassPathHack;
import org.reldb.rel.v0.interpreter.Instance;
import org.reldb.rel.v0.interpreter.Interpreter;
import org.reldb.rel.v0.interpreter.ParseExceptionPrinter;
import org.reldb.rel.v0.languages.tutoriald.parser.ParseException;
import org.reldb.rel.v0.languages.tutoriald.parser.TokenMgrError;
import org.reldb.rel.v0.version.Version;
/** Convenient access point for running an embedded or stand-alone interpreter. */
public class Rel {
private Interpreter interpreter;
private PipedInputStream input;
private PrintStream output;
private static void buildClasspath() throws IOException {
ClassPathHack.addFile(Version.getBerkeleyDbJarFilename());
ClassPathHack.addFile("relshared.jar");
ClassPathHack.addFile("ecj-4.4.2.jar");
}
/** Convenient runner for a stand-alone Rel interpreter.
* @throws IOException */
public static void main(String[] args) throws IOException {
buildClasspath();
org.reldb.rel.v0.interpreter.Instance.main(args);
}
/** Open this database and back it up to the named file. */
public static void backup(String databaseDir, String backupFileName) throws IOException, ParseException, DatabaseFormatVersionException {
buildClasspath();
PrintStream output = new PrintStream(backupFileName);
Instance instance = new Instance(databaseDir, false, output);
Interpreter interpreter = new Interpreter(instance.getDatabase(), output);
interpreter.interpret("BACKUP;");
output.close();
instance.close();
}
/** Establish a connection with this server. */
public Rel(String databaseDir, boolean createDbAllowed, String[] additionalJars) throws IOException, DatabaseFormatVersionException {
buildClasspath();
input = new PipedInputStream();
PipedOutputStream pipeOutput = new PipedOutputStream(input);
output = new PrintStream(pipeOutput, true);
Instance instance = new Instance(databaseDir, createDbAllowed, output, additionalJars);
interpreter = new Interpreter(instance.getDatabase(), output);
instance.announceActive(output);
output.println("<EOT>");
}
public InputStream getServerResponseInputStream() throws IOException {
return input;
}
private static abstract class Action {
public abstract void execute() throws ParseException;
}
private void send(Action action) throws IOException, ExceptionFatal {
try {
action.execute();
} catch (ParseException pe) {
interpreter.reset();
output.println("ERROR: " + ParseExceptionPrinter.getParseExceptionMessage(pe));
} catch (TokenMgrError tme) {
interpreter.reset();
output.println("ERROR: " + tme.getMessage());
} catch (ExceptionSemantic es) {
interpreter.reset();
output.println("ERROR: " + es.getMessage());
} catch (ExceptionFatal et) {
interpreter.reset();
output.println("ERROR: " + et.getMessage());
et.printStackTrace(output);
et.printStackTrace();
throw et;
} catch (Throwable t) {
interpreter.reset();
output.println("ERROR: " + t);
t.printStackTrace(output);
t.printStackTrace();
throw t;
}
output.println("<EOT>");
}
public void sendEvaluate(final String source) throws IOException {
send(new Action() {
public void execute() throws ParseException {
interpreter.evaluate(source).toStream(output);
output.println();
}
});
}
public void sendExecute(final String source) throws IOException {
send(new Action() {
public void execute() throws ParseException {
interpreter.interpret(source);
output.println("\nOk.");
}
});
}
public void reset() {
interpreter.reset();
output.println();
output.println("Cancel.");
}
}
|
Implement Rel.convertToLatestFormat()
|
ServerV0000/src/org/reldb/rel/v0/engine/Rel.java
|
Implement Rel.convertToLatestFormat()
|
<ide><path>erverV0000/src/org/reldb/rel/v0/engine/Rel.java
<ide> package org.reldb.rel.v0.engine;
<ide>
<add>import java.io.File;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.io.PipedInputStream;
<ide> instance.close();
<ide> }
<ide>
<add> /** Convert this database to the latest format, if necessary. Throw exception if not necessary. Normally only needed if invoking
<add> * the constructor throws DatabaseFormatVersionException. */
<add> public static void convertToLatestFormat(String databaseDir, PrintStream conversionOutput, String[] additionalJars) throws DatabaseFormatVersionException, IOException {
<add> buildClasspath();
<add> Instance.convertToLatestFormat(new File(databaseDir), conversionOutput, additionalJars);
<add> }
<add>
<ide> /** Establish a connection with this server. */
<ide> public Rel(String databaseDir, boolean createDbAllowed, String[] additionalJars) throws IOException, DatabaseFormatVersionException {
<ide> buildClasspath();
|
|
Java
|
apache-2.0
|
b21da1e14ad4188c4e66b8ac76cb6254cadf2f21
| 0 |
suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,da1z/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,allotria/intellij-community,da1z/intellij-community,ibinti/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,allotria/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,apixandru/intellij-community,xfournet/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.light;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.ItemPresentationProviders;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.util.ObjectUtils.notNull;
public class LightJavaModule extends LightElement implements PsiJavaModule {
private final LightJavaModuleReferenceElement myRefElement;
private final VirtualFile myJarRoot;
private final NotNullLazyValue<List<PsiPackageAccessibilityStatement>> myExports = AtomicNotNullLazyValue.createValue(() -> findExports());
private LightJavaModule(@NotNull PsiManager manager, @NotNull VirtualFile jarRoot) {
super(manager, JavaLanguage.INSTANCE);
myJarRoot = jarRoot;
myRefElement = new LightJavaModuleReferenceElement(manager, moduleName(jarRoot.getNameWithoutExtension()));
}
@NotNull
public VirtualFile getRootVirtualFile() {
return myJarRoot;
}
@Nullable
@Override
public PsiDocComment getDocComment() {
return null;
}
@NotNull
@Override
public Iterable<PsiRequiresStatement> getRequires() {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<PsiPackageAccessibilityStatement> getExports() {
return myExports.getValue();
}
private List<PsiPackageAccessibilityStatement> findExports() {
List<PsiPackageAccessibilityStatement> exports = ContainerUtil.newArrayList();
VfsUtilCore.visitChildrenRecursively(myJarRoot, new VirtualFileVisitor() {
private JavaDirectoryService service = JavaDirectoryService.getInstance();
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (file.isDirectory() && !myJarRoot.equals(file)) {
PsiDirectory directory = myManager.findDirectory(file);
if (directory != null) {
PsiPackage pkg = service.getPackage(directory);
if (pkg != null) {
String packageName = pkg.getQualifiedName();
if (!packageName.isEmpty() && !PsiUtil.isPackageEmpty(new PsiDirectory[]{directory}, packageName)) {
exports.add(new LightPackageAccessibilityStatement(myManager, packageName));
}
}
}
}
return true;
}
});
return exports;
}
@NotNull
@Override
public Iterable<PsiPackageAccessibilityStatement> getOpens() {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<PsiUsesStatement> getUses() {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<PsiProvidesStatement> getProvides() {
return Collections.emptyList();
}
@NotNull
@Override
public PsiJavaModuleReferenceElement getNameIdentifier() {
return myRefElement;
}
@NotNull
@Override
public String getName() {
return myRefElement.getReferenceText();
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Cannot modify automatic module '" + getName() + "'");
}
@Override
public PsiModifierList getModifierList() {
return null;
}
@Override
public boolean hasModifierProperty(@NotNull String name) {
return false;
}
@Override
public ItemPresentation getPresentation() {
return ItemPresentationProviders.getItemPresentation(this);
}
@NotNull
@Override
public PsiElement getNavigationElement() {
return notNull(myManager.findDirectory(myJarRoot), super.getNavigationElement());
}
@Override
public boolean equals(Object obj) {
return obj instanceof LightJavaModule && myJarRoot.equals(((LightJavaModule)obj).myJarRoot) && getManager() == ((LightJavaModule)obj).getManager();
}
@Override
public int hashCode() {
return getName().hashCode() * 31 + getManager().hashCode();
}
@Override
public String toString() {
return "PsiJavaModule:" + getName();
}
private static class LightJavaModuleReferenceElement extends LightElement implements PsiJavaModuleReferenceElement {
private final String myText;
public LightJavaModuleReferenceElement(@NotNull PsiManager manager, @NotNull String text) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
}
@NotNull
@Override
public String getReferenceText() {
return myText;
}
@Nullable
@Override
public PsiPolyVariantReference getReference() {
return null;
}
@Override
public String toString() {
return "PsiJavaModuleReference";
}
}
private static class LightPackageAccessibilityStatement extends LightElement implements PsiPackageAccessibilityStatement {
private final String myPackageName;
public LightPackageAccessibilityStatement(@NotNull PsiManager manager, @NotNull String packageName) {
super(manager, JavaLanguage.INSTANCE);
myPackageName = packageName;
}
@NotNull
@Override
public Role getRole() {
return Role.EXPORTS;
}
@Nullable
@Override
public PsiJavaCodeReferenceElement getPackageReference() {
return null;
}
@Nullable
@Override
public String getPackageName() {
return myPackageName;
}
@NotNull
@Override
public Iterable<PsiJavaModuleReferenceElement> getModuleReferences() {
return Collections.emptyList();
}
@NotNull
@Override
public List<String> getModuleNames() {
return Collections.emptyList();
}
@Override
public String toString() {
return "PsiPackageAccessibilityStatement";
}
}
@NotNull
public static LightJavaModule getModule(@NotNull PsiManager manager, @NotNull VirtualFile jarRoot) {
PsiDirectory directory = manager.findDirectory(jarRoot);
assert directory != null : jarRoot;
return CachedValuesManager.getCachedValue(directory, () -> {
LightJavaModule module = new LightJavaModule(manager, jarRoot);
return CachedValueProvider.Result.create(module, directory);
});
}
/**
* Implements a name deriving for automatic modules as described in ModuleFinder.of(Path...) method documentation.
*
* @param name a .jar file name without extension
* @see <a href="http://download.java.net/java/jdk9/docs/api/java/lang/module/ModuleFinder.html#of-java.nio.file.Path...-">ModuleFinder.of(Path...)</a>
*/
@NotNull
public static String moduleName(@NotNull String name) {
// If the name matches the regular expression "-(\\d+(\\.|$))" then the module name will be derived from the sub-sequence
// preceding the hyphen of the first occurrence.
Matcher m = Patterns.VERSION.matcher(name);
if (m.find()) {
name = name.substring(0, m.start());
}
// All non-alphanumeric characters ([^A-Za-z0-9]) are replaced with a dot (".") ...
name = Patterns.NON_NAME.matcher(name).replaceAll(".");
// ... all repeating dots are replaced with one dot ...
name = Patterns.DOT_SEQUENCE.matcher(name).replaceAll(".");
// ... and all leading and trailing dots are removed.
name = StringUtil.trimLeading(StringUtil.trimTrailing(name, '.'), '.');
return name;
}
private static class Patterns {
private static final Pattern VERSION = Pattern.compile("-(\\d+(\\.|$))");
private static final Pattern NON_NAME = Pattern.compile("[^A-Za-z0-9]");
private static final Pattern DOT_SEQUENCE = Pattern.compile("\\.{2,}");
}
}
|
java/java-psi-impl/src/com/intellij/psi/impl/light/LightJavaModule.java
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.light;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.ItemPresentationProviders;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.intellij.util.ObjectUtils.notNull;
public class LightJavaModule extends LightElement implements PsiJavaModule {
private final LightJavaModuleReferenceElement myRefElement;
private final VirtualFile myJarRoot;
private final NotNullLazyValue<List<PsiPackageAccessibilityStatement>> myExports = AtomicNotNullLazyValue.createValue(() -> findExports());
private LightJavaModule(@NotNull PsiManager manager, @NotNull VirtualFile jarRoot) {
super(manager, JavaLanguage.INSTANCE);
myJarRoot = jarRoot;
myRefElement = new LightJavaModuleReferenceElement(manager, moduleName(jarRoot.getNameWithoutExtension()));
}
@NotNull
public VirtualFile getRootVirtualFile() {
return myJarRoot;
}
@Nullable
@Override
public PsiDocComment getDocComment() {
return null;
}
@NotNull
@Override
public Iterable<PsiRequiresStatement> getRequires() {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<PsiPackageAccessibilityStatement> getExports() {
return myExports.getValue();
}
private List<PsiPackageAccessibilityStatement> findExports() {
List<PsiPackageAccessibilityStatement> exports = ContainerUtil.newArrayList();
VfsUtilCore.visitChildrenRecursively(myJarRoot, new VirtualFileVisitor() {
private JavaDirectoryService service = JavaDirectoryService.getInstance();
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (file.isDirectory() && !myJarRoot.equals(file)) {
PsiDirectory directory = myManager.findDirectory(file);
if (directory != null) {
PsiPackage pkg = service.getPackage(directory);
if (pkg != null) {
String packageName = pkg.getQualifiedName();
if (!packageName.isEmpty() && !PsiUtil.isPackageEmpty(new PsiDirectory[]{directory}, packageName)) {
exports.add(new LightPackageAccessibilityStatement(myManager, packageName));
}
}
}
}
return true;
}
});
return exports;
}
@NotNull
@Override
public Iterable<PsiPackageAccessibilityStatement> getOpens() {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<PsiUsesStatement> getUses() {
return Collections.emptyList();
}
@NotNull
@Override
public Iterable<PsiProvidesStatement> getProvides() {
return Collections.emptyList();
}
@NotNull
@Override
public PsiJavaModuleReferenceElement getNameIdentifier() {
return myRefElement;
}
@NotNull
@Override
public String getName() {
return myRefElement.getReferenceText();
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Cannot modify automatic module '" + getName() + "'");
}
@Override
public PsiModifierList getModifierList() {
return null;
}
@Override
public boolean hasModifierProperty(@NotNull String name) {
return false;
}
@Override
public ItemPresentation getPresentation() {
return ItemPresentationProviders.getItemPresentation(this);
}
@NotNull
@Override
public PsiElement getNavigationElement() {
return notNull(myManager.findDirectory(myJarRoot), super.getNavigationElement());
}
@Override
public boolean equals(Object obj) {
return obj instanceof LightJavaModule && myJarRoot.equals(((LightJavaModule)obj).myJarRoot) && getManager() == ((LightJavaModule)obj).getManager();
}
@Override
public int hashCode() {
return getName().hashCode() * 31 + getManager().hashCode();
}
@Override
public String toString() {
return "PsiJavaModule:" + getName();
}
private static class LightJavaModuleReferenceElement extends LightElement implements PsiJavaModuleReferenceElement {
private final String myText;
public LightJavaModuleReferenceElement(@NotNull PsiManager manager, @NotNull String text) {
super(manager, JavaLanguage.INSTANCE);
myText = text;
}
@NotNull
@Override
public String getReferenceText() {
return myText;
}
@Nullable
@Override
public PsiPolyVariantReference getReference() {
return null;
}
@Override
public String toString() {
return "PsiJavaModuleReference";
}
}
private static class LightPackageAccessibilityStatement extends LightElement implements PsiPackageAccessibilityStatement {
private final String myPackageName;
public LightPackageAccessibilityStatement(@NotNull PsiManager manager, @NotNull String packageName) {
super(manager, JavaLanguage.INSTANCE);
myPackageName = packageName;
}
@NotNull
@Override
public Role getRole() {
return Role.EXPORTS;
}
@Nullable
@Override
public PsiJavaCodeReferenceElement getPackageReference() {
return null;
}
@Nullable
@Override
public String getPackageName() {
return myPackageName;
}
@NotNull
@Override
public Iterable<PsiJavaModuleReferenceElement> getModuleReferences() {
return Collections.emptyList();
}
@NotNull
@Override
public List<String> getModuleNames() {
return Collections.emptyList();
}
@Override
public String toString() {
return "PsiPackageAccessibilityStatement";
}
}
@NotNull
public static LightJavaModule getModule(@NotNull final PsiManager manager, @NotNull final VirtualFile jarRoot) {
final PsiDirectory directory = manager.findDirectory(jarRoot);
assert directory != null : jarRoot;
return CachedValuesManager.getCachedValue(directory, () -> {
LightJavaModule module = new LightJavaModule(manager, jarRoot);
return CachedValueProvider.Result.create(module, directory);
});
}
/**
* Implements a name deriving for automatic modules as described in ModuleFinder.of(Path...) method documentation.
*
* @param name a .jar file name without extension
* @see <a href="http://download.java.net/java/jdk9/docs/api/java/lang/module/ModuleFinder.html#of-java.nio.file.Path...-">ModuleFinder.of(Path...)</a>
*/
@NotNull
public static String moduleName(@NotNull String name) {
// If the name matches the regular expression "-(\\d+(\\.|$))" then the module name will be derived from the sub-sequence
// preceding the hyphen of the first occurrence.
Matcher m = Patterns.VERSION.matcher(name);
if (m.find()) {
name = name.substring(0, m.start());
}
// All non-alphanumeric characters ([^A-Za-z0-9]) are replaced with a dot (".") ...
name = Patterns.NON_NAME.matcher(name).replaceAll(".");
// ... all repeating dots are replaced with one dot ...
name = Patterns.DOT_SEQUENCE.matcher(name).replaceAll(".");
// ... and all leading and trailing dots are removed.
name = StringUtil.trimLeading(StringUtil.trimTrailing(name, '.'), '.');
return name;
}
private static class Patterns {
private static final Pattern VERSION = Pattern.compile("-(\\d+(\\.|$))");
private static final Pattern NON_NAME = Pattern.compile("[^A-Za-z0-9]");
private static final Pattern DOT_SEQUENCE = Pattern.compile("\\.{2,}");
}
}
|
Cleanup (formatting)
|
java/java-psi-impl/src/com/intellij/psi/impl/light/LightJavaModule.java
|
Cleanup (formatting)
|
<ide><path>ava/java-psi-impl/src/com/intellij/psi/impl/light/LightJavaModule.java
<ide> }
<ide>
<ide> @NotNull
<del> public static LightJavaModule getModule(@NotNull final PsiManager manager, @NotNull final VirtualFile jarRoot) {
<del> final PsiDirectory directory = manager.findDirectory(jarRoot);
<add> public static LightJavaModule getModule(@NotNull PsiManager manager, @NotNull VirtualFile jarRoot) {
<add> PsiDirectory directory = manager.findDirectory(jarRoot);
<ide> assert directory != null : jarRoot;
<ide> return CachedValuesManager.getCachedValue(directory, () -> {
<ide> LightJavaModule module = new LightJavaModule(manager, jarRoot);
|
|
JavaScript
|
bsd-3-clause
|
a904527bd0169a7ef4176ba6a0d93d55317ea6bd
| 0 |
redaktor/deliteful
|
dojo.provide("dojox.grid.DataGrid");
dojo.require("dojox.grid._Grid");
dojo.require("dojox.grid.DataSelection");
dojo.declare("dojox.grid.DataGrid", dojox.grid._Grid, {
store: null,
query: null,
queryOptions: null,
fetchText: '...',
_store_connects: null,
_by_idty: null,
_by_idx: null,
_cache: null,
_pages: null,
_pending_requests: null,
_bop: -1,
_eop: -1,
_requests: 0,
rowCount: 0,
_isLoaded: false,
_isLoading: false,
postCreate: function(){
this._pages = [];
this._store_connects = [];
this._by_idty = {};
this._by_idx = [];
this._cache = [];
this._pending_requests = {};
this._setStore(this.store);
this.inherited(arguments);
},
createSelection: function(){
this.selection = new dojox.grid.DataSelection(this);
},
get: function(inRowIndex, inItem){
return (!inItem ? this.defaultValue : (!this.field ? this.value : this.grid.store.getValue(inItem, this.field)));
},
_onSet: function(item, attribute, oldValue, newValue){
var idx = this.getItemIndex(item);
if(idx>-1){
this.updateRow(idx);
}
},
_addItem: function(item, index){
var idty = this._hasIdentity ? this.store.getIdentity(item) : dojo.toJson(this.query) + ":idx:" + index + ":sort:" + dojo.toJson(this.getSortProps());
var o = { idty: idty, item: item };
this._by_idty[idty] = this._by_idx[index] = o;
this.updateRow(index);
},
_onNew: function(item, parentInfo){
this.updateRowCount(this.rowCount+1);
this._addItem(item, this.rowCount-1);
this.showMessage();
},
_onDelete: function(item){
var idx = this._getItemIndex(item, true);
if(idx >= 0){
var o = this._by_idx[idx];
this._by_idx.splice(idx, 1);
delete this._by_idty[o.idty];
this.updateRowCount(this.rowCount-1);
if(this.rowCount === 0){
this.showMessage(this.noDataMessage);
}
}
},
_onRevert: function(){
this._refresh();
},
setStore: function(store){
this._setStore(store);
this._refresh(true);
},
_setStore: function(store){
if(this.store&&this._store_connects){
dojo.forEach(this._store_connects,function(arr){
dojo.forEach(arr, dojo.disconnect);
});
}
this.store = store;
if(this.store){
var f = this.store.getFeatures();
var h = [];
this._canEdit = !!f["dojo.data.api.Write"] && !!f["dojo.data.api.Identity"];
this._hasIdentity = !!f["dojo.data.api.Identity"];
if(!!f["dojo.data.api.Notification"]){
h.push(this.connect(this.store, "onSet", "_onSet"));
h.push(this.connect(this.store, "onNew", "_onNew"));
h.push(this.connect(this.store, "onDelete", "_onDelete"));
}
if(this._canEdit){
h.push(this.connect(this.store, "revert", "_onRevert"));
}
this._store_connects = h;
}
},
_onFetchBegin: function(size, req){
if(this.rowCount != size){
if(req.isRender){
this.scroller.init(size, this.keepRows, this.rowsPerPage);
this.prerender();
}
this.updateRowCount(size);
}
},
_onFetchComplete: function(items, req){
if(items && items.length > 0){
//console.log(items);
dojo.forEach(items, function(item, idx){
this._addItem(item, req.start+idx);
}, this);
if(req.isRender){
this.setScrollTop(0);
this.postrender();
}
}
if(!this._isLoaded){
this._isLoading = false;
this._isLoaded = true;
if(!items || !items.length){
this.showMessage(this.noDataMessage);
}else{
this.showMessage();
}
}
this._pending_requests[req.start] = false;
},
_onFetchError: function(err, req){
console.log(err);
if(!this._isLoaded){
this._isLoading = false;
this._isLoaded = true;
this.showMessage(this.errorMessage);
}
this.onFetchError(err, req);
},
onFetchError: function(err, req){
},
_fetch: function(start, isRender){
var start = start || 0;
if(this.store && !this._pending_requests[start]){
if(!this._isLoaded && !this._isLoading){
this._isLoading = true;
this.showMessage(this.loadingMessage);
}
this._pending_requests[start] = true;
//console.log("fetch: ", start);
this.store.fetch({
start: start,
count: this.rowsPerPage,
query: this.query,
sort: this.getSortProps(),
queryOptions: this.queryOptions,
isRender: isRender,
onBegin: dojo.hitch(this, "_onFetchBegin"),
onComplete: dojo.hitch(this, "_onFetchComplete"),
onError: dojo.hitch(this, "_onFetchError")
});
}
},
_clearData: function(){
this.rowCount = 0;
this._by_idty = {};
this._by_idx = [];
this._pages = [];
this._bop = this._eop = -1;
},
getItem: function(idx){
var data = this._by_idx[idx];
if(!data||(data&&!data.item)){
this._preparePage(idx);
return null;
}
return data.item;
},
getItemIndex: function(item){
return this._getItemIndex(item, false);
},
_getItemIndex: function(item, isDeleted){
if(!isDeleted && !this.store.isItem(item)){
return -1;
}
var idty = this._hasIdentity ? this.store.getIdentity(item) : null;
for(var i=0, l=this._by_idx.length; i<l; i++){
var d = this._by_idx[i];
if(d && ((idty && d.idty == idty) || (d.item === item))){
return i;
}
}
return -1;
},
filter: function(query, reRender){
this.query = query;
if(reRender){
this._clearData();
}
this._fetch();
},
_getItemAttr: function(idx, attr){
var item = this.getItem(idx);
return (!item ? this.fetchText : this.store.getValue(item, attr));
},
// rendering
_render: function(){
if(this.domNode.parentNode){
this.scroller.init(this.rowCount, this.keepRows, this.rowsPerPage);
this.prerender();
this._fetch(0, true);
}
},
renderRows: function(inPageIndex, inRowsPerPage){
this.views.renderRows(inPageIndex, inRowsPerPage);
},
// paging
_requestsPending: function(inRowIndex){
return this._pending_requests[inRowIndex];
},
_rowToPage: function(inRowIndex){
return (this.rowsPerPage ? Math.floor(inRowIndex / this.rowsPerPage) : inRowIndex);
},
_pageToRow: function(inPageIndex){
return (this.rowsPerPage ? this.rowsPerPage * inPageIndex : inPageIndex);
},
_preparePage: function(inRowIndex){
if(inRowIndex < this._bop || inRowIndex >= this._eop){
var pageIndex = this._rowToPage(inRowIndex);
this._needPage(pageIndex);
this._bop = pageIndex * this.rowsPerPage;
this._eop = this._bop + (this.rowsPerPage || this.rowCount);
}
},
_needPage: function(inPageIndex){
if(!this._pages[inPageIndex]){
this._pages[inPageIndex] = true;
this._requestPage(inPageIndex);
}
},
_requestPage: function(inPageIndex){
var row = this._pageToRow(inPageIndex);
var count = Math.min(this.rowsPerPage, this.rowCount - row);
if(count > 0){
this._requests++;
if(!this._requestsPending(row)){
setTimeout(dojo.hitch(this, "_fetch", row, false), 1);
//this.requestRows(row, count);
}
}
},
getCellName: function(inCell){
return inCell.field;
//console.log(inCell);
},
_refresh: function(isRender){
this._clearData();
this._fetch(0, isRender);
},
sort: function(){
this._refresh();
},
canSort: function(){
return true;
},
getSortProps: function(){
var c = this.getCell(this.getSortIndex());
if(!c){
return null;
}else{
var desc = c["sortDesc"];
var si = !(this.sortInfo>0);
if(typeof desc == "undefined"){
desc = si;
}else{
desc = si ? !desc : desc;
}
return [{ attribute: c.field, descending: desc }];
}
},
styleRowState: function(inRow){
// summary: Perform row styling
if(this.store && this.store.getState){
var states=this.store.getState(inRow.index), c='';
for(var i=0, ss=["inflight", "error", "inserting"], s; s=ss[i]; i++){
if(states[s]){
c = ' dojoxGrid-row-' + s;
break;
}
}
inRow.customClasses += c;
}
},
onStyleRow: function(inRow){
this.styleRowState(inRow);
this.inherited(arguments);
},
// editing
canEdit: function(inCell, inRowIndex){
return this._canEdit;
},
_copyAttr: function(idx, attr){
var row = {};
var backstop = {};
var src = this.getItem(idx);
return this.store.getValue(src, attr);
},
doStartEdit: function(inCell, inRowIndex){
if(!this._cache[inRowIndex]){
this._cache[inRowIndex] = this._copyAttr(inRowIndex, inCell.field);
}
this.onStartEdit(inCell, inRowIndex);
},
doApplyCellEdit: function(inValue, inRowIndex, inAttrName){
this.store.fetchItemByIdentity({
identity: this._by_idx[inRowIndex].idty,
onItem: dojo.hitch(this, function(item){
this.store.setValue(item, inAttrName, inValue);
this.onApplyCellEdit(inValue, inRowIndex, inAttrName);
})
});
},
doCancelEdit: function(inRowIndex){
var cache = this._cache[inRowIndex];
if(cache){
this.updateRow(inRowIndex);
delete this._cache[inRowIndex];
}
this.onCancelEdit.apply(this, arguments);
},
doApplyEdit: function(inRowIndex, inDataAttr){
var cache = this._cache[inRowIndex];
/*if(cache){
var data = this.getItem(inRowIndex);
if(this.store.getValue(data, inDataAttr) != cache){
this.update(cache, data, inRowIndex);
}
delete this._cache[inRowIndex];
}*/
this.onApplyEdit(inRowIndex);
},
removeSelectedRows: function(){
// summary:
// Remove the selected rows from the grid.
if(this._canEdit){
this.edit.apply();
var items = this.selection.getSelected();
if(items.length){
dojo.forEach(items, this.store.deleteItem, this.store);
this.selection.clear();
}
}
}
});
dojox.grid.DataGrid.markupFactory = function(props, node, ctor){
return dojox.grid._Grid.markupFactory(props, node, ctor, function(node, cellDef){
var field = dojo.trim(dojo.attr(node, "field")||"");
if(field){
cellDef.field = field;
}
cellDef.field = cellDef.field||cellDef.name;
});
}
|
grid/DataGrid.js
|
dojo.provide("dojox.grid.DataGrid");
dojo.require("dojox.grid._Grid");
dojo.require("dojox.grid.DataSelection");
dojo.declare("dojox.grid.DataGrid", dojox.grid._Grid, {
store: null,
query: null,
queryOptions: null,
fetchText: '...',
_store_connects: null,
_by_idty: null,
_by_idx: null,
_cache: null,
_pages: null,
_pending_requests: null,
_bop: -1,
_eop: -1,
_requests: 0,
rowCount: 0,
_isLoaded: false,
_isLoading: false,
postCreate: function(){
this._pages = [];
this._store_connects = [];
this._by_idty = {};
this._by_idx = [];
this._cache = [];
this._pending_requests = {};
this._setStore(this.store);
this.inherited(arguments);
},
createSelection: function(){
this.selection = new dojox.grid.DataSelection(this);
},
get: function(inRowIndex, inItem){
return (!inItem ? this.defaultValue : (!this.field ? this.value : this.grid.store.getValue(inItem, this.field)));
},
_onSet: function(item, attribute, oldValue, newValue){
var idx = this.getItemIndex(item);
if(idx>-1){
this.updateRow(idx);
}
},
_addItem: function(item, index){
var idty = this._hasIdentity ? this.store.getIdentity(item) : dojo.toJson(this.query) + ":idx:" + index + ":sort:" + dojo.toJson(this.getSortProps());
var o = { idty: idty, item: item };
this._by_idty[idty] = this._by_idx[index] = o;
this.updateRow(index);
},
_onNew: function(item, parentInfo){
this.updateRowCount(this.rowCount+1);
this._addItem(item, this.rowCount-1);
},
_onDelete: function(item){
var idx = this._getItemIndex(item, true);
if(idx >= 0){
var o = this._by_idx[idx];
this._by_idx.splice(idx, 1);
delete this._by_idty[o.idty];
this.updateRowCount(this.rowCount-1);
}
},
_onRevert: function(){
this._refresh();
},
setStore: function(store){
this._setStore(store);
this._refresh(true);
},
_setStore: function(store){
if(this.store&&this._store_connects){
dojo.forEach(this._store_connects,function(arr){
dojo.forEach(arr, dojo.disconnect);
});
}
this.store = store;
if(this.store){
var f = this.store.getFeatures();
var h = [];
this._canEdit = !!f["dojo.data.api.Write"] && !!f["dojo.data.api.Identity"];
this._hasIdentity = !!f["dojo.data.api.Identity"];
if(!!f["dojo.data.api.Notification"]){
h.push(this.connect(this.store, "onSet", "_onSet"));
h.push(this.connect(this.store, "onNew", "_onNew"));
h.push(this.connect(this.store, "onDelete", "_onDelete"));
}
if(this._canEdit){
h.push(this.connect(this.store, "revert", "_onRevert"));
}
this._store_connects = h;
}
},
_onFetchBegin: function(size, req){
if(this.rowCount != size){
if(req.isRender){
this.scroller.init(size, this.keepRows, this.rowsPerPage);
this.prerender();
}
this.updateRowCount(size);
}
},
_onFetchComplete: function(items, req){
if(items && items.length > 0){
//console.log(items);
dojo.forEach(items, function(item, idx){
this._addItem(item, req.start+idx);
}, this);
if(req.isRender){
this.setScrollTop(0);
this.postrender();
}
}
if(!this._isLoaded){
this._isLoading = false;
this._isLoaded = true;
if(!items || !items.length){
this.showMessage(this.noDataMessage);
}else{
this.showMessage();
}
}
this._pending_requests[req.start] = false;
},
_onFetchError: function(err, req){
console.log(err);
if(!this._isLoaded){
this._isLoading = false;
this._isLoaded = true;
this.showMessage(this.errorMessage);
}
this.onFetchError(err, req);
},
onFetchError: function(err, req){
},
_fetch: function(start, isRender){
var start = start || 0;
if(this.store && !this._pending_requests[start]){
if(!this._isLoaded && !this._isLoading){
this._isLoading = true;
this.showMessage(this.loadingMessage);
}
this._pending_requests[start] = true;
//console.log("fetch: ", start);
this.store.fetch({
start: start,
count: this.rowsPerPage,
query: this.query,
sort: this.getSortProps(),
queryOptions: this.queryOptions,
isRender: isRender,
onBegin: dojo.hitch(this, "_onFetchBegin"),
onComplete: dojo.hitch(this, "_onFetchComplete"),
onError: dojo.hitch(this, "_onFetchError")
});
}
},
_clearData: function(){
this.rowCount = 0;
this._by_idty = {};
this._by_idx = [];
this._pages = [];
this._bop = this._eop = -1;
},
getItem: function(idx){
var data = this._by_idx[idx];
if(!data||(data&&!data.item)){
this._preparePage(idx);
return null;
}
return data.item;
},
getItemIndex: function(item){
return this._getItemIndex(item, false);
},
_getItemIndex: function(item, isDeleted){
if(!isDeleted && !this.store.isItem(item)){
return -1;
}
var idty = this._hasIdentity ? this.store.getIdentity(item) : null;
for(var i=0, l=this._by_idx.length; i<l; i++){
var d = this._by_idx[i];
if(d && ((idty && d.idty == idty) || (d.item === item))){
return i;
}
}
return -1;
},
filter: function(query, reRender){
this.query = query;
if(reRender){
this._clearData();
}
this._fetch();
},
_getItemAttr: function(idx, attr){
var item = this.getItem(idx);
return (!item ? this.fetchText : this.store.getValue(item, attr));
},
// rendering
_render: function(){
if(this.domNode.parentNode){
this.scroller.init(this.rowCount, this.keepRows, this.rowsPerPage);
this.prerender();
this._fetch(0, true);
}
},
renderRows: function(inPageIndex, inRowsPerPage){
this.views.renderRows(inPageIndex, inRowsPerPage);
},
// paging
_requestsPending: function(inRowIndex){
return this._pending_requests[inRowIndex];
},
_rowToPage: function(inRowIndex){
return (this.rowsPerPage ? Math.floor(inRowIndex / this.rowsPerPage) : inRowIndex);
},
_pageToRow: function(inPageIndex){
return (this.rowsPerPage ? this.rowsPerPage * inPageIndex : inPageIndex);
},
_preparePage: function(inRowIndex){
if(inRowIndex < this._bop || inRowIndex >= this._eop){
var pageIndex = this._rowToPage(inRowIndex);
this._needPage(pageIndex);
this._bop = pageIndex * this.rowsPerPage;
this._eop = this._bop + (this.rowsPerPage || this.rowCount);
}
},
_needPage: function(inPageIndex){
if(!this._pages[inPageIndex]){
this._pages[inPageIndex] = true;
this._requestPage(inPageIndex);
}
},
_requestPage: function(inPageIndex){
var row = this._pageToRow(inPageIndex);
var count = Math.min(this.rowsPerPage, this.rowCount - row);
if(count > 0){
this._requests++;
if(!this._requestsPending(row)){
setTimeout(dojo.hitch(this, "_fetch", row, false), 1);
//this.requestRows(row, count);
}
}
},
getCellName: function(inCell){
return inCell.field;
//console.log(inCell);
},
_refresh: function(isRender){
this._clearData();
this._fetch(0, isRender);
},
sort: function(){
this._refresh();
},
canSort: function(){
return true;
},
getSortProps: function(){
var c = this.getCell(this.getSortIndex());
if(!c){
return null;
}else{
var desc = c["sortDesc"];
var si = !(this.sortInfo>0);
if(typeof desc == "undefined"){
desc = si;
}else{
desc = si ? !desc : desc;
}
return [{ attribute: c.field, descending: desc }];
}
},
styleRowState: function(inRow){
// summary: Perform row styling
if(this.store && this.store.getState){
var states=this.store.getState(inRow.index), c='';
for(var i=0, ss=["inflight", "error", "inserting"], s; s=ss[i]; i++){
if(states[s]){
c = ' dojoxGrid-row-' + s;
break;
}
}
inRow.customClasses += c;
}
},
onStyleRow: function(inRow){
this.styleRowState(inRow);
this.inherited(arguments);
},
// editing
canEdit: function(inCell, inRowIndex){
return this._canEdit;
},
_copyAttr: function(idx, attr){
var row = {};
var backstop = {};
var src = this.getItem(idx);
return this.store.getValue(src, attr);
},
doStartEdit: function(inCell, inRowIndex){
if(!this._cache[inRowIndex]){
this._cache[inRowIndex] = this._copyAttr(inRowIndex, inCell.field);
}
this.onStartEdit(inCell, inRowIndex);
},
doApplyCellEdit: function(inValue, inRowIndex, inAttrName){
this.store.fetchItemByIdentity({
identity: this._by_idx[inRowIndex].idty,
onItem: dojo.hitch(this, function(item){
this.store.setValue(item, inAttrName, inValue);
this.onApplyCellEdit(inValue, inRowIndex, inAttrName);
})
});
},
doCancelEdit: function(inRowIndex){
var cache = this._cache[inRowIndex];
if(cache){
this.updateRow(inRowIndex);
delete this._cache[inRowIndex];
}
this.onCancelEdit.apply(this, arguments);
},
doApplyEdit: function(inRowIndex, inDataAttr){
var cache = this._cache[inRowIndex];
/*if(cache){
var data = this.getItem(inRowIndex);
if(this.store.getValue(data, inDataAttr) != cache){
this.update(cache, data, inRowIndex);
}
delete this._cache[inRowIndex];
}*/
this.onApplyEdit(inRowIndex);
},
removeSelectedRows: function(){
// summary:
// Remove the selected rows from the grid.
if(this._canEdit){
this.edit.apply();
var items = this.selection.getSelected();
if(items.length){
dojo.forEach(items, this.store.deleteItem, this.store);
this.selection.clear();
}
}
}
});
dojox.grid.DataGrid.markupFactory = function(props, node, ctor){
return dojox.grid._Grid.markupFactory(props, node, ctor, function(node, cellDef){
var field = dojo.trim(dojo.attr(node, "field")||"");
if(field){
cellDef.field = field;
}
cellDef.field = cellDef.field||cellDef.name;
});
}
|
Refs: #6590 - update messages when adding/removing the first/last row !strict
git-svn-id: ee6e786acc44c9cca5ee17c71a5576c45c210361@14212 560b804f-0ae3-0310-86f3-f6aa0a117693
|
grid/DataGrid.js
|
Refs: #6590 - update messages when adding/removing the first/last row !strict
|
<ide><path>rid/DataGrid.js
<ide> _onNew: function(item, parentInfo){
<ide> this.updateRowCount(this.rowCount+1);
<ide> this._addItem(item, this.rowCount-1);
<add> this.showMessage();
<ide> },
<ide>
<ide> _onDelete: function(item){
<ide> this._by_idx.splice(idx, 1);
<ide> delete this._by_idty[o.idty];
<ide> this.updateRowCount(this.rowCount-1);
<add> if(this.rowCount === 0){
<add> this.showMessage(this.noDataMessage);
<add> }
<ide> }
<ide> },
<ide>
|
|
Java
|
epl-1.0
|
c848dccdf601587fe48fc6e642dde2c39014266a
| 0 |
ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder
|
/*******************************************************************************
* Copyright (c) 2015 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.display.builder.representation.javafx;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.csstudio.display.builder.model.properties.ScriptInfo;
import org.csstudio.display.builder.model.properties.ScriptPV;
import org.csstudio.javafx.MultiLineInputDialog;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Window;
import javafx.util.Callback;
/** Dialog for editing {@link ScriptInfo}s
* @author Kay Kasemir
*/
public class ScriptsDialog extends Dialog<List<ScriptInfo>>
{
/** Modifiable ScriptPV */
private static class PVItem
{
public String name;
public BooleanProperty trigger = new SimpleBooleanProperty(true);
public PVItem(final String name, final boolean trigger)
{
this.name = name;
this.trigger.set(trigger);
}
public static PVItem forPV(final ScriptPV info)
{
return new PVItem(info.getName(), info.isTrigger());
}
public ScriptPV toScriptPV()
{
return new ScriptPV(name, trigger.get());
}
};
/** Modifiable ScriptInfo */
private static class ScriptItem
{
public StringProperty file = new SimpleStringProperty();
public String text;
public List<PVItem> pvs;
public ScriptItem()
{
this("", null, new ArrayList<>());
}
public ScriptItem(final String file, final String text, final List<PVItem> pvs)
{
this.file.set(file);
this.text = text;
this.pvs = pvs;
}
public static ScriptItem forInfo(final ScriptInfo info)
{
final List<PVItem> pvs = new ArrayList<>();
info.getPVs().forEach(pv -> pvs.add(PVItem.forPV(pv)));
return new ScriptItem(info.getFile(), info.getText(), pvs);
}
public ScriptInfo getScriptInfo()
{
final List<ScriptPV> spvs = new ArrayList<>();
pvs.forEach(pv -> spvs.add(pv.toScriptPV()));
return new ScriptInfo(file.get(), text, spvs);
}
};
/** Table cell with buttons to select file or edit the "embedded" script */
private static class ScriptButtonCell extends TableCell<ScriptItem, Boolean>
{
private final Button btn_file = new Button("File");
private final Button btn_embed = new Button("Embedded");
private final HBox buttons = new HBox(10, btn_file, btn_embed);
public ScriptButtonCell(TableColumn<ScriptItem, Boolean> col)
{
col.getTableView().getScene().getWindow();
Window window = null;
btn_file.setOnAction(event ->
{
final TableView<ScriptItem> table = col.getTableView();
final ScriptItem item = table.getItems().get(getTableRow().getIndex());
final FileChooser dlg = new FileChooser();
dlg.setTitle("Select Script");
if (item.file.get().length() > 0)
{
File file = new File(item.file.get());
dlg.setInitialDirectory(file.getParentFile());
dlg.setInitialFileName(file.getName());
}
dlg.getExtensionFilters().addAll(new ExtensionFilter("Script", "*.py"),
new ExtensionFilter("All", "*.*"));
final File result = dlg.showOpenDialog(window);
if (result != null)
{
item.file.set(result.getPath());
item.text = null;
}
});
btn_embed.setOnAction(event ->
{
final TableView<ScriptItem> table = col.getTableView();
final ScriptItem item = table.getItems().get(getTableRow().getIndex());
if (item.text == null || item.text.trim().isEmpty())
item.text = "# Embedded python script\n\n";
final MultiLineInputDialog dlg = new MultiLineInputDialog(table, item.text);
final Optional<String> result = dlg.showAndWait();
if (result.isPresent())
{
item.file.set(ScriptInfo.EMBEDDED_PYTHON);
item.text = result.get();
}
});
}
@Override
protected void updateItem(final Boolean item, final boolean empty)
{
setGraphic(empty ? null : buttons);
}
};
/** Data that is linked to the scripts_table */
private final ObservableList<ScriptItem> script_items = FXCollections.observableArrayList();
/** Table for all scripts */
private TableView<ScriptItem> scripts_table;
/** Data that is linked to the pvs_table */
private final ObservableList<PVItem> pv_items = FXCollections.observableArrayList();
/** Table for PVs of currently selected script */
private TableView<PVItem> pvs_table;
/** @param scripts Scripts to show/edit in the dialog */
public ScriptsDialog(final List<ScriptInfo> scripts)
{
setTitle("Scripts");
setHeaderText("Edit scripts and their PVs");
scripts.forEach(script -> script_items.add(ScriptItem.forInfo(script)));
fixupScripts(0);
getDialogPane().setContent(createContent());
getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
setResizable(true);
setResultConverter(button ->
{
if (button != ButtonType.OK)
return null;
return script_items.stream()
.filter(item -> ! item.file.get().isEmpty())
.map(ScriptItem::getScriptInfo)
.collect(Collectors.toList());
});
}
private Node createContent()
{
final Node scripts = createScriptsTable();
final Node pvs = createPVsTable();
// Display PVs of currently selected script
scripts_table.getSelectionModel().selectedItemProperty().addListener((prop, old, selected) ->
{
if (selected == null)
pv_items.clear();
else
{
pv_items.setAll(selected.pvs);
fixupPVs(0);
}
});
// Update PVs of selected script from PVs table
final ListChangeListener<PVItem> ll = change ->
{
final ScriptItem selected = scripts_table.getSelectionModel().getSelectedItem();
if (selected != null)
selected.pvs = new ArrayList<>(change.getList());
};
pv_items.addListener(ll);
final HBox box = new HBox(10, scripts, pvs);
HBox.setHgrow(scripts, Priority.ALWAYS);
HBox.setHgrow(pvs, Priority.ALWAYS);
// box.setStyle("-fx-background-color: rgb(255, 100, 0, 0.2);"); // For debugging
return box;
}
/** @return Node for UI elements that edit the scripts */
private Node createScriptsTable()
{
// Create table with editable script file column
final TableColumn<ScriptItem, String> name_col = new TableColumn<>("Scripts");
name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ScriptItem, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(final CellDataFeatures<ScriptItem, String> param)
{
final StringProperty file = param.getValue().file;
if (file.get().isEmpty())
return new ReadOnlyStringWrapper("<enter name>");
return file;
}
});
name_col.setCellFactory(TextFieldTableCell.<ScriptItem>forTableColumn());
name_col.setOnEditCommit(event ->
{
final int row = event.getTablePosition().getRow();
script_items.get(row).file.set(event.getNewValue());
fixupScripts(row);
});
// TODO Table column to select file or set to ScriptInfo.EMBEDDED_PYTHON
final TableColumn<ScriptItem, Boolean> embed_col = new TableColumn<>();
Callback<TableColumn<ScriptItem, Boolean>, TableCell<ScriptItem, Boolean>> embed_cell_factory = col ->
{
return new ScriptButtonCell(col);
};
embed_col.setCellFactory(embed_cell_factory);
scripts_table = new TableView<>(script_items);
scripts_table.getColumns().add(name_col);
scripts_table.getColumns().add(embed_col);
scripts_table.setEditable(true);
scripts_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
scripts_table.setTooltip(new Tooltip("Edit scripts. Add new script in last row"));
// Buttons
final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png"));
add.setMaxWidth(Double.MAX_VALUE);
add.setOnAction(event ->
{
script_items.add(new ScriptItem());
});
final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png"));
remove.setMaxWidth(Double.MAX_VALUE);
remove.setOnAction(event ->
{
final int sel = scripts_table.getSelectionModel().getSelectedIndex();
if (sel >= 0)
{
script_items.remove(sel);
fixupScripts(sel);
}
});
final VBox buttons = new VBox(10, add, remove);
final HBox content = new HBox(10, scripts_table, buttons);
HBox.setHgrow(scripts_table, Priority.ALWAYS);
return content;
}
/** Fix scripts data: Delete empty rows in middle, but keep one empty final row
* @param changed_row Row to check, and remove if it's empty
*/
private void fixupScripts(final int changed_row)
{
// Check if edited row is now empty and should be deleted
if (changed_row < script_items.size())
{
final ScriptItem item = script_items.get(changed_row);
if (item.file.get().trim().isEmpty())
script_items.remove(changed_row);
}
// Assert one empty row at bottom
final int len = script_items.size();
if (len <= 0 ||
script_items.get(len-1).file.get().trim().length() > 0)
script_items.add(new ScriptItem());
}
/** @return Node for UI elements that edit the PVs of a script */
private Node createPVsTable()
{
// Create table with editable column
final TableColumn<PVItem, String> name_col = new TableColumn<>("PVs");
name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PVItem, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(final CellDataFeatures<PVItem, String> param)
{
final String name = param.getValue().name;
if (name.isEmpty())
return new ReadOnlyStringWrapper("<enter name>");
return new ReadOnlyStringWrapper(name);
}
});
name_col.setCellFactory(TextFieldTableCell.<PVItem>forTableColumn());
name_col.setOnEditCommit(event ->
{
final int row = event.getTablePosition().getRow();
pv_items.get(row).name = event.getNewValue();
fixupPVs(row);
});
// Boolean Table column needs Observable. "OnEdit" is never called
final TableColumn<PVItem, Boolean> trigger_col = new TableColumn<>("Trigger Script?");
trigger_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PVItem, Boolean>, ObservableValue<Boolean>>()
{
@Override
public ObservableValue<Boolean> call(final CellDataFeatures<PVItem, Boolean> param)
{
return param.getValue().trigger;
}
});
trigger_col.setCellFactory(CheckBoxTableCell.<PVItem>forTableColumn(trigger_col));
pvs_table = new TableView<>(pv_items);
pvs_table.getColumns().add(name_col);
pvs_table.getColumns().add(trigger_col);
pvs_table.setEditable(true);
pvs_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
pvs_table.setTooltip(new Tooltip("Edit PVs. Add new PV in last row"));
pvs_table.setPlaceholder(new Label("Select Script to see PVs"));
// Buttons
final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png"));
add.setMaxWidth(Double.MAX_VALUE);
add.setOnAction(event ->
{
pv_items.add(new PVItem("", true));
});
final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png"));
remove.setMaxWidth(Double.MAX_VALUE);
remove.setOnAction(event ->
{
final int sel = pvs_table.getSelectionModel().getSelectedIndex();
if (sel >= 0)
{
pv_items.remove(sel);
fixupPVs(sel);
}
});
final VBox buttons = new VBox(10, add, remove);
final HBox content = new HBox(10, pvs_table, buttons);
HBox.setHgrow(pvs_table, Priority.ALWAYS);
return content;
}
/** Fix PVs data: Delete empty rows in middle, but keep one empty final row
* @param changed_row Row to check, and remove if it's empty
*/
private void fixupPVs(final int changed_row)
{
// Check if edited row is now empty and should be deleted
if (changed_row < pv_items.size())
{
final PVItem item = pv_items.get(changed_row);
if (item.name.trim().isEmpty())
pv_items.remove(changed_row);
}
// Assert one empty row at bottom
final int len = pv_items.size();
if (len <= 0 ||
pv_items.get(len-1).name.trim().length() > 0)
pv_items.add(new PVItem("", true));
}
}
|
org.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/ScriptsDialog.java
|
/*******************************************************************************
* Copyright (c) 2015 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.display.builder.representation.javafx;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.csstudio.display.builder.model.properties.ScriptInfo;
import org.csstudio.display.builder.model.properties.ScriptPV;
import org.csstudio.javafx.MultiLineInputDialog;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Window;
import javafx.util.Callback;
/** Dialog for editing {@link ScriptInfo}s
* @author Kay Kasemir
*/
public class ScriptsDialog extends Dialog<List<ScriptInfo>>
{
/** Modifiable ScriptPV */
private static class PVItem
{
public String name; // TODO Use JFX property to simplify binding to table column?
public BooleanProperty trigger = new SimpleBooleanProperty(true);
public PVItem(final String name, final boolean trigger)
{
this.name = name;
this.trigger.set(trigger);
}
public static PVItem forPV(final ScriptPV info)
{
return new PVItem(info.getName(), info.isTrigger());
}
public ScriptPV toScriptPV()
{
return new ScriptPV(name, trigger.get());
}
};
/** Modifiable ScriptInfo */
private static class ScriptItem
{
public StringProperty file = new SimpleStringProperty();
public String text;
public List<PVItem> pvs;
public ScriptItem()
{
this("", null, new ArrayList<>());
}
public ScriptItem(final String file, final String text, final List<PVItem> pvs)
{
this.file.set(file);
this.text = text;
this.pvs = pvs;
}
public static ScriptItem forInfo(final ScriptInfo info)
{
final List<PVItem> pvs = new ArrayList<>();
info.getPVs().forEach(pv -> pvs.add(PVItem.forPV(pv)));
return new ScriptItem(info.getFile(), info.getText(), pvs);
}
public ScriptInfo getScriptInfo()
{
final List<ScriptPV> spvs = new ArrayList<>();
pvs.forEach(pv -> spvs.add(pv.toScriptPV()));
return new ScriptInfo(file.get(), text, spvs);
}
};
/** Table cell with buttons to select file or edit the "embedded" script */
private static class ScriptButtonCell extends TableCell<ScriptItem, Boolean>
{
private final Button btn_file = new Button("File");
private final Button btn_embed = new Button("Embedded");
private final HBox buttons = new HBox(btn_file, btn_embed);
public ScriptButtonCell(TableColumn<ScriptItem, Boolean> col)
{
col.getTableView().getScene().getWindow();
Window window = null;
btn_file.setOnAction(event ->
{
final TableView<ScriptItem> table = col.getTableView();
final ScriptItem item = table.getItems().get(getTableRow().getIndex());
final FileChooser dlg = new FileChooser();
dlg.setTitle("Select Script");
if (item.file.get().length() > 0)
{
File file = new File(item.file.get());
dlg.setInitialDirectory(file.getParentFile());
dlg.setInitialFileName(file.getName());
}
dlg.getExtensionFilters().addAll(new ExtensionFilter("Script", "*.py"),
new ExtensionFilter("All", "*.*"));
final File result = dlg.showOpenDialog(window);
if (result != null)
{
item.file.set(result.getPath());
item.text = null;
}
});
btn_embed.setOnAction(event ->
{
final TableView<ScriptItem> table = col.getTableView();
final ScriptItem item = table.getItems().get(getTableRow().getIndex());
if (item.text == null || item.text.trim().isEmpty())
item.text = "# Embedded python script\n\n";
final MultiLineInputDialog dlg = new MultiLineInputDialog(table, item.text);
final Optional<String> result = dlg.showAndWait();
if (result.isPresent())
{
item.file.set(ScriptInfo.EMBEDDED_PYTHON);
item.text = result.get();
}
});
}
@Override
protected void updateItem(final Boolean item, final boolean empty)
{
setGraphic(empty ? null : buttons);
}
};
/** Data that is linked to the scripts_table */
private final ObservableList<ScriptItem> script_items = FXCollections.observableArrayList();
/** Table for all scripts */
private TableView<ScriptItem> scripts_table;
/** Data that is linked to the pvs_table */
private final ObservableList<PVItem> pv_items = FXCollections.observableArrayList();
/** Table for PVs of currently selected script */
private TableView<PVItem> pvs_table;
/** @param scripts Scripts to show/edit in the dialog */
public ScriptsDialog(final List<ScriptInfo> scripts)
{
setTitle("Scripts");
setHeaderText("Edit scripts and their PVs");
scripts.forEach(script -> script_items.add(ScriptItem.forInfo(script)));
fixupScripts(0);
getDialogPane().setContent(createContent());
getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
setResizable(true);
setResultConverter(button ->
{
if (button != ButtonType.OK)
return null;
return script_items.stream()
.filter(item -> ! item.file.get().isEmpty())
.map(ScriptItem::getScriptInfo)
.collect(Collectors.toList());
});
}
private Node createContent()
{
final Node scripts = createScriptsTable();
final Node pvs = createPVsTable();
// Display PVs of currently selected script
scripts_table.getSelectionModel().selectedItemProperty().addListener((prop, old, selected) ->
{
if (selected == null)
pv_items.clear();
else
{
pv_items.setAll(selected.pvs);
fixupPVs(0);
}
});
// Update PVs of selected script from PVs table
final ListChangeListener<PVItem> ll = change ->
{
final ScriptItem selected = scripts_table.getSelectionModel().getSelectedItem();
if (selected != null)
selected.pvs = new ArrayList<>(change.getList());
};
pv_items.addListener(ll);
final HBox box = new HBox(10, scripts, pvs);
HBox.setHgrow(scripts, Priority.ALWAYS);
HBox.setHgrow(pvs, Priority.ALWAYS);
// box.setStyle("-fx-background-color: rgb(255, 100, 0, 0.2);"); // For debugging
return box;
}
/** @return Node for UI elements that edit the scripts */
private Node createScriptsTable()
{
final GridPane content = new GridPane();
content.setHgap(10);
content.setVgap(10);
// content.setGridLinesVisible(true); // For debugging
// Create table with editable script file column
final TableColumn<ScriptItem, String> name_col = new TableColumn<>("Scripts");
name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ScriptItem, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(final CellDataFeatures<ScriptItem, String> param)
{
final StringProperty file = param.getValue().file;
if (file.get().isEmpty())
return new ReadOnlyStringWrapper("<enter name>");
return file;
}
});
name_col.setCellFactory(TextFieldTableCell.<ScriptItem>forTableColumn());
name_col.setOnEditCommit(event ->
{
final int row = event.getTablePosition().getRow();
script_items.get(row).file.set(event.getNewValue());
fixupScripts(row);
});
// TODO Table column to select file or set to ScriptInfo.EMBEDDED_PYTHON
final TableColumn<ScriptItem, Boolean> embed_col = new TableColumn<>();
Callback<TableColumn<ScriptItem, Boolean>, TableCell<ScriptItem, Boolean>> embed_cell_factory = col ->
{
return new ScriptButtonCell(col);
};
embed_col.setCellFactory(embed_cell_factory);
scripts_table = new TableView<>(script_items);
scripts_table.getColumns().add(name_col);
scripts_table.getColumns().add(embed_col);
scripts_table.setEditable(true);
scripts_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
scripts_table.setTooltip(new Tooltip("Edit scripts. Add new script in last row"));
content.add(scripts_table, 0, 0, 1, 3);
GridPane.setHgrow(scripts_table, Priority.ALWAYS);
// TODO This has no effect, table does not grow vertically
GridPane.setVgrow(scripts_table, Priority.ALWAYS);
// Buttons
final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png"));
add.setMaxWidth(Double.MAX_VALUE);
content.add(add, 1, 0);
add.setOnAction(event ->
{
script_items.add(new ScriptItem());
});
final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png"));
remove.setMaxWidth(Double.MAX_VALUE);
content.add(remove, 1, 1);
remove.setOnAction(event ->
{
final int sel = scripts_table.getSelectionModel().getSelectedIndex();
if (sel >= 0)
{
script_items.remove(sel);
fixupScripts(sel);
}
});
return content;
}
/** Fix scripts data: Delete empty rows in middle, but keep one empty final row
* @param changed_row Row to check, and remove if it's empty
*/
private void fixupScripts(final int changed_row)
{
// Check if edited row is now empty and should be deleted
if (changed_row < script_items.size())
{
final ScriptItem item = script_items.get(changed_row);
if (item.file.get().trim().isEmpty())
script_items.remove(changed_row);
}
// Assert one empty row at bottom
final int len = script_items.size();
if (len <= 0 ||
script_items.get(len-1).file.get().trim().length() > 0)
script_items.add(new ScriptItem());
}
/** @return Node for UI elements that edit the PVs of a script */
private Node createPVsTable()
{
final GridPane content = new GridPane();
content.setHgap(10);
content.setVgap(10);
// content.setGridLinesVisible(true); // For debugging
// Create table with editable column
final TableColumn<PVItem, String> name_col = new TableColumn<>("PVs");
name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PVItem, String>, ObservableValue<String>>()
{
@Override
public ObservableValue<String> call(final CellDataFeatures<PVItem, String> param)
{
final String name = param.getValue().name;
if (name.isEmpty())
return new ReadOnlyStringWrapper("<enter name>");
return new ReadOnlyStringWrapper(name);
}
});
name_col.setCellFactory(TextFieldTableCell.<PVItem>forTableColumn());
name_col.setOnEditCommit(event ->
{
final int row = event.getTablePosition().getRow();
pv_items.get(row).name = event.getNewValue();
fixupPVs(row);
});
// Boolean Table column needs Observable. "OnEdit" is never called
final TableColumn<PVItem, Boolean> trigger_col = new TableColumn<>("Trigger Script?");
trigger_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PVItem, Boolean>, ObservableValue<Boolean>>()
{
@Override
public ObservableValue<Boolean> call(final CellDataFeatures<PVItem, Boolean> param)
{
return param.getValue().trigger;
}
});
trigger_col.setCellFactory(CheckBoxTableCell.<PVItem>forTableColumn(trigger_col));
pvs_table = new TableView<>(pv_items);
pvs_table.getColumns().add(name_col);
pvs_table.getColumns().add(trigger_col);
pvs_table.setEditable(true);
pvs_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
pvs_table.setTooltip(new Tooltip("Edit PVs. Add new PV in last row"));
pvs_table.setPlaceholder(new Label("Select Script to see PVs"));
content.add(pvs_table, 0, 0, 1, 3);
GridPane.setHgrow(pvs_table, Priority.ALWAYS);
GridPane.setVgrow(pvs_table, Priority.ALWAYS);
// Buttons
final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png"));
add.setMaxWidth(Double.MAX_VALUE);
content.add(add, 1, 0);
add.setOnAction(event ->
{
pv_items.add(new PVItem("", true));
});
final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png"));
remove.setMaxWidth(Double.MAX_VALUE);
content.add(remove, 1, 1);
remove.setOnAction(event ->
{
final int sel = pvs_table.getSelectionModel().getSelectedIndex();
if (sel >= 0)
{
pv_items.remove(sel);
fixupPVs(sel);
}
});
return content;
}
/** Fix PVs data: Delete empty rows in middle, but keep one empty final row
* @param changed_row Row to check, and remove if it's empty
*/
private void fixupPVs(final int changed_row)
{
// Check if edited row is now empty and should be deleted
if (changed_row < pv_items.size())
{
final PVItem item = pv_items.get(changed_row);
if (item.name.trim().isEmpty())
pv_items.remove(changed_row);
}
// Assert one empty row at bottom
final int len = pv_items.size();
if (len <= 0 ||
pv_items.get(len-1).name.trim().length() > 0)
pv_items.add(new PVItem("", true));
}
}
|
ScriptDialog: Fix layout
|
org.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/ScriptsDialog.java
|
ScriptDialog: Fix layout
|
<ide><path>rg.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/ScriptsDialog.java
<ide> import javafx.scene.layout.GridPane;
<ide> import javafx.scene.layout.HBox;
<ide> import javafx.scene.layout.Priority;
<add>import javafx.scene.layout.VBox;
<ide> import javafx.stage.FileChooser;
<ide> import javafx.stage.FileChooser.ExtensionFilter;
<ide> import javafx.stage.Window;
<ide> /** Modifiable ScriptPV */
<ide> private static class PVItem
<ide> {
<del> public String name; // TODO Use JFX property to simplify binding to table column?
<del>
<add> public String name;
<ide> public BooleanProperty trigger = new SimpleBooleanProperty(true);
<ide>
<ide> public PVItem(final String name, final boolean trigger)
<ide> {
<ide> private final Button btn_file = new Button("File");
<ide> private final Button btn_embed = new Button("Embedded");
<del> private final HBox buttons = new HBox(btn_file, btn_embed);
<add> private final HBox buttons = new HBox(10, btn_file, btn_embed);
<ide>
<ide> public ScriptButtonCell(TableColumn<ScriptItem, Boolean> col)
<ide> {
<ide> /** @return Node for UI elements that edit the scripts */
<ide> private Node createScriptsTable()
<ide> {
<del> final GridPane content = new GridPane();
<del> content.setHgap(10);
<del> content.setVgap(10);
<del> // content.setGridLinesVisible(true); // For debugging
<del>
<ide> // Create table with editable script file column
<ide> final TableColumn<ScriptItem, String> name_col = new TableColumn<>("Scripts");
<ide> name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ScriptItem, String>, ObservableValue<String>>()
<ide> scripts_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
<ide> scripts_table.setTooltip(new Tooltip("Edit scripts. Add new script in last row"));
<ide>
<del> content.add(scripts_table, 0, 0, 1, 3);
<del> GridPane.setHgrow(scripts_table, Priority.ALWAYS);
<del> // TODO This has no effect, table does not grow vertically
<del> GridPane.setVgrow(scripts_table, Priority.ALWAYS);
<del>
<ide> // Buttons
<ide> final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png"));
<ide> add.setMaxWidth(Double.MAX_VALUE);
<del> content.add(add, 1, 0);
<ide> add.setOnAction(event ->
<ide> {
<ide> script_items.add(new ScriptItem());
<ide>
<ide> final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png"));
<ide> remove.setMaxWidth(Double.MAX_VALUE);
<del> content.add(remove, 1, 1);
<ide> remove.setOnAction(event ->
<ide> {
<ide> final int sel = scripts_table.getSelectionModel().getSelectedIndex();
<ide> }
<ide> });
<ide>
<add> final VBox buttons = new VBox(10, add, remove);
<add> final HBox content = new HBox(10, scripts_table, buttons);
<add> HBox.setHgrow(scripts_table, Priority.ALWAYS);
<ide> return content;
<ide> }
<ide>
<ide> /** @return Node for UI elements that edit the PVs of a script */
<ide> private Node createPVsTable()
<ide> {
<del> final GridPane content = new GridPane();
<del> content.setHgap(10);
<del> content.setVgap(10);
<del> // content.setGridLinesVisible(true); // For debugging
<del>
<ide> // Create table with editable column
<ide> final TableColumn<PVItem, String> name_col = new TableColumn<>("PVs");
<ide> name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<PVItem, String>, ObservableValue<String>>()
<ide> pvs_table.setTooltip(new Tooltip("Edit PVs. Add new PV in last row"));
<ide> pvs_table.setPlaceholder(new Label("Select Script to see PVs"));
<ide>
<del> content.add(pvs_table, 0, 0, 1, 3);
<del> GridPane.setHgrow(pvs_table, Priority.ALWAYS);
<del> GridPane.setVgrow(pvs_table, Priority.ALWAYS);
<del>
<ide> // Buttons
<ide> final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png"));
<ide> add.setMaxWidth(Double.MAX_VALUE);
<del> content.add(add, 1, 0);
<ide> add.setOnAction(event ->
<ide> {
<ide> pv_items.add(new PVItem("", true));
<ide>
<ide> final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png"));
<ide> remove.setMaxWidth(Double.MAX_VALUE);
<del> content.add(remove, 1, 1);
<ide> remove.setOnAction(event ->
<ide> {
<ide> final int sel = pvs_table.getSelectionModel().getSelectedIndex();
<ide> }
<ide> });
<ide>
<add> final VBox buttons = new VBox(10, add, remove);
<add> final HBox content = new HBox(10, pvs_table, buttons);
<add> HBox.setHgrow(pvs_table, Priority.ALWAYS);
<ide> return content;
<ide> }
<ide>
|
|
Java
|
mit
|
2e58b480581746a31b836ce4a3daa7a3ea23fd11
| 0 |
AC31007-Group-8/QuizSystem,AC31007-Group-8/QuizSystem,AC31007-Group-8/QuizSystem
|
package com.github.ac31007_group_8.quiz;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import javax.annotation.ParametersAreNonnullByDefault;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* Database handler.
*
* @author Robert T.
*/
@ParametersAreNonnullByDefault
public class Database {
private Database() {} // Static
private static String DB_URL;
private static String getURL() {
// Cache it, to save constant string rebuilds
if (DB_URL != null) return DB_URL;
DB_URL = "jdbc:mysql://" + Configuration.DATABASE_HOST + ":" + Configuration.DATABASE_PORT + "/" + Configuration.DATABASE_SCHEMA;
return DB_URL;
}
/**
* Get a connection directly from JDBC.
*
* This allows you to use the standard JDBC flow, as shown in this article: http://www.vogella.com/tutorials/MySQLJava/article.html
*
* <b>Remember to CLOSE your connection when you're done with it!</b>
*
* @return A fresh JDBC connection to use.
*/
public static Connection getConnection() {
// TODO: Pooling? Something more efficient?
try (Connection conn = DriverManager.getConnection(getURL(), Configuration.DATABASE_USER, Configuration.DATABASE_PASSWORD)) {
return conn;
} catch(Exception ex) {
// TODO: Make this less brutish.
throw new RuntimeException(ex);
}
}
/**
* Gets a jOOQ DSL to use for database communication.
*
* This is provided for the SQLphobes in the team, as it provides a "SQL-ish" Java interface rather than raw SQL.
*
* See the jOOQ documentation for more: https://www.jooq.org/doc/3.9/manual/
*
* @return A jOOQ DSL, typically called 'create' in the documentation.
*/
public static DSLContext getJooq() {
return DSL.using(getConnection(), SQLDialect.MYSQL);
}
/**
*
* @param tableName - Name of table to return entry count from
* @return # of entries
*/
public static int getJooqTableCount(String tableName) {
DSL.using(getConnection(), SQLDialect.MYSQL);
return DSL.count(table(tableName));
}
}
|
src/main/java/com/github/ac31007_group_8/quiz/Database.java
|
package com.github.ac31007_group_8.quiz;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import javax.annotation.ParametersAreNonnullByDefault;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* Database handler.
*
* @author Robert T.
*/
@ParametersAreNonnullByDefault
public class Database {
private Database() {} // Static
private static String DB_URL;
private static String getURL() {
// Cache it, to save constant string rebuilds
if (DB_URL != null) return DB_URL;
DB_URL = "jdbc:mysql://" + Configuration.DATABASE_HOST + ":" + Configuration.DATABASE_PORT + "/" + Configuration.DATABASE_SCHEMA;
return DB_URL;
}
/**
* Get a connection directly from JDBC.
*
* This allows you to use the standard JDBC flow, as shown in this article: http://www.vogella.com/tutorials/MySQLJava/article.html
*
* <b>Remember to CLOSE your connection when you're done with it!</b>
*
* @return A fresh JDBC connection to use.
*/
public static Connection getConnection() {
// TODO: Pooling? Something more efficient?
try (Connection conn = DriverManager.getConnection(getURL(), Configuration.DATABASE_USER, Configuration.DATABASE_PASSWORD)) {
return conn;
} catch(Exception ex) {
// TODO: Make this less brutish.
throw new RuntimeException(ex);
}
}
/**
* Gets a jOOQ DSL to use for database communication.
*
* This is provided for the SQLphobes in the team, as it provides a "SQL-ish" Java interface rather than raw SQL.
*
* See the jOOQ documentation for more: https://www.jooq.org/doc/3.9/manual/
*
* @return A jOOQ DSL, typically called 'create' in the documentation.
*/
public static DSLContext getJooq() {
return DSL.using(getConnection(), SQLDialect.MYSQL);
}
/**
*
* @param tableName - Name of table to return entry count from
* @return # of entries
*/
}
|
Added a method (non-working) to return number of table entries to Database.java
|
src/main/java/com/github/ac31007_group_8/quiz/Database.java
|
Added a method (non-working) to return number of table entries to Database.java
|
<ide><path>rc/main/java/com/github/ac31007_group_8/quiz/Database.java
<ide> * @param tableName - Name of table to return entry count from
<ide> * @return # of entries
<ide> */
<add> public static int getJooqTableCount(String tableName) {
<add> DSL.using(getConnection(), SQLDialect.MYSQL);
<add> return DSL.count(table(tableName));
<add> }
<ide>
<ide> }
|
|
Java
|
bsd-3-clause
|
cf01c35917ce726cc6572939249e5a9d9c12ee68
| 0 |
scala/scala-jline,kaulkie/jline2,renew-tgi/jline2,tkruse/jline2,fantasy86/jline2,DALDEI/jline2,ctubbsii/jline2,msaxena2/jline2,scala/scala-jline
|
/*
* Copyright (c) 2002-2012, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jline;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import jline.internal.Configuration;
import jline.internal.Log;
import jline.internal.Preconditions;
import static jline.internal.Preconditions.checkNotNull;
/**
* Creates terminal instances.
*
* @author <a href="mailto:[email protected]">Jason Dillon</a>
* @since 2.0
*/
public class TerminalFactory
{
public static final String JLINE_TERMINAL = "jline.terminal";
public static final String AUTO = "auto";
public static final String UNIX = "unix";
public static final String WIN = "win";
public static final String WINDOWS = "windows";
public static final String NONE = "none";
public static final String OFF = "off";
public static final String FALSE = "false";
private static final InheritableThreadLocal<Terminal> holder = new InheritableThreadLocal<Terminal>();
public static synchronized Terminal create() {
if (Log.TRACE) {
//noinspection ThrowableInstanceNeverThrown
Log.trace(new Throwable("CREATE MARKER"));
}
String type = Configuration.getString(JLINE_TERMINAL, AUTO);
if ("dumb".equals(System.getenv("TERM"))) {
type = "none";
Log.debug("$TERM=dumb; setting type=", type);
}
Log.debug("Creating terminal; type=", type);
Terminal t;
try {
String tmp = type.toLowerCase();
if (tmp.equals(UNIX)) {
t = getFlavor(Flavor.UNIX);
}
else if (tmp.equals(WIN) | tmp.equals(WINDOWS)) {
t = getFlavor(Flavor.WINDOWS);
}
else if (tmp.equals(NONE) || tmp.equals(OFF) || tmp.equals(FALSE)) {
t = new UnsupportedTerminal();
}
else {
if (tmp.equals(AUTO)) {
String os = Configuration.getOsName();
Flavor flavor = Flavor.UNIX;
if (os.contains(WINDOWS)) {
flavor = Flavor.WINDOWS;
}
t = getFlavor(flavor);
}
else {
try {
t = (Terminal) Thread.currentThread().getContextClassLoader().loadClass(type).newInstance();
}
catch (Exception e) {
throw new IllegalArgumentException(MessageFormat.format("Invalid terminal type: {0}", type), e);
}
}
}
}
catch (Exception e) {
Log.error("Failed to construct terminal; falling back to unsupported", e);
t = new UnsupportedTerminal();
}
Log.debug("Created Terminal: ", t);
try {
t.init();
}
catch (Throwable e) {
Log.error("Terminal initialization failed; falling back to unsupported", e);
return new UnsupportedTerminal();
}
return t;
}
public static synchronized void reset() {
holder.remove();
}
public static synchronized void resetIf(final Terminal t) {
if (holder.get() == t) {
reset();
}
}
public static enum Type
{
AUTO,
WINDOWS,
UNIX,
NONE
}
public static synchronized void configure(final String type) {
checkNotNull(type);
System.setProperty(JLINE_TERMINAL, type);
}
public static synchronized void configure(final Type type) {
checkNotNull(type);
configure(type.name().toLowerCase());
}
//
// Flavor Support
//
public static enum Flavor
{
WINDOWS,
UNIX
}
private static final Map<Flavor, Class<? extends Terminal>> FLAVORS = new HashMap<Flavor, Class<? extends Terminal>>();
static {
registerFlavor(Flavor.WINDOWS, AnsiWindowsTerminal.class);
registerFlavor(Flavor.UNIX, UnixTerminal.class);
}
public static synchronized Terminal get() {
Terminal t = holder.get();
if (t == null) {
t = create();
holder.set(t);
}
return t;
}
public static Terminal getFlavor(final Flavor flavor) throws Exception {
Class<? extends Terminal> type = FLAVORS.get(flavor);
if (type != null) {
return type.newInstance();
}
throw new InternalError();
}
public static void registerFlavor(final Flavor flavor, final Class<? extends Terminal> type) {
FLAVORS.put(flavor, type);
}
}
|
src/main/java/jline/TerminalFactory.java
|
/*
* Copyright (c) 2002-2012, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jline;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import jline.internal.Configuration;
import jline.internal.Log;
import jline.internal.Preconditions;
import static jline.internal.Preconditions.checkNotNull;
/**
* Creates terminal instances.
*
* @author <a href="mailto:[email protected]">Jason Dillon</a>
* @since 2.0
*/
public class TerminalFactory
{
public static final String JLINE_TERMINAL = "jline.terminal";
public static final String AUTO = "auto";
public static final String UNIX = "unix";
public static final String WIN = "win";
public static final String WINDOWS = "windows";
public static final String NONE = "none";
public static final String OFF = "off";
public static final String FALSE = "false";
private static final InheritableThreadLocal<Terminal> holder = new InheritableThreadLocal<Terminal>();
public static synchronized Terminal create() {
if (Log.TRACE) {
//noinspection ThrowableInstanceNeverThrown
Log.trace(new Throwable("CREATE MARKER"));
}
String type = Configuration.getString(JLINE_TERMINAL, AUTO);
if (System.getenv("TERM").equals("dumb")) {
type = "none";
Log.debug("$TERM=dumb; setting type=", type);
}
Log.debug("Creating terminal; type=", type);
Terminal t;
try {
String tmp = type.toLowerCase();
if (tmp.equals(UNIX)) {
t = getFlavor(Flavor.UNIX);
}
else if (tmp.equals(WIN) | tmp.equals(WINDOWS)) {
t = getFlavor(Flavor.WINDOWS);
}
else if (tmp.equals(NONE) || tmp.equals(OFF) || tmp.equals(FALSE)) {
t = new UnsupportedTerminal();
}
else {
if (tmp.equals(AUTO)) {
String os = Configuration.getOsName();
Flavor flavor = Flavor.UNIX;
if (os.contains(WINDOWS)) {
flavor = Flavor.WINDOWS;
}
t = getFlavor(flavor);
}
else {
try {
t = (Terminal) Thread.currentThread().getContextClassLoader().loadClass(type).newInstance();
}
catch (Exception e) {
throw new IllegalArgumentException(MessageFormat.format("Invalid terminal type: {0}", type), e);
}
}
}
}
catch (Exception e) {
Log.error("Failed to construct terminal; falling back to unsupported", e);
t = new UnsupportedTerminal();
}
Log.debug("Created Terminal: ", t);
try {
t.init();
}
catch (Throwable e) {
Log.error("Terminal initialization failed; falling back to unsupported", e);
return new UnsupportedTerminal();
}
return t;
}
public static synchronized void reset() {
holder.remove();
}
public static synchronized void resetIf(final Terminal t) {
if (holder.get() == t) {
reset();
}
}
public static enum Type
{
AUTO,
WINDOWS,
UNIX,
NONE
}
public static synchronized void configure(final String type) {
checkNotNull(type);
System.setProperty(JLINE_TERMINAL, type);
}
public static synchronized void configure(final Type type) {
checkNotNull(type);
configure(type.name().toLowerCase());
}
//
// Flavor Support
//
public static enum Flavor
{
WINDOWS,
UNIX
}
private static final Map<Flavor, Class<? extends Terminal>> FLAVORS = new HashMap<Flavor, Class<? extends Terminal>>();
static {
registerFlavor(Flavor.WINDOWS, AnsiWindowsTerminal.class);
registerFlavor(Flavor.UNIX, UnixTerminal.class);
}
public static synchronized Terminal get() {
Terminal t = holder.get();
if (t == null) {
t = create();
holder.set(t);
}
return t;
}
public static Terminal getFlavor(final Flavor flavor) throws Exception {
Class<? extends Terminal> type = FLAVORS.get(flavor);
if (type != null) {
return type.newInstance();
}
throw new InternalError();
}
public static void registerFlavor(final Flavor flavor, final Class<? extends Terminal> type) {
FLAVORS.put(flavor, type);
}
}
|
Account for null TERM
|
src/main/java/jline/TerminalFactory.java
|
Account for null TERM
|
<ide><path>rc/main/java/jline/TerminalFactory.java
<ide> }
<ide>
<ide> String type = Configuration.getString(JLINE_TERMINAL, AUTO);
<del> if (System.getenv("TERM").equals("dumb")) {
<add> if ("dumb".equals(System.getenv("TERM"))) {
<ide> type = "none";
<ide> Log.debug("$TERM=dumb; setting type=", type);
<ide> }
|
|
Java
|
apache-2.0
|
fb839a3c19e78d9ae0d06c78694f61e34705369c
| 0 |
XDean/ExtendableTool
|
package xdean.screenShot;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import xdean.jex.config.Config;
import xdean.jex.util.task.TaskUtil;
import xdean.jfx.ex.support.DragSupport;
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import com.sun.javafx.application.PlatformImpl;
@UtilityClass
public class ScreenShot {
private final String KEY = "ScreenShotKey";
private final String DEFAULT_KEY = "ALT+SHIFT+A";
private final HotkeyListener listener = e -> {
if (e == 0) {
show();
}
};
static {
TaskUtil.uncatch(() -> PlatformImpl.startup(() -> {
PlatformImpl.setTaskbarApplication(false);
Platform.setImplicitExit(false);
}));
Config.setIfAbsent(KEY, DEFAULT_KEY);
}
public void main(String[] args) {
// register();
Platform.setImplicitExit(true);
show();
}
public void register(boolean b) {
if (b) {
register();
} else {
unregister();
}
}
public void register() {
JIntellitype jni = JIntellitype.getInstance();
jni.registerHotKey(0, Config.getProperty(KEY).orElse(DEFAULT_KEY));
jni.addHotKeyListener(listener);
}
public void unregister() {
JIntellitype jni = JIntellitype.getInstance();
jni.unregisterHotKey(0);
jni.removeHotKeyListener(listener);
}
// TODO reuse it
public void show() {
Platform.runLater(() -> {
Stage stage = new Stage(StageStyle.TRANSPARENT);
stage.setAlwaysOnTop(true);
Group rootGroup = new Group();
Scene scene = new Scene(rootGroup, 200, 200, Color.TRANSPARENT);
Rectangle target = new Rectangle();
target.setFill(Color.TRANSPARENT);
target.setStroke(Color.BLACK);
Rectangle mask = new Rectangle();
mask.setLayoutX(0);
mask.setLayoutY(0);
mask.setWidth(Screen.getPrimary().getBounds().getWidth());
mask.setHeight(Screen.getPrimary().getBounds().getHeight());
mask.setFill(new Color(0, 0, 0, 0.3));
DragSupport.bind(target).doOnDrag(() -> mask.setClip(Shape.subtract(mask, target)));
ImageView view = new ImageView(getScreenShot());
rootGroup.getChildren().addAll(view, mask, target);
double[] startPos = new double[2];
scene.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> {
startPos[0] = e.getScreenX();
startPos[1] = e.getScreenY();
target.setWidth(0);
target.setHeight(0);
});
scene.addEventHandler(MouseEvent.MOUSE_DRAGGED, e -> {
target.setLayoutX(Math.min(e.getScreenX(), startPos[0]));
target.setLayoutY(Math.min(e.getScreenY(), startPos[1]));
target.setWidth(Math.abs(e.getScreenX() - startPos[0]));
target.setHeight(Math.abs(e.getScreenY() - startPos[1]));
mask.setClip(Shape.subtract(mask, target));
});
scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.ESCAPE) {
stage.close();
}
});
scene.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> {
if (target.contains(e.getScreenX() - target.getLayoutX(), e.getScreenY() - target.getLayoutY())) {
if (e.getClickCount() > 1) {
Shape shape = Shape.union(target, new Rectangle());
view.setClip(shape);
putIntoClipBoard(view.snapshot(null, null));
stage.close();
} else if (e.getButton() == MouseButton.SECONDARY) {
target.setWidth(0);
target.setHeight(0);
mask.setClip(Shape.subtract(mask, target));
}
} else {
if (e.getButton() == MouseButton.SECONDARY || e.getClickCount() > 1) {
e.consume();
stage.close();
}
}
});
stage.setScene(scene);
stage.setWidth(Screen.getPrimary().getBounds().getWidth());
stage.setHeight(Screen.getPrimary().getBounds().getHeight());
stage.setX(0);
stage.setY(0);
stage.show();
});
}
@SneakyThrows
Image getScreenShot() {
int width = (int) Screen.getPrimary().getBounds().getWidth();
int height = (int) Screen.getPrimary().getBounds().getHeight();
Robot robot = new Robot();
BufferedImage swingImage = robot.createScreenCapture(new java.awt.Rectangle(width, height));
return SwingFXUtils.toFXImage(swingImage, new WritableImage(width, height));
}
void putIntoClipBoard(Image image) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putImage(image);
clipboard.setContent(content);
}
}
|
Tool-My/ScreenShot/src/main/java/xdean/screenShot/ScreenShot.java
|
package xdean.screenShot;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import xdean.jex.config.Config;
import xdean.jex.util.task.TaskUtil;
import xdean.jfx.ex.support.DragSupport;
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import com.sun.javafx.application.PlatformImpl;
@UtilityClass
public class ScreenShot {
private final String KEY = "ScreenShotKey";
private final String DEFAULT_KEY = "ALT+SHIFT+A";
private final HotkeyListener listener = e -> {
if (e == 0) {
show();
}
};
static {
TaskUtil.uncatch(() -> PlatformImpl.startup(() -> {
PlatformImpl.setTaskbarApplication(false);
Platform.setImplicitExit(false);
}));
Config.setIfAbsent(KEY, DEFAULT_KEY);
}
public void main(String[] args) {
// register();
Platform.setImplicitExit(true);
show();
}
public void register(boolean b) {
if (b) {
register();
} else {
unregister();
}
}
// FIXME unregister and register again will lead double listener
public void register() {
JIntellitype jni = JIntellitype.getInstance();
jni.registerHotKey(0, Config.getProperty(KEY).orElse(DEFAULT_KEY));
jni.addHotKeyListener(listener);
}
public void unregister() {
JIntellitype jni = JIntellitype.getInstance();
jni.unregisterHotKey(0);
}
// TODO reuse it
public void show() {
Platform.runLater(() -> {
Stage stage = new Stage(StageStyle.TRANSPARENT);
stage.setAlwaysOnTop(true);
Group rootGroup = new Group();
Scene scene = new Scene(rootGroup, 200, 200, Color.TRANSPARENT);
Rectangle target = new Rectangle();
target.setFill(Color.TRANSPARENT);
target.setStroke(Color.BLACK);
Rectangle mask = new Rectangle();
mask.setLayoutX(0);
mask.setLayoutY(0);
mask.setWidth(Screen.getPrimary().getBounds().getWidth());
mask.setHeight(Screen.getPrimary().getBounds().getHeight());
mask.setFill(new Color(0, 0, 0, 0.3));
DragSupport.bind(target).doOnDrag(() -> mask.setClip(Shape.subtract(mask, target)));
ImageView view = new ImageView(getScreenShot());
rootGroup.getChildren().addAll(view, mask, target);
double[] startPos = new double[2];
scene.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> {
startPos[0] = e.getScreenX();
startPos[1] = e.getScreenY();
target.setWidth(0);
target.setHeight(0);
});
scene.addEventHandler(MouseEvent.MOUSE_DRAGGED, e -> {
target.setLayoutX(Math.min(e.getScreenX(), startPos[0]));
target.setLayoutY(Math.min(e.getScreenY(), startPos[1]));
target.setWidth(Math.abs(e.getScreenX() - startPos[0]));
target.setHeight(Math.abs(e.getScreenY() - startPos[1]));
mask.setClip(Shape.subtract(mask, target));
});
scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.ESCAPE) {
stage.close();
}
});
scene.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> {
if (target.contains(e.getScreenX() - target.getLayoutX(), e.getScreenY() - target.getLayoutY())) {
if (e.getClickCount() > 1) {
Shape shape = Shape.union(target, new Rectangle());
view.setClip(shape);
putIntoClipBoard(view.snapshot(null, null));
stage.close();
} else if (e.getButton() == MouseButton.SECONDARY) {
target.setWidth(0);
target.setHeight(0);
mask.setClip(Shape.subtract(mask, target));
}
} else {
if (e.getButton() == MouseButton.SECONDARY || e.getClickCount() > 1) {
e.consume();
stage.close();
}
}
});
stage.setScene(scene);
stage.setWidth(Screen.getPrimary().getBounds().getWidth());
stage.setHeight(Screen.getPrimary().getBounds().getHeight());
stage.setX(0);
stage.setY(0);
stage.show();
});
}
@SneakyThrows
Image getScreenShot() {
int width = (int) Screen.getPrimary().getBounds().getWidth();
int height = (int) Screen.getPrimary().getBounds().getHeight();
Robot robot = new Robot();
BufferedImage swingImage = robot.createScreenCapture(new java.awt.Rectangle(width, height));
return SwingFXUtils.toFXImage(swingImage, new WritableImage(width, height));
}
void putIntoClipBoard(Image image) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putImage(image);
clipboard.setContent(content);
}
}
|
fix multi-register
|
Tool-My/ScreenShot/src/main/java/xdean/screenShot/ScreenShot.java
|
fix multi-register
|
<ide><path>ool-My/ScreenShot/src/main/java/xdean/screenShot/ScreenShot.java
<ide> }
<ide> }
<ide>
<del> // FIXME unregister and register again will lead double listener
<ide> public void register() {
<ide> JIntellitype jni = JIntellitype.getInstance();
<ide> jni.registerHotKey(0, Config.getProperty(KEY).orElse(DEFAULT_KEY));
<ide> public void unregister() {
<ide> JIntellitype jni = JIntellitype.getInstance();
<ide> jni.unregisterHotKey(0);
<add> jni.removeHotKeyListener(listener);
<ide> }
<ide>
<ide> // TODO reuse it
|
|
Java
|
apache-2.0
|
ec596dadd96df07c9315d0955c6f5e09f07f2d1f
| 0 |
j-bernardo/lumify,dvdnglnd/lumify,TeamUDS/lumify,j-bernardo/lumify,TeamUDS/lumify,dvdnglnd/lumify,lumifyio/lumify,Steimel/lumify,RavenB/lumify,j-bernardo/lumify,j-bernardo/lumify,bings/lumify,Steimel/lumify,lumifyio/lumify,Steimel/lumify,bings/lumify,RavenB/lumify,RavenB/lumify,RavenB/lumify,TeamUDS/lumify,TeamUDS/lumify,lumifyio/lumify,lumifyio/lumify,j-bernardo/lumify,bings/lumify,RavenB/lumify,Steimel/lumify,TeamUDS/lumify,bings/lumify,dvdnglnd/lumify,Steimel/lumify,dvdnglnd/lumify,bings/lumify,dvdnglnd/lumify,lumifyio/lumify
|
package com.altamiracorp.lumify.web.routes.artifact;
import com.altamiracorp.lumify.core.ingest.video.VideoPlaybackDetails;
import com.altamiracorp.lumify.core.model.artifact.Artifact;
import com.altamiracorp.lumify.core.model.artifact.ArtifactRepository;
import com.altamiracorp.lumify.core.model.artifact.ArtifactRowKey;
import com.altamiracorp.lumify.core.model.graph.GraphRepository;
import com.altamiracorp.lumify.core.model.graph.GraphVertex;
import com.altamiracorp.lumify.core.user.User;
import com.altamiracorp.lumify.web.BaseRequestHandler;
import com.altamiracorp.miniweb.HandlerChain;
import com.altamiracorp.miniweb.utils.UrlUtils;
import com.google.inject.Inject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ArtifactRawByRowKey extends BaseRequestHandler {
private static final Pattern RANGE_PATTERN = Pattern.compile("bytes=([0-9]*)-([0-9]*)");
private final ArtifactRepository artifactRepository;
private final GraphRepository graphRepository;
@Inject
public ArtifactRawByRowKey(final ArtifactRepository repo, final GraphRepository graphRepository) {
this.graphRepository = graphRepository;
artifactRepository = repo;
}
public static String getUrl(ArtifactRowKey artifactKey) {
return "/artifact/" + UrlUtils.urlEncode(artifactKey.toString()) + "/raw";
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
boolean download = getOptionalParameter(request, "download") != null;
boolean videoPlayback = getOptionalParameter(request, "playback") != null;
User user = getUser(request);
ArtifactRowKey artifactKey = new ArtifactRowKey(UrlUtils.urlDecode(getAttributeString(request, "_rowKey")));
Artifact artifact = artifactRepository.findByRowKey(artifactKey.toString(), user.getModelUserContext());
if (artifact == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
chain.next(request, response);
return;
}
String graphVertexId = artifact.getMetadata().getGraphVertexId();
GraphVertex vertex = graphRepository.findVertex(graphVertexId, user);
String fileName = getFileName(artifact);
if (videoPlayback) {
handlePartialPlayback(request, response, artifact, fileName);
} else {
String mimeType = getMimeType(artifact);
response.setContentType(mimeType);
if (download) {
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
} else {
response.addHeader("Content-Disposition", "inline; filename=" + fileName);
}
InputStream in = artifactRepository.getRaw(artifact, vertex, user);
try {
IOUtils.copy(in, response.getOutputStream());
} finally {
in.close();
}
}
chain.next(request, response);
}
private void handlePartialPlayback(HttpServletRequest request, HttpServletResponse response, Artifact artifact, String fileName) throws IOException {
String videoType = getRequiredParameter(request, "type");
InputStream in = null;
long totalLength = 0;
long partialStart = 0;
Long partialEnd = null;
String range = request.getHeader("Range");
if (range != null) {
Matcher m = RANGE_PATTERN.matcher(range);
if (m.matches()) {
partialStart = Long.parseLong(m.group(1));
if (m.group(2).length() > 0) {
partialEnd = Long.parseLong(m.group(2));
}
if (partialEnd == null) {
partialEnd = partialStart + 100000 - 1;
}
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
}
}
if (videoType.equals("video/mp4") || videoType.equals("video/webm")) {
final String videoFormat = FilenameUtils.getBaseName(videoType);
response.setContentType(videoType);
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
VideoPlaybackDetails videoDetails = artifactRepository.getVideoPlaybackDetails(artifact.getRowKey().toString(), videoFormat);
in = videoDetails.getVideoStream();
totalLength = videoDetails.getVideoFileSize();
} else {
throw new RuntimeException("Invalid video type: " + videoType);
}
if (partialEnd == null) {
partialEnd = totalLength;
}
// Ensure that the last byte position is less than the instance-length
partialEnd = Math.min(partialEnd, totalLength - 1);
long partialLength = partialEnd - partialStart + 1;
response.addHeader("Content-Length", "" + partialLength);
response.addHeader("Content-Range", "bytes " + partialStart + "-" + partialEnd + "/" + totalLength);
if (partialStart > 0) {
in.skip(partialStart);
}
OutputStream out = response.getOutputStream();
copy(in, out, partialLength);
response.flushBuffer();
}
private void copy(InputStream in, OutputStream out, Long length) throws IOException {
byte[] buffer = new byte[1024];
int read = 0;
while (length > 0 && (read = in.read(buffer, 0, (int) Math.min(length, buffer.length))) > 0) {
out.write(buffer, 0, read);
length -= read;
}
}
private String getFileName(Artifact artifact) {
return artifact.getMetadata().getFileName();
}
private String getMimeType(Artifact artifact) {
String mimeType = artifact.getMetadata().getMimeType();
if (mimeType == null || mimeType.isEmpty()) {
mimeType = "application/octet-stream";
}
return mimeType;
}
}
|
lumify-web/src/main/java/com/altamiracorp/lumify/web/routes/artifact/ArtifactRawByRowKey.java
|
package com.altamiracorp.lumify.web.routes.artifact;
import com.altamiracorp.lumify.core.ingest.video.VideoPlaybackDetails;
import com.altamiracorp.lumify.core.model.artifact.Artifact;
import com.altamiracorp.lumify.core.model.artifact.ArtifactRepository;
import com.altamiracorp.lumify.core.model.artifact.ArtifactRowKey;
import com.altamiracorp.lumify.core.model.graph.GraphRepository;
import com.altamiracorp.lumify.core.model.graph.GraphVertex;
import com.altamiracorp.lumify.core.user.User;
import com.altamiracorp.lumify.web.BaseRequestHandler;
import com.altamiracorp.miniweb.HandlerChain;
import com.altamiracorp.miniweb.utils.UrlUtils;
import com.google.inject.Inject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ArtifactRawByRowKey extends BaseRequestHandler {
private static final Pattern RANGE_PATTERN = Pattern.compile("bytes=([0-9]*)-([0-9]*)");
private final ArtifactRepository artifactRepository;
private final GraphRepository graphRepository;
@Inject
public ArtifactRawByRowKey(final ArtifactRepository repo, final GraphRepository graphRepository) {
this.graphRepository = graphRepository;
artifactRepository = repo;
}
public static String getUrl(ArtifactRowKey artifactKey) {
return "/artifact/" + UrlUtils.urlEncode(artifactKey.toString()) + "/raw";
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception {
boolean download = getOptionalParameter(request, "download") != null;
boolean videoPlayback = getOptionalParameter(request, "playback") != null;
User user = getUser(request);
ArtifactRowKey artifactKey = new ArtifactRowKey(UrlUtils.urlDecode(getAttributeString(request, "_rowKey")));
Artifact artifact = artifactRepository.findByRowKey(artifactKey.toString(), user.getModelUserContext());
if (artifact == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
chain.next(request, response);
return;
}
String graphVertexId = artifact.getMetadata().getGraphVertexId();
GraphVertex vertex = graphRepository.findVertex(graphVertexId, user);
String fileName = getFileName(artifact);
if (videoPlayback) {
handlePartialPlayback(request, response, artifact, fileName);
} else {
String mimeType = getMimeType(artifact);
response.setContentType(mimeType);
if (download) {
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
} else {
response.addHeader("Content-Disposition", "inline; filename=" + fileName);
}
InputStream in = artifactRepository.getRaw(artifact, vertex, user);
try {
IOUtils.copy(in, response.getOutputStream());
} finally {
in.close();
}
}
chain.next(request, response);
}
private void handlePartialPlayback(HttpServletRequest request, HttpServletResponse response, Artifact artifact, String fileName) throws IOException {
String videoType = getRequiredParameter(request, "type");
InputStream in = null;
long totalLength = 0;
long partialStart = 0;
Long partialEnd = null;
String range = request.getHeader("Range");
if (range != null) {
Matcher m = RANGE_PATTERN.matcher(range);
if (m.matches()) {
partialStart = Long.parseLong(m.group(1));
if (m.group(2).length() > 0) {
partialEnd = Long.parseLong(m.group(2));
}
if (partialEnd == null) {
partialEnd = partialStart + 100000 - 1;
}
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
}
}
if (videoType.equals("video/mp4") || videoType.equals("video/webm")) {
final String videoFormat = FilenameUtils.getBaseName(videoType);
response.setContentType(videoType);
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
VideoPlaybackDetails videoDetails = artifactRepository.getVideoPlaybackDetails(artifact.getRowKey().toString(), videoFormat);
in = videoDetails.getVideoStream();
totalLength = videoDetails.getVideoFileSize();
} else {
throw new RuntimeException("Invalid video type: " + videoType);
}
if (partialEnd == null) {
partialEnd = totalLength;
}
// Ensure that the last byte position is less than the instance-length
partialEnd = Math.min(partialEnd, totalLength - 1);
long partialLength = partialEnd - partialStart + 1;
response.addHeader("Content-Length", "" + partialLength);
response.addHeader("Content-Range", "bytes " + partialStart + "-" + partialEnd + "/" + totalLength);
if (partialStart > 0) {
in.skip(partialStart);
}
OutputStream out = response.getOutputStream();
copy(in, out, partialLength);
response.flushBuffer();
}
private void copy(InputStream in, OutputStream out, Long length) throws IOException {
byte[] buffer = new byte[1024];
int read = 0;
while (length > 0 && (read = in.read(buffer, 0, (int) Math.min(length, buffer.length))) > 0) {
out.write(buffer, 0, read);
length -= read;
}
}
private String getFileName(Artifact artifact) {
return artifact.getMetadata().getFileName() + "." + artifact.getMetadata().getFileExtension();
}
private String getMimeType(Artifact artifact) {
String mimeType = artifact.getMetadata().getMimeType();
if (mimeType == null || mimeType.isEmpty()) {
mimeType = "application/octet-stream";
}
return mimeType;
}
}
|
[#63478348] strip extension with date from filename
|
lumify-web/src/main/java/com/altamiracorp/lumify/web/routes/artifact/ArtifactRawByRowKey.java
|
[#63478348] strip extension with date from filename
|
<ide><path>umify-web/src/main/java/com/altamiracorp/lumify/web/routes/artifact/ArtifactRawByRowKey.java
<ide> }
<ide>
<ide> private String getFileName(Artifact artifact) {
<del> return artifact.getMetadata().getFileName() + "." + artifact.getMetadata().getFileExtension();
<add> return artifact.getMetadata().getFileName();
<ide> }
<ide>
<ide> private String getMimeType(Artifact artifact) {
|
|
Java
|
bsd-2-clause
|
a1d8923f7bee5740acb92e023950fb0ecae55363
| 0 |
stavamichal/perun,CESNET/perun,licehammer/perun,jirmauritz/perun,balcirakpeter/perun,Natrezim/perun,jirmauritz/perun,ondrejvelisek/perun,balcirakpeter/perun,licehammer/perun,dsarman/perun,D3jph/perun,mvocu/perun,jirmauritz/perun,stavamichal/perun,Natrezim/perun,martin-kuba/perun,dsarman/perun,Natrezim/perun,jirmauritz/perun,Natrezim/perun,zlamalp/perun,licehammer/perun,balcirakpeter/perun,balcirakpeter/perun,martin-kuba/perun,zoraseb/perun,ondrejvelisek/perun,martin-kuba/perun,zoraseb/perun,D3jph/perun,martin-kuba/perun,zoraseb/perun,zlamalp/perun,D3jph/perun,zwejra/perun,ondrejvelisek/perun,stavamichal/perun,dsarman/perun,zoraseb/perun,stavamichal/perun,stavamichal/perun,zwejra/perun,licehammer/perun,martin-kuba/perun,martin-kuba/perun,CESNET/perun,CESNET/perun,dsarman/perun,mvocu/perun,zwejra/perun,zwejra/perun,licehammer/perun,CESNET/perun,ondrejvelisek/perun,zwejra/perun,D3jph/perun,mvocu/perun,D3jph/perun,stavamichal/perun,mvocu/perun,jirmauritz/perun,CESNET/perun,stavamichal/perun,zlamalp/perun,zlamalp/perun,ondrejvelisek/perun,mvocu/perun,balcirakpeter/perun,D3jph/perun,CESNET/perun,zoraseb/perun,balcirakpeter/perun,zlamalp/perun,mvocu/perun,Natrezim/perun,zlamalp/perun,zlamalp/perun,mvocu/perun,Natrezim/perun,CESNET/perun,balcirakpeter/perun,licehammer/perun,jirmauritz/perun,dsarman/perun,ondrejvelisek/perun,zoraseb/perun,martin-kuba/perun,zwejra/perun,dsarman/perun
|
package cz.metacentrum.perun.registrar.modules;
import cz.metacentrum.perun.core.api.*;
import cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.PerunException;
import cz.metacentrum.perun.registrar.RegistrarManager;
import cz.metacentrum.perun.registrar.RegistrarModule;
import cz.metacentrum.perun.registrar.exceptions.CantBeApprovedException;
import cz.metacentrum.perun.registrar.model.Application;
import cz.metacentrum.perun.registrar.model.ApplicationFormItemData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Module for VO Metacentrum
*
* @author Pavel Zlamal <[email protected]>
*/
public class Metacentrum implements RegistrarModule {
final static Logger log = LoggerFactory.getLogger(Metacentrum.class);
private RegistrarManager registrar;
@Override
public void setRegistrar(RegistrarManager registrar) {
this.registrar = registrar;
}
@Override
public List<ApplicationFormItemData> createApplication(PerunSession user, Application application, List<ApplicationFormItemData> data) throws PerunException {
return data;
}
/**
* Add all new Metacentrum members to "storage" group.
*/
@Override
public Application approveApplication(PerunSession session, Application app) throws PerunException {
// get perun from session
Perun perun = session.getPerun();
if (Application.AppType.INITIAL.equals(app.getType())) {
Vo vo = app.getVo();
User user = app.getUser();
Group group = perun.getGroupsManager().getGroupByName(session, vo, "storage");
Member mem = perun.getMembersManager().getMemberByUser(session, vo, user);
try {
perun.getGroupsManager().addMember(session, group, mem);
} catch (AlreadyMemberException ex) {
}
}
// Support statistic groups
String statisticGroupName = "";
List<ApplicationFormItemData> formData = registrar.getApplicationDataById(session, app.getId());
for (ApplicationFormItemData item : formData) {
if (Objects.equals("urn:perun:user:attribute-def:def:researchGroupStatistic", item.getFormItem().getPerunDestinationAttribute())) {
statisticGroupName = item.getValue();
break;
}
}
if (statisticGroupName != null && !statisticGroupName.isEmpty()) {
Group group;
try {
group = perun.getGroupsManager().getGroupByName(session, app.getVo(), statisticGroupName);
} catch (GroupNotExistsException ex) {
// user filled non existing group, just skip adding
return app;
} catch (InternalErrorException ex) {
// wrong group name
return app;
}
Attribute isStatisticGroup = perun.getAttributesManager().getAttribute(session, group, "urn:perun:group:attribute-def:def:statisticGroup");
Attribute isStatisticGroupAutoFill = perun.getAttributesManager().getAttribute(session, group, "urn:perun:group:attribute-def:def:statisticGroupAutoFill");
boolean statisticGroup = (isStatisticGroup.getValue() != null) ? (Boolean)isStatisticGroup.getValue() : false;
boolean statisticGroupAutoFill = (isStatisticGroupAutoFill.getValue() != null) ? (Boolean)isStatisticGroupAutoFill.getValue() : false;
if (statisticGroup && statisticGroupAutoFill) {
try {
Member mem = perun.getMembersManager().getMemberByUser(session, app.getVo(), app.getUser());
perun.getGroupsManager().addMember(session, group, mem);
} catch (AlreadyMemberException ex) {
}
}
}
return app;
}
@Override
public Application rejectApplication(PerunSession session, Application app, String reason) throws PerunException {
return app;
}
@Override
public Application beforeApprove(PerunSession session, Application app) throws PerunException {
return app;
}
@Override
public void canBeApproved(PerunSession session, Application app) throws PerunException {
// allow only Education & Research community members
// allow hostel with loa=2
if (Objects.equals(app.getExtSourceName(), "https://idp.hostel.eduid.cz/idp/shibboleth") &&
app.getExtSourceLoa() == 2) return;
List<ApplicationFormItemData> data = registrar.getApplicationDataById(session, app.getId());
String category = "";
String affiliation = "";
for (ApplicationFormItemData item : data) {
if (item.getFormItem() != null && Objects.equals("md_entityCategory", item.getFormItem().getFederationAttribute())) {
if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
category = item.getValue();
break;
}
}
}
for (ApplicationFormItemData item : data) {
if (item.getFormItem() != null && Objects.equals("affiliation", item.getFormItem().getFederationAttribute())) {
if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
affiliation = item.getValue();
break;
}
}
}
if (category.contains("http://eduid.cz/uri/idp-group/university")) {
if (affiliation.contains("employee@") ||
affiliation.contains("faculty@") ||
affiliation.contains("member@") ||
affiliation.contains("student@") ||
affiliation.contains("staff@"))
return;
} else if (category.contains("http://eduid.cz/uri/idp-group/avcr")) {
if (affiliation.contains("member@")) return;
} else if (category.contains("http://eduid.cz/uri/idp-group/library")) {
if (affiliation.contains("employee@")) return;
} else if (category.contains("http://eduid.cz/uri/idp-group/hospital")) {
if (affiliation.contains("employee@")) return;
} else if (category.contains("http://eduid.cz/uri/idp-group/other")) {
if (affiliation.contains("employee@") || affiliation.contains("member@")) return;
}
throw new CantBeApprovedException("User is not active academia member", "NOT_ACADEMIC", category, affiliation, true);
}
@Override
public void canBeSubmitted(PerunSession session, Map<String, String> params) throws PerunException {
}
}
|
perun-registrar-lib/src/main/java/cz/metacentrum/perun/registrar/modules/Metacentrum.java
|
package cz.metacentrum.perun.registrar.modules;
import cz.metacentrum.perun.core.api.*;
import cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.PerunException;
import cz.metacentrum.perun.registrar.RegistrarManager;
import cz.metacentrum.perun.registrar.RegistrarModule;
import cz.metacentrum.perun.registrar.exceptions.CantBeApprovedException;
import cz.metacentrum.perun.registrar.model.Application;
import cz.metacentrum.perun.registrar.model.ApplicationFormItemData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Module for VO Metacentrum
*
* @author Pavel Zlamal <[email protected]>
*/
public class Metacentrum implements RegistrarModule {
final static Logger log = LoggerFactory.getLogger(Metacentrum.class);
private RegistrarManager registrar;
@Override
public void setRegistrar(RegistrarManager registrar) {
this.registrar = registrar;
}
@Override
public List<ApplicationFormItemData> createApplication(PerunSession user, Application application, List<ApplicationFormItemData> data) throws PerunException {
return data;
}
/**
* Add all new Metacentrum members to "storage" group.
*/
@Override
public Application approveApplication(PerunSession session, Application app) throws PerunException {
// get perun from session
Perun perun = session.getPerun();
if (Application.AppType.INITIAL.equals(app.getType())) {
Vo vo = app.getVo();
User user = app.getUser();
Group group = perun.getGroupsManager().getGroupByName(session, vo, "storage");
Member mem = perun.getMembersManager().getMemberByUser(session, vo, user);
try {
perun.getGroupsManager().addMember(session, group, mem);
} catch (AlreadyMemberException ex) {
}
}
// Support statistic groups
String statisticGroupName = "";
List<ApplicationFormItemData> formData = registrar.getApplicationDataById(session, app.getId());
for (ApplicationFormItemData item : formData) {
if (Objects.equals("urn:perun:user:attribute-def:def:researchGroupStatistic", item.getFormItem().getPerunDestinationAttribute())) {
statisticGroupName = item.getValue();
break;
}
}
if (statisticGroupName != null && !statisticGroupName.isEmpty()) {
Group group;
try {
group = perun.getGroupsManager().getGroupByName(session, app.getVo(), statisticGroupName);
} catch (GroupNotExistsException ex) {
// user filled non existing group, just skip adding
return app;
}
Attribute isStatisticGroup = perun.getAttributesManager().getAttribute(session, group, "urn:perun:group:attribute-def:def:statisticGroup");
Attribute isStatisticGroupAutoFill = perun.getAttributesManager().getAttribute(session, group, "urn:perun:group:attribute-def:def:statisticGroupAutoFill");
boolean statisticGroup = (isStatisticGroup.getValue() != null) ? (Boolean)isStatisticGroup.getValue() : false;
boolean statisticGroupAutoFill = (isStatisticGroupAutoFill.getValue() != null) ? (Boolean)isStatisticGroupAutoFill.getValue() : false;
if (statisticGroup && statisticGroupAutoFill) {
try {
Member mem = perun.getMembersManager().getMemberByUser(session, app.getVo(), app.getUser());
perun.getGroupsManager().addMember(session, group, mem);
} catch (AlreadyMemberException ex) {
}
}
}
return app;
}
@Override
public Application rejectApplication(PerunSession session, Application app, String reason) throws PerunException {
return app;
}
@Override
public Application beforeApprove(PerunSession session, Application app) throws PerunException {
return app;
}
@Override
public void canBeApproved(PerunSession session, Application app) throws PerunException {
// allow only Education & Research community members
// allow hostel with loa=2
if (Objects.equals(app.getExtSourceName(), "https://idp.hostel.eduid.cz/idp/shibboleth") &&
app.getExtSourceLoa() == 2) return;
List<ApplicationFormItemData> data = registrar.getApplicationDataById(session, app.getId());
String category = "";
String affiliation = "";
for (ApplicationFormItemData item : data) {
if (item.getFormItem() != null && Objects.equals("md_entityCategory", item.getFormItem().getFederationAttribute())) {
if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
category = item.getValue();
break;
}
}
}
for (ApplicationFormItemData item : data) {
if (item.getFormItem() != null && Objects.equals("affiliation", item.getFormItem().getFederationAttribute())) {
if (item.getValue() != null && !item.getValue().trim().isEmpty()) {
affiliation = item.getValue();
break;
}
}
}
if (category.contains("http://eduid.cz/uri/idp-group/university")) {
if (affiliation.contains("employee@") ||
affiliation.contains("faculty@") ||
affiliation.contains("member@") ||
affiliation.contains("student@") ||
affiliation.contains("staff@"))
return;
} else if (category.contains("http://eduid.cz/uri/idp-group/avcr")) {
if (affiliation.contains("member@")) return;
} else if (category.contains("http://eduid.cz/uri/idp-group/library")) {
if (affiliation.contains("employee@")) return;
} else if (category.contains("http://eduid.cz/uri/idp-group/hospital")) {
if (affiliation.contains("employee@")) return;
} else if (category.contains("http://eduid.cz/uri/idp-group/other")) {
if (affiliation.contains("employee@") || affiliation.contains("member@")) return;
}
throw new CantBeApprovedException("User is not active academia member", "NOT_ACADEMIC", category, affiliation, true);
}
@Override
public void canBeSubmitted(PerunSession session, Map<String, String> params) throws PerunException {
}
}
|
REGISTRAR: Catch also InternalErrorException
- Allow to approve applications even when user entered
not valid group name.
|
perun-registrar-lib/src/main/java/cz/metacentrum/perun/registrar/modules/Metacentrum.java
|
REGISTRAR: Catch also InternalErrorException
|
<ide><path>erun-registrar-lib/src/main/java/cz/metacentrum/perun/registrar/modules/Metacentrum.java
<ide> import cz.metacentrum.perun.core.api.*;
<ide> import cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException;
<ide> import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
<add>import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
<ide> import cz.metacentrum.perun.core.api.exceptions.PerunException;
<ide> import cz.metacentrum.perun.registrar.RegistrarManager;
<ide> import cz.metacentrum.perun.registrar.RegistrarModule;
<ide> group = perun.getGroupsManager().getGroupByName(session, app.getVo(), statisticGroupName);
<ide> } catch (GroupNotExistsException ex) {
<ide> // user filled non existing group, just skip adding
<add> return app;
<add> } catch (InternalErrorException ex) {
<add> // wrong group name
<ide> return app;
<ide> }
<ide>
|
|
JavaScript
|
mit
|
34eac523f07f0755500eb6d30edda6a8839433f5
| 0 |
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
|
(function() {
angular.module('ncsaas')
.controller('ProjectEventTabController', [
'$stateParams',
'projectsService',
'baseEventListController',
'currentStateService',
ProjectEventTabController
]);
function ProjectEventTabController($stateParams, projectsService, baseEventListController, currentStateService) {
var controllerScope = this;
var EventController = baseEventListController.extend({
project: null,
init: function() {
this.controllerScope = controllerScope;
this._super();
this.getProject();
},
getList: function(filter) {
if (this.project) {
this.service.defaultFilter.scope = this.project.url;
return this._super(filter);
} else {
return this.getProject();
}
},
getProject: function() {
var vm = this;
if ($stateParams.uuid) {
return projectsService.$get($stateParams.uuid).then(function(response) {
vm.project = response;
return vm.getList();
});
} else {
return currentStateService.getProject().then(function(response) {
vm.project = response;
return vm.getList();
});
}
}
});
controllerScope.__proto__ = new EventController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectAlertTabController', [
'BaseAlertsListController',
'currentStateService',
ProjectAlertTabController
]);
function ProjectAlertTabController(
BaseAlertsListController,
currentStateService
) {
var controllerScope = this;
var AlertController = BaseAlertsListController.extend({
init: function() {
this.controllerScope = controllerScope;
this._super();
},
getList: function(filter) {
var getList = this._super.bind(controllerScope),
vm = this;
this.service.defaultFilter.aggregate = 'project';
this.service.defaultFilter.opened = true;
return currentStateService.getProject().then(function(response) {
vm.service.defaultFilter.uuid = response.uuid;
return getList(filter);
});
}
});
controllerScope.__proto__ = new AlertController();
}
})();
(function() {
angular.module('ncsaas')
.service('BaseProjectResourcesTabController', [
'baseResourceListController', 'currentStateService', BaseProjectResourcesTabController]);
function BaseProjectResourcesTabController(baseResourceListController, currentStateService) {
var controllerClass = baseResourceListController.extend({
getList: function(filter) {
var vm = this;
var fn = this._super.bind(vm);
return currentStateService.getProject().then(function(project){
vm.service.defaultFilter.project_uuid = project.uuid;
return fn(filter);
})
}
});
return controllerClass;
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectResourcesTabController', [
'BaseProjectResourcesTabController',
'ENV',
ProjectResourcesTabController
]);
function ProjectResourcesTabController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init: function() {
this.controllerScope = controllerScope;
this.category = ENV.VirtualMachines;
this._super();
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no virtual machines yet';
options.noMatchesText = 'No virtual machines found matching filter.';
return options;
},
getImportTitle: function() {
return 'Import virtual machine';
},
getCreateTitle: function() {
return 'Add virtual machine';
},
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectPrivateCloudsTabController', [
'BaseProjectResourcesTabController',
'ENV',
ProjectPrivateCloudsTabController
]);
function ProjectPrivateCloudsTabController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init: function() {
this.controllerScope = controllerScope;
this.category = ENV.PrivateClouds;
this._super();
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no private clouds yet';
options.noMatchesText = 'No private clouds found matching filter.';
return options;
},
getImportTitle: function() {
return 'Import private cloud';
},
getCreateTitle: function() {
return 'Add private cloud';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectApplicationsTabController', [
'BaseProjectResourcesTabController', 'ENV',
ProjectApplicationsTabController]);
function ProjectApplicationsTabController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init:function() {
this.controllerScope = controllerScope;
this.category = ENV.Applications;
this._super();
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no applications yet.';
options.noMatchesText = 'No applications found matching filter.';
return options;
},
getImportTitle: function() {
return 'Import application';
},
getCreateTitle: function() {
return 'Add application';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('VolumesListController', [
'BaseProjectResourcesTabController',
'ncUtils',
'$state',
'ENV',
VolumesListController]);
function VolumesListController(BaseProjectResourcesTabController, ncUtils, $state, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init:function() {
this.category = ENV.Storages;
this.controllerScope = controllerScope;
this._super();
this.rowFields.push('instance');
this.rowFields.push('instance_name');
},
getFilter: function() {
return {
resource_type: 'OpenStack.Volume'
};
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no volumes yet.';
options.noMatchesText = 'No volumes found matching filter.';
options.columns.push({
title: 'Attached to',
render: function(data, type, row, meta) {
if (!row.instance) {
return 'Not known';
}
var uuid = ncUtils.getUUID(row.instance);
var href = $state.href('resources.details', {
uuid: uuid,
resource_type: 'OpenStack.Instance'
});
return ncUtils.renderLink(href, row.instance_name || 'Link');
}
});
return options;
},
getImportTitle: function() {
return 'Import volumes';
},
getCreateTitle: function() {
return 'Add volumes';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('SnapshotsListController', [
'BaseProjectResourcesTabController', 'ncUtils', '$state',
SnapshotsListController]);
function SnapshotsListController(BaseProjectResourcesTabController, ncUtils, $state) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init:function() {
this.controllerScope = controllerScope;
this._super();
this.rowFields.push('source_volume');
this.rowFields.push('source_volume_name');
},
getFilter: function(filter) {
return {
resource_type: 'OpenStack.Snapshot'
};
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no snapshots yet.';
options.noMatchesText = 'No snapshots found matching filter.';
options.columns.push({
title: 'Volume',
render: function(data, type, row, meta) {
if (!row.source_volume) {
return 'Not known';
}
var uuid = ncUtils.getUUID(row.source_volume);
var href = $state.href('resources.details', {
uuid: uuid,
resource_type: 'OpenStack.Volume'
});
return ncUtils.renderLink(href, row.source_volume_name || 'Link');
}
});
return options;
},
getImportTitle: function() {
return 'Import snapshots';
},
getCreateTitle: function() {
return 'Add snapshots';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectSupportTabController', [
'baseControllerListClass',
'premiumSupportContractsService',
'premiumSupportPlansService',
'currentStateService',
'ENTITYLISTFIELDTYPES',
'ENV',
'$filter',
'$stateParams',
'ncUtils',
ProjectSupportTabController
]);
function ProjectSupportTabController(
baseControllerListClass,
premiumSupportContractsService,
premiumSupportPlansService,
currentStateService,
ENTITYLISTFIELDTYPES,
ENV,
$filter,
$stateParams,
ncUtils
) {
var controllerScope = this;
var ResourceController = baseControllerListClass.extend({
init: function() {
this.controllerScope = controllerScope;
this.service = premiumSupportContractsService;
this._super();
this.entityOptions = {
entityData: {
noDataText: 'You have no SLAs yet.',
createLink: 'appstore.store({category: "support"})',
createLinkText: 'Add SLA',
expandable: true,
hideActionButtons: true
},
list: [
{
name: 'Name',
propertyName: 'plan_name',
type: ENTITYLISTFIELDTYPES.none,
showForMobile: ENTITYLISTFIELDTYPES.showForMobile
},
{
name: 'State',
propertyName: 'state',
type: ENTITYLISTFIELDTYPES.none,
showForMobile: ENTITYLISTFIELDTYPES.showForMobile
}
]
};
this.expandableOptions = [
{
isList: false,
addItemBlock: false,
viewType: 'description',
items: [
{
key: 'plan_description',
label: 'Description'
},
{
key: 'plan_base_rate',
label: 'Base rate'
},
{
key: 'plan_hour_rate',
label: 'Hour rate'
},
{
key: 'plan_terms',
label: 'Terms'
}
]
}
];
},
getList: function(filter) {
var vm = this;
var fn = this._super.bind(vm);
if ($stateParams.uuid) {
this.service.defaultFilter.project_uuid = $stateParams.uuid;
return fn(filter);
}
return currentStateService.getProject().then(function(project) {
vm.service.defaultFilter.project_uuid = project.uuid;
return fn(filter);
})
},
showMore: function(contract) {
var promise = premiumSupportPlansService.$get(null, contract.plan).then(function(response) {
contract.plan_description = response.description;
contract.plan_terms = response.terms;
contract.plan_base_rate = $filter('currency')(response.base_rate, ENV.currency);
contract.plan_hour_rate = $filter('currency')(response.hour_rate, ENV.currency);
});
ncUtils.blockElement('block_'+contract.uuid, promise);
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectDeleteTabController', [
'baseControllerClass',
'projectsService',
'currentStateService',
'$rootScope',
'$state',
'$q',
ProjectDeleteTabController
]);
function ProjectDeleteTabController(
baseControllerClass,
projectsService,
currentStateService,
$rootScope,
$state,
$q
) {
var controllerScope = this;
var DeleteController = baseControllerClass.extend({
init: function() {
this.controllerScope = controllerScope;
this.service = projectsService;
this._super();
var vm = this;
currentStateService.getProject().then(function(project) {
vm.project = project;
});
},
removeProject: function () {
var confirmDelete = confirm('Confirm deletion?'),
vm = this;
if (confirmDelete) {
currentStateService.setProject(null);
return this.project.$delete().then(function() {
projectsService.clearAllCacheForCurrentEndpoint();
return projectsService.getFirst().then(function(project) {
currentStateService.setProject(project);
$rootScope.$broadcast('refreshProjectList', {model: controllerScope.project, remove: true});
});
}, function() {
currentStateService.setProject(vm.project);
}).then(function() {
currentStateService.reloadCurrentCustomer(function(customer) {
$rootScope.$broadcast('checkQuotas:refresh');
$rootScope.$broadcast('customerBalance:refresh');
$state.go('organization.projects', {uuid: customer.uuid});
});
});
} else {
return $q.reject();
}
}
});
controllerScope.__proto__ = new DeleteController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectUsersListController', [
'baseControllerListClass',
'projectsService',
'currentProject',
ProjectUsersListController
]);
function ProjectUsersListController(
baseControllerListClass,
projectsService,
currentProject) {
var controllerScope = this;
var TeamController = baseControllerListClass.extend({
init: function() {
this.controllerScope = controllerScope;
this.service = projectsService;
this.hideNoDataText = true;
this.tableOptions = this.getTableOptions();
this._super();
},
getTableOptions: function() {
return {
noDataText: 'You have no team members yet',
noMatchesText: 'No members found matching filter.',
searchFieldName: 'full_name',
columns: [
{
title: 'Member',
render: function(data, type, row, meta) {
var avatar = '<img gravatar-src="\'{gravatarSrc}\'" gravatar-size="100" alt="" class="avatar-img img-xs">'
.replace('{gravatarSrc}', row.email);
return avatar + ' ' + (row.full_name || row.username);
}
},
{
title: 'E-mail',
render: function(data, type, row, meta) {
return row.email;
}
},
{
title: 'Role in project:',
render: function(data, type, row, meta) {
return row.role;
}
}
]
};
},
getFilter: function() {
return {operation: 'users', UUID: currentProject.uuid};
}
});
controllerScope.__proto__ = new TeamController();
}
})();
|
app/scripts/controllers/projects-tabs-controllers.js
|
(function() {
angular.module('ncsaas')
.controller('ProjectEventTabController', [
'$stateParams',
'projectsService',
'baseEventListController',
'currentStateService',
ProjectEventTabController
]);
function ProjectEventTabController($stateParams, projectsService, baseEventListController, currentStateService) {
var controllerScope = this;
var EventController = baseEventListController.extend({
project: null,
init: function() {
this.controllerScope = controllerScope;
this._super();
this.getProject();
},
getList: function(filter) {
if (this.project) {
this.service.defaultFilter.scope = this.project.url;
return this._super(filter);
} else {
return this.getProject();
}
},
getProject: function() {
var vm = this;
if ($stateParams.uuid) {
return projectsService.$get($stateParams.uuid).then(function(response) {
vm.project = response;
return vm.getList();
});
} else {
return currentStateService.getProject().then(function(response) {
vm.project = response;
return vm.getList();
});
}
}
});
controllerScope.__proto__ = new EventController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectAlertTabController', [
'BaseAlertsListController',
'currentStateService',
ProjectAlertTabController
]);
function ProjectAlertTabController(
BaseAlertsListController,
currentStateService
) {
var controllerScope = this;
var AlertController = BaseAlertsListController.extend({
init: function() {
this.controllerScope = controllerScope;
this._super();
},
getList: function(filter) {
var getList = this._super.bind(controllerScope),
vm = this;
this.service.defaultFilter.aggregate = 'project';
this.service.defaultFilter.opened = true;
return currentStateService.getProject().then(function(response) {
vm.service.defaultFilter.uuid = response.uuid;
return getList(filter);
});
}
});
controllerScope.__proto__ = new AlertController();
}
})();
(function() {
angular.module('ncsaas')
.service('BaseProjectResourcesTabController', [
'baseResourceListController', 'currentStateService', BaseProjectResourcesTabController]);
function BaseProjectResourcesTabController(baseResourceListController, currentStateService) {
var controllerClass = baseResourceListController.extend({
getList: function(filter) {
var vm = this;
var fn = this._super.bind(vm);
return currentStateService.getProject().then(function(project){
vm.service.defaultFilter.project_uuid = project.uuid;
return fn(filter);
})
}
});
return controllerClass;
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectResourcesTabController', [
'BaseProjectResourcesTabController',
'ENV',
ProjectResourcesTabController
]);
function ProjectResourcesTabController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init: function() {
this.controllerScope = controllerScope;
this.category = ENV.VirtualMachines;
this._super();
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no virtual machines yet';
options.noMatchesText = 'No virtual machines found matching filter.';
return options;
},
getImportTitle: function() {
return 'Import virtual machine';
},
getCreateTitle: function() {
return 'Add virtual machine';
},
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectPrivateCloudsTabController', [
'BaseProjectResourcesTabController',
'ENV',
ProjectPrivateCloudsTabController
]);
function ProjectPrivateCloudsTabController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init: function() {
this.controllerScope = controllerScope;
this.category = ENV.PrivateClouds;
this._super();
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no private clouds yet';
options.noMatchesText = 'No private clouds found matching filter.';
return options;
},
getImportTitle: function() {
return 'Import private cloud';
},
getCreateTitle: function() {
return 'Add private cloud';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectApplicationsTabController', [
'BaseProjectResourcesTabController', 'ENV',
ProjectApplicationsTabController]);
function ProjectApplicationsTabController(BaseProjectResourcesTabController, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init:function() {
this.controllerScope = controllerScope;
this.category = ENV.Applications;
this._super();
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no applications yet.';
options.noMatchesText = 'No applications found matching filter.';
return options;
},
getImportTitle: function() {
return 'Import application';
},
getCreateTitle: function() {
return 'Add application';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('VolumesListController', [
'BaseProjectResourcesTabController',
'ncUtils',
'$state',
'ENV',
VolumesListController]);
function VolumesListController(BaseProjectResourcesTabController, ncUtils, $state, ENV) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init:function() {
this.category = ENV.Storages;
this.controllerScope = controllerScope;
this._super();
this.rowFields.push('instance');
this.rowFields.push('instance_name');
},
getFilter: function() {
return {
resource_type: 'OpenStack.Volume'
};
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no volumes yet.';
options.noMatchesText = 'No volumes found matching filter.';
options.columns.push({
title: 'Attached to',
render: function(data, type, row, meta) {
if (!row.instance) {
return 'Not known';
}
var uuid = ncUtils.getUUID(row.instance);
var href = $state.href('resources.details', {
uuid: uuid,
resource_type: 'OpenStack.Instance'
});
return ncUtils.renderLink(href, row.instance_name || 'Link');
}
});
return options;
},
getImportTitle: function() {
return 'Import volumes';
},
getCreateTitle: function() {
return 'Add volumes';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('SnapshotsListController', [
'BaseProjectResourcesTabController', 'ncUtils', '$state',
SnapshotsListController]);
function SnapshotsListController(BaseProjectResourcesTabController, ncUtils, $state) {
var controllerScope = this;
var ResourceController = BaseProjectResourcesTabController.extend({
init:function() {
this.controllerScope = controllerScope;
this._super();
this.rowFields.push('source_volume');
this.rowFields.push('source_volume_name');
},
getFilter: function(filter) {
return {
resource_type: 'OpenStack.Snapshot'
};
},
getTableOptions: function() {
var options = this._super();
options.noDataText = 'You have no snapshots yet.';
options.noMatchesText = 'No snapshots found matching filter.';
options.columns.push({
title: 'Volume',
render: function(data, type, row, meta) {
if (!row.source_volume) {
return 'Not known';
}
var uuid = ncUtils.getUUID(row.source_volume);
var href = $state.href('resources.details', {
uuid: uuid,
resource_type: 'OpenStack.Volume'
});
return ncUtils.renderLink(href, row.source_volume_name || 'Link');
}
});
return options;
},
getImportTitle: function() {
return 'Import snapshots';
},
getCreateTitle: function() {
return 'Add snapshots';
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectSupportTabController', [
'baseControllerListClass',
'premiumSupportContractsService',
'premiumSupportPlansService',
'currentStateService',
'ENTITYLISTFIELDTYPES',
'ENV',
'$filter',
'$stateParams',
'ncUtils',
ProjectSupportTabController
]);
function ProjectSupportTabController(
baseControllerListClass,
premiumSupportContractsService,
premiumSupportPlansService,
currentStateService,
ENTITYLISTFIELDTYPES,
ENV,
$filter,
$stateParams,
ncUtils
) {
var controllerScope = this;
var ResourceController = baseControllerListClass.extend({
init: function() {
this.controllerScope = controllerScope;
this.service = premiumSupportContractsService;
this._super();
this.entityOptions = {
entityData: {
noDataText: 'You have no SLAs yet.',
createLink: 'appstore.store({category: "support"})',
createLinkText: 'Add SLA',
expandable: true,
hideActionButtons: true
},
list: [
{
name: 'Name',
propertyName: 'plan_name',
type: ENTITYLISTFIELDTYPES.none,
showForMobile: ENTITYLISTFIELDTYPES.showForMobile
},
{
name: 'State',
propertyName: 'state',
type: ENTITYLISTFIELDTYPES.none,
showForMobile: ENTITYLISTFIELDTYPES.showForMobile
}
]
};
this.expandableOptions = [
{
isList: false,
addItemBlock: false,
viewType: 'description',
items: [
{
key: 'plan_description',
label: 'Description'
},
{
key: 'plan_base_rate',
label: 'Base rate'
},
{
key: 'plan_hour_rate',
label: 'Hour rate'
},
{
key: 'plan_terms',
label: 'Terms'
}
]
}
];
},
getList: function(filter) {
var vm = this;
var fn = this._super.bind(vm);
if ($stateParams.uuid) {
this.service.defaultFilter.project_uuid = $stateParams.uuid;
return fn(filter);
}
return currentStateService.getProject().then(function(project) {
vm.service.defaultFilter.project_uuid = project.uuid;
return fn(filter);
})
},
showMore: function(contract) {
var promise = premiumSupportPlansService.$get(null, contract.plan).then(function(response) {
contract.plan_description = response.description;
contract.plan_terms = response.terms;
contract.plan_base_rate = $filter('currency')(response.base_rate, ENV.currency);
contract.plan_hour_rate = $filter('currency')(response.hour_rate, ENV.currency);
});
ncUtils.blockElement('block_'+contract.uuid, promise);
}
});
controllerScope.__proto__ = new ResourceController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectDeleteTabController', [
'baseControllerClass',
'projectsService',
'currentStateService',
'$rootScope',
'$state',
'$q',
ProjectDeleteTabController
]);
function ProjectDeleteTabController(
baseControllerClass,
projectsService,
currentStateService,
$rootScope,
$state,
$q
) {
var controllerScope = this;
var DeleteController = baseControllerClass.extend({
init: function() {
this.controllerScope = controllerScope;
this.service = projectsService;
this._super();
var vm = this;
currentStateService.getProject().then(function(project) {
vm.project = project;
});
},
removeProject: function () {
var confirmDelete = confirm('Confirm deletion?'),
vm = this;
if (confirmDelete) {
currentStateService.setProject(null);
return this.project.$delete().then(function() {
projectsService.clearAllCacheForCurrentEndpoint();
return projectsService.getFirst().then(function(project) {
currentStateService.setProject(project);
$rootScope.$broadcast('refreshProjectList', {model: controllerScope.project, remove: true});
});
}, function() {
currentStateService.setProject(vm.project);
}).then(function() {
currentStateService.reloadCurrentCustomer(function(customer) {
$rootScope.$broadcast('checkQuotas:refresh');
$rootScope.$broadcast('customerBalance:refresh');
$state.go('organization.projects', {uuid: customer.uuid});
});
});
} else {
return $q.reject();
}
}
});
controllerScope.__proto__ = new DeleteController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectUsersListController', [
'baseControllerListClass',
'projectsService',
'currentProject',
ProjectUsersListController
]);
function ProjectUsersListController(
baseControllerListClass,
projectsService,
currentProject) {
var controllerScope = this;
var TeamController = baseControllerListClass.extend({
init: function() {
this.controllerScope = controllerScope;
this.service = projectsService;
this.hideNoDataText = true;
this.tableOptions = this.getTableOptions();
this._super();
},
getTableOptions: function() {
return {
noDataText: 'You have no team members yet',
noMatchesText: 'No members found matching filter.',
searchFieldName: 'full_name',
columns: [
{
title: 'Member',
render: function(data, type, row, meta) {
var avatar = '<img gravatar-src="\'{gravatarSrc}\'" gravatar-size="100" alt="" class="avatar-img img-xs">'
.replace('{gravatarSrc}', row.email);
return avatar + ' ' + (row.full_name || row.username);
}
},
{
title: 'E-mail',
render: function(data, type, row, meta) {
return row.email;
}
},
{
title: 'Role in project:',
render: function(data, type, row, meta) {
return row.role;
}
}
]
};
},
getList: function(filter) {
return this._super(angular.extend(this.getFilter(), filter));
},
getFilter: function() {
return {operation: 'users', UUID: currentProject.uuid};
}
});
controllerScope.__proto__ = new TeamController();
}
})();
|
Removed unnecessary call to getList from projectUsersList controller
|
app/scripts/controllers/projects-tabs-controllers.js
|
Removed unnecessary call to getList from projectUsersList controller
|
<ide><path>pp/scripts/controllers/projects-tabs-controllers.js
<ide> ]
<ide> };
<ide> },
<del> getList: function(filter) {
<del> return this._super(angular.extend(this.getFilter(), filter));
<del> },
<ide> getFilter: function() {
<ide> return {operation: 'users', UUID: currentProject.uuid};
<ide> }
|
|
Java
|
apache-2.0
|
a57428151f5ef70568d71e0b4433b407085dd7e2
| 0 |
HappyRay/azkaban,azkaban/azkaban,chengren311/azkaban,chengren311/azkaban,HappyRay/azkaban,azkaban/azkaban,chengren311/azkaban,HappyRay/azkaban,HappyRay/azkaban,chengren311/azkaban,azkaban/azkaban,HappyRay/azkaban,azkaban/azkaban,azkaban/azkaban,azkaban/azkaban,chengren311/azkaban,HappyRay/azkaban
|
/*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.jobtype;
import static org.apache.hadoop.security.UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION;
import java.io.File;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import org.apache.pig.PigRunner;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.JavaProcessJob;
import azkaban.security.commons.HadoopSecurityManager;
import azkaban.utils.Props;
import azkaban.utils.StringUtils;
/*
* need lib:
* apache pig
* hadoop-core*.jar
* HadoopSecurePigWrapper
* HadoopSecurityManager(corresponding version with hadoop)
* abandon support for pig 0.8 and prior versions. don't see a use case here.
*/
public class HadoopPigJob extends JavaProcessJob {
public static final String PIG_SCRIPT = "pig.script";
public static final String UDF_IMPORT = "udf.import.list";
public static final String PIG_ADDITIONAL_JARS = "pig.additional.jars";
public static final String DEFAULT_PIG_ADDITIONAL_JARS =
"default.pig.additional.jars";
public static final String PIG_PARAM_PREFIX = "param.";
public static final String PIG_PARAM_FILES = "paramfile";
public static final String HADOOP_UGI = "hadoop.job.ugi";
public static final String DEBUG = "debug";
public static String HADOOP_SECURE_PIG_WRAPPER =
"azkaban.jobtype.HadoopSecurePigWrapper";
private String userToProxy = null;
private boolean shouldProxy = false;
private boolean obtainTokens = false;
File tokenFile = null;
private final boolean userPigJar;
private HadoopSecurityManager hadoopSecurityManager;
private File pigLogFile = null;
public HadoopPigJob(String jobid, Props sysProps, Props jobProps, Logger log)
throws IOException {
super(jobid, sysProps, jobProps, log);
HADOOP_SECURE_PIG_WRAPPER = HadoopSecurePigWrapper.class.getName();
getJobProps().put(CommonJobProperties.JOB_ID, jobid);
shouldProxy =
getSysProps().getBoolean(HadoopSecurityManager.ENABLE_PROXYING, false);
getJobProps().put(HadoopSecurityManager.ENABLE_PROXYING,
Boolean.toString(shouldProxy));
obtainTokens =
getSysProps().getBoolean(HadoopSecurityManager.OBTAIN_BINARY_TOKEN,
false);
userPigJar = getJobProps().getBoolean("use.user.pig.jar", false);
if (shouldProxy) {
getLog().info("Initiating hadoop security manager.");
try {
hadoopSecurityManager =
HadoopJobUtils.loadHadoopSecurityManager(getSysProps(), log);
} catch (RuntimeException e) {
throw new RuntimeException("Failed to get hadoop security manager!" + e);
}
}
}
@Override
public void run() throws Exception {
String[] tagKeys = new String[] { CommonJobProperties.EXEC_ID,
CommonJobProperties.FLOW_ID, CommonJobProperties.PROJECT_NAME };
getJobProps().put(HadoopConfigurationInjector.INJECT_PREFIX
+ HadoopJobUtils.MAPREDUCE_JOB_TAGS,
HadoopJobUtils.constructHadoopTags(getJobProps(), tagKeys));
HadoopConfigurationInjector.prepareResourcesToInject(getJobProps(),
getWorkingDirectory());
if (shouldProxy && obtainTokens) {
userToProxy = getJobProps().getString("user.to.proxy");
getLog().info("Need to proxy. Getting tokens.");
// get tokens in to a file, and put the location in props
Props props = new Props();
props.putAll(getJobProps());
props.putAll(getSysProps());
HadoopJobUtils.addAdditionalNamenodesToPropsFromMRJob(props, getLog());
tokenFile =
HadoopJobUtils
.getHadoopTokens(hadoopSecurityManager, props, getLog());
getJobProps().put("env." + HADOOP_TOKEN_FILE_LOCATION,
tokenFile.getAbsolutePath());
}
try {
super.run();
} catch (Throwable t) {
t.printStackTrace();
getLog().error("caught error running the job", t);
throw new Exception(t);
} finally {
if (tokenFile != null) {
HadoopJobUtils.cancelHadoopTokens(hadoopSecurityManager, userToProxy,
tokenFile, getLog());
if (tokenFile.exists()) {
tokenFile.delete();
}
}
}
}
@Override
protected String getJavaClass() {
return HADOOP_SECURE_PIG_WRAPPER;
}
@Override
protected String getJVMArguments() {
String args = super.getJVMArguments();
String typeGlobalJVMArgs =
getSysProps().getString("jobtype.global.jvm.args", null);
if (typeGlobalJVMArgs != null) {
args += " " + typeGlobalJVMArgs;
}
List<String> udfImport = getUDFImportList();
if (udfImport.size() > 0) {
args += " -Dudf.import.list=" + super.createArguments(udfImport, ":");
}
List<String> additionalJars = getAdditionalJarsList();
if (additionalJars.size() > 0) {
args +=
" -Dpig.additional.jars="
+ super.createArguments(additionalJars, ":");
}
String hadoopUGI = getHadoopUGI();
if (hadoopUGI != null) {
args += " -Dhadoop.job.ugi=" + hadoopUGI;
}
if (shouldProxy) {
info("Setting up secure proxy info for child process");
String secure;
secure =
" -D" + HadoopSecurityManager.USER_TO_PROXY + "="
+ getJobProps().getString(HadoopSecurityManager.USER_TO_PROXY);
String extraToken =
getSysProps().getString(HadoopSecurityManager.OBTAIN_BINARY_TOKEN,
"false");
if (extraToken != null) {
secure +=
" -D" + HadoopSecurityManager.OBTAIN_BINARY_TOKEN + "="
+ extraToken;
}
info("Secure settings = " + secure);
args += secure;
} else {
info("Not setting up secure proxy info for child process");
}
return args;
}
@Override
protected String getMainArguments() {
ArrayList<String> list = new ArrayList<String>();
Map<String, String> map = getPigParams();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
list.add("-param "
+ StringUtils.shellQuote(entry.getKey() + "=" + entry.getValue(),
StringUtils.SINGLE_QUOTE));
}
}
List<String> paramFiles = getPigParamFiles();
if (paramFiles != null) {
for (String paramFile : paramFiles) {
list.add("-param_file " + paramFile);
}
}
if (getDebug()) {
list.add("-debug");
}
try {
pigLogFile =
File.createTempFile("piglogfile", ".log", new File(
getWorkingDirectory()));
jobProps.put("env." + "PIG_LOG_FILE", pigLogFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
if (pigLogFile != null) {
list.add("-logfile " + pigLogFile.getAbsolutePath());
}
list.add(getScript());
return StringUtils.join((Collection<String>) list, " ");
}
@Override
protected List<String> getClassPaths() {
List<String> classPath = super.getClassPaths();
// To add az-core jar classpath
classPath.add(getSourcePathFromClass(Props.class));
// To add az-common jar classpath
classPath.add(getSourcePathFromClass(JavaProcessJob.class));
classPath.add(getSourcePathFromClass(HadoopSecurePigWrapper.class));
classPath.add(getSourcePathFromClass(HadoopSecurityManager.class));
classPath.add(HadoopConfigurationInjector.getPath(getJobProps(),
getWorkingDirectory()));
// assuming pig 0.8 and up
if (!userPigJar) {
classPath.add(getSourcePathFromClass(PigRunner.class));
}
// merging classpaths from plugin.properties
mergeClassPaths(classPath,
getJobProps().getStringList("jobtype.classpath", null, ","));
// merging classpaths from private.properties
mergeClassPaths(classPath,
getSysProps().getStringList("jobtype.classpath", null, ","));
List<String> typeGlobalClassPath =
getSysProps().getStringList("jobtype.global.classpath", null, ",");
if (typeGlobalClassPath != null) {
for (String jar : typeGlobalClassPath) {
if (!classPath.contains(jar)) {
classPath.add(jar);
}
}
}
return classPath;
}
private void mergeClassPaths(List<String> classPath,
List<String> typeClassPath) {
if (typeClassPath != null) {
// fill in this when load this jobtype
String pluginDir = getSysProps().get("plugin.dir");
for (String jar : typeClassPath) {
File jarFile = new File(jar);
if (!jarFile.isAbsolute()) {
jarFile = new File(pluginDir + File.separatorChar + jar);
}
if (!classPath.contains(jarFile.getAbsolutePath())) {
classPath.add(jarFile.getAbsolutePath());
}
}
}
}
protected boolean getDebug() {
return getJobProps().getBoolean(DEBUG, false);
}
protected String getScript() {
return getJobProps().getString(PIG_SCRIPT);
}
protected List<String> getUDFImportList() {
List<String> udfImports = new ArrayList<String>();
List<String> typeImports =
getSysProps().getStringList(UDF_IMPORT, null, ",");
List<String> jobImports =
getJobProps().getStringList(UDF_IMPORT, null, ",");
if (typeImports != null) {
udfImports.addAll(typeImports);
}
if (jobImports != null) {
udfImports.addAll(jobImports);
}
return udfImports;
}
/**
* Merging all additional jars first from user specified property
* and private.properties (in the jobtype property) for additionalJarProperty
* TODO kunkun-tang: A refactor is necessary here. Recommend using Java Optional to better handle
* parsing exceptions.
*/
protected List<String> getAdditionalJarsList() {
List<String> wholeAdditionalJarsList = new ArrayList<>();
List<String> jobAdditionalJars =
getJobProps().getStringList(PIG_ADDITIONAL_JARS, null, ",");
List<String> jobDefinedDefaultJars =
getJobProps().getStringList(DEFAULT_PIG_ADDITIONAL_JARS, null, ",");
List<String> systemDefinedDefaultJars =
getSysProps().getStringList(DEFAULT_PIG_ADDITIONAL_JARS, null, ",");
/*
if user defines the custom default pig Jar, we only incorporate the user
settings; otherwise, only when system configurations have it, we add the system
additional jar settings. We don't accept both at the same time.
*/
if (jobAdditionalJars != null) {
wholeAdditionalJarsList.addAll(jobAdditionalJars);
}
if (jobDefinedDefaultJars != null) {
wholeAdditionalJarsList.addAll(jobDefinedDefaultJars);
} else if (systemDefinedDefaultJars != null) {
wholeAdditionalJarsList.addAll(systemDefinedDefaultJars);
}
return wholeAdditionalJarsList;
}
protected String getHadoopUGI() {
return getJobProps().getString(HADOOP_UGI, null);
}
protected Map<String, String> getPigParams() {
return getJobProps().getMapByPrefix(PIG_PARAM_PREFIX);
}
protected List<String> getPigParamFiles() {
return getJobProps().getStringList(PIG_PARAM_FILES, null, ",");
}
private static String getSourcePathFromClass(Class<?> containedClass) {
File file =
new File(containedClass.getProtectionDomain().getCodeSource()
.getLocation().getPath());
if (!file.isDirectory() && file.getName().endsWith(".class")) {
String name = containedClass.getName();
StringTokenizer tokenizer = new StringTokenizer(name, ".");
while (tokenizer.hasMoreTokens()) {
tokenizer.nextElement();
file = file.getParentFile();
}
return file.getPath();
} else {
return containedClass.getProtectionDomain().getCodeSource().getLocation()
.getPath();
}
}
/**
* This cancel method, in addition to the default canceling behavior, also
* kills the MR jobs launched by Pig on Hadoop
*/
@Override
public void cancel() throws InterruptedException {
super.cancel();
info("Cancel called. Killing the Pig launched MR jobs on the cluster");
String azExecId = jobProps.getString(CommonJobProperties.EXEC_ID);
final String logFilePath =
String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId,
getId());
info("log file path is: " + logFilePath);
HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps,
tokenFile, getLog());
}
}
|
az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopPigJob.java
|
/*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.jobtype;
import static org.apache.hadoop.security.UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION;
import java.io.File;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.Logger;
import org.apache.pig.PigRunner;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.JavaProcessJob;
import azkaban.security.commons.HadoopSecurityManager;
import azkaban.utils.Props;
import azkaban.utils.StringUtils;
/*
* need lib:
* apache pig
* hadoop-core*.jar
* HadoopSecurePigWrapper
* HadoopSecurityManager(corresponding version with hadoop)
* abandon support for pig 0.8 and prior versions. don't see a use case here.
*/
public class HadoopPigJob extends JavaProcessJob {
public static final String PIG_SCRIPT = "pig.script";
public static final String UDF_IMPORT = "udf.import.list";
public static final String PIG_ADDITIONAL_JARS = "pig.additional.jars";
public static final String DEFAULT_PIG_ADDITIONAL_JARS =
"default.pig.additional.jars";
public static final String PIG_PARAM_PREFIX = "param.";
public static final String PIG_PARAM_FILES = "paramfile";
public static final String HADOOP_UGI = "hadoop.job.ugi";
public static final String DEBUG = "debug";
public static String HADOOP_SECURE_PIG_WRAPPER =
"azkaban.jobtype.HadoopSecurePigWrapper";
private String userToProxy = null;
private boolean shouldProxy = false;
private boolean obtainTokens = false;
File tokenFile = null;
private final boolean userPigJar;
private HadoopSecurityManager hadoopSecurityManager;
private File pigLogFile = null;
public HadoopPigJob(String jobid, Props sysProps, Props jobProps, Logger log)
throws IOException {
super(jobid, sysProps, jobProps, log);
HADOOP_SECURE_PIG_WRAPPER = HadoopSecurePigWrapper.class.getName();
getJobProps().put(CommonJobProperties.JOB_ID, jobid);
shouldProxy =
getSysProps().getBoolean(HadoopSecurityManager.ENABLE_PROXYING, false);
getJobProps().put(HadoopSecurityManager.ENABLE_PROXYING,
Boolean.toString(shouldProxy));
obtainTokens =
getSysProps().getBoolean(HadoopSecurityManager.OBTAIN_BINARY_TOKEN,
false);
userPigJar = getJobProps().getBoolean("use.user.pig.jar", false);
if (shouldProxy) {
getLog().info("Initiating hadoop security manager.");
try {
hadoopSecurityManager =
HadoopJobUtils.loadHadoopSecurityManager(getSysProps(), log);
} catch (RuntimeException e) {
throw new RuntimeException("Failed to get hadoop security manager!" + e);
}
}
}
@Override
public void run() throws Exception {
String[] tagKeys = new String[] { CommonJobProperties.EXEC_ID,
CommonJobProperties.FLOW_ID, CommonJobProperties.PROJECT_NAME };
getJobProps().put(HadoopConfigurationInjector.INJECT_PREFIX
+ HadoopJobUtils.MAPREDUCE_JOB_TAGS,
HadoopJobUtils.constructHadoopTags(getJobProps(), tagKeys));
HadoopConfigurationInjector.prepareResourcesToInject(getJobProps(),
getWorkingDirectory());
if (shouldProxy && obtainTokens) {
userToProxy = getJobProps().getString("user.to.proxy");
getLog().info("Need to proxy. Getting tokens.");
// get tokens in to a file, and put the location in props
Props props = new Props();
props.putAll(getJobProps());
props.putAll(getSysProps());
HadoopJobUtils.addAdditionalNamenodesToPropsFromMRJob(props, getLog());
tokenFile =
HadoopJobUtils
.getHadoopTokens(hadoopSecurityManager, props, getLog());
getJobProps().put("env." + HADOOP_TOKEN_FILE_LOCATION,
tokenFile.getAbsolutePath());
}
try {
super.run();
} catch (Throwable t) {
t.printStackTrace();
getLog().error("caught error running the job", t);
throw new Exception(t);
} finally {
if (tokenFile != null) {
HadoopJobUtils.cancelHadoopTokens(hadoopSecurityManager, userToProxy,
tokenFile, getLog());
if (tokenFile.exists()) {
tokenFile.delete();
}
}
}
}
@Override
protected String getJavaClass() {
return HADOOP_SECURE_PIG_WRAPPER;
}
@Override
protected String getJVMArguments() {
String args = super.getJVMArguments();
String typeGlobalJVMArgs =
getSysProps().getString("jobtype.global.jvm.args", null);
if (typeGlobalJVMArgs != null) {
args += " " + typeGlobalJVMArgs;
}
List<String> udfImport = getUDFImportList();
if (udfImport.size() > 0) {
args += " -Dudf.import.list=" + super.createArguments(udfImport, ":");
}
List<String> additionalJars = getAdditionalJarsList();
if (additionalJars.size() > 0) {
args +=
" -Dpig.additional.jars="
+ super.createArguments(additionalJars, ":");
}
String hadoopUGI = getHadoopUGI();
if (hadoopUGI != null) {
args += " -Dhadoop.job.ugi=" + hadoopUGI;
}
if (shouldProxy) {
info("Setting up secure proxy info for child process");
String secure;
secure =
" -D" + HadoopSecurityManager.USER_TO_PROXY + "="
+ getJobProps().getString(HadoopSecurityManager.USER_TO_PROXY);
String extraToken =
getSysProps().getString(HadoopSecurityManager.OBTAIN_BINARY_TOKEN,
"false");
if (extraToken != null) {
secure +=
" -D" + HadoopSecurityManager.OBTAIN_BINARY_TOKEN + "="
+ extraToken;
}
info("Secure settings = " + secure);
args += secure;
} else {
info("Not setting up secure proxy info for child process");
}
return args;
}
@Override
protected String getMainArguments() {
ArrayList<String> list = new ArrayList<String>();
Map<String, String> map = getPigParams();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
list.add("-param "
+ StringUtils.shellQuote(entry.getKey() + "=" + entry.getValue(),
StringUtils.SINGLE_QUOTE));
}
}
List<String> paramFiles = getPigParamFiles();
if (paramFiles != null) {
for (String paramFile : paramFiles) {
list.add("-param_file " + paramFile);
}
}
if (getDebug()) {
list.add("-debug");
}
try {
pigLogFile =
File.createTempFile("piglogfile", ".log", new File(
getWorkingDirectory()));
jobProps.put("env." + "PIG_LOG_FILE", pigLogFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
if (pigLogFile != null) {
list.add("-logfile " + pigLogFile.getAbsolutePath());
}
list.add(getScript());
return StringUtils.join((Collection<String>) list, " ");
}
@Override
protected List<String> getClassPaths() {
List<String> classPath = super.getClassPaths();
// To add az-core jar classpath
classPath.add(getSourcePathFromClass(Props.class));
// To add az-common jar classpath
classPath.add(getSourcePathFromClass(JavaProcessJob.class));
classPath.add(getSourcePathFromClass(HadoopSecurePigWrapper.class));
classPath.add(getSourcePathFromClass(HadoopSecurityManager.class));
classPath.add(HadoopConfigurationInjector.getPath(getJobProps(),
getWorkingDirectory()));
// assuming pig 0.8 and up
if (!userPigJar) {
classPath.add(getSourcePathFromClass(PigRunner.class));
}
// merging classpaths from plugin.properties
mergeClassPaths(classPath,
getJobProps().getStringList("jobtype.classpath", null, ","));
// merging classpaths from private.properties
mergeClassPaths(classPath,
getSysProps().getStringList("jobtype.classpath", null, ","));
List<String> typeGlobalClassPath =
getSysProps().getStringList("jobtype.global.classpath", null, ",");
if (typeGlobalClassPath != null) {
for (String jar : typeGlobalClassPath) {
if (!classPath.contains(jar)) {
classPath.add(jar);
}
}
}
return classPath;
}
private void mergeClassPaths(List<String> classPath,
List<String> typeClassPath) {
if (typeClassPath != null) {
// fill in this when load this jobtype
String pluginDir = getSysProps().get("plugin.dir");
for (String jar : typeClassPath) {
File jarFile = new File(jar);
if (!jarFile.isAbsolute()) {
jarFile = new File(pluginDir + File.separatorChar + jar);
}
if (!classPath.contains(jarFile.getAbsolutePath())) {
classPath.add(jarFile.getAbsolutePath());
}
}
}
}
protected boolean getDebug() {
return getJobProps().getBoolean(DEBUG, false);
}
protected String getScript() {
return getJobProps().getString(PIG_SCRIPT);
}
protected List<String> getUDFImportList() {
List<String> udfImports = new ArrayList<String>();
List<String> typeImports =
getSysProps().getStringList(UDF_IMPORT, null, ",");
List<String> jobImports =
getJobProps().getStringList(UDF_IMPORT, null, ",");
if (typeImports != null) {
udfImports.addAll(typeImports);
}
if (jobImports != null) {
udfImports.addAll(jobImports);
}
return udfImports;
}
protected List<String> getAdditionalJarsList() {
List<String> additionalJars = new ArrayList<String>();
mergeAdditionalJars(additionalJars, PIG_ADDITIONAL_JARS);
mergeAdditionalJars(additionalJars, DEFAULT_PIG_ADDITIONAL_JARS);
return additionalJars;
}
/**
* Merging all additional jars first from user specified/plugin.properties
* then private.properties for additionalJarProperty property
*/
private void mergeAdditionalJars(List<String> additionalJars,
String additionalJarProperty) {
List<String> jobJars =
getJobProps().getStringList(additionalJarProperty, null, ",");
List<String> typeJars =
getSysProps().getStringList(additionalJarProperty, null, ",");
if (jobJars != null) {
additionalJars.addAll(jobJars);
}
if (typeJars != null) {
additionalJars.addAll(typeJars);
}
}
protected String getHadoopUGI() {
return getJobProps().getString(HADOOP_UGI, null);
}
protected Map<String, String> getPigParams() {
return getJobProps().getMapByPrefix(PIG_PARAM_PREFIX);
}
protected List<String> getPigParamFiles() {
return getJobProps().getStringList(PIG_PARAM_FILES, null, ",");
}
private static String getSourcePathFromClass(Class<?> containedClass) {
File file =
new File(containedClass.getProtectionDomain().getCodeSource()
.getLocation().getPath());
if (!file.isDirectory() && file.getName().endsWith(".class")) {
String name = containedClass.getName();
StringTokenizer tokenizer = new StringTokenizer(name, ".");
while (tokenizer.hasMoreTokens()) {
tokenizer.nextElement();
file = file.getParentFile();
}
return file.getPath();
} else {
return containedClass.getProtectionDomain().getCodeSource().getLocation()
.getPath();
}
}
/**
* This cancel method, in addition to the default canceling behavior, also
* kills the MR jobs launched by Pig on Hadoop
*/
@Override
public void cancel() throws InterruptedException {
super.cancel();
info("Cancel called. Killing the Pig launched MR jobs on the cluster");
String azExecId = jobProps.getString(CommonJobProperties.EXEC_ID);
final String logFilePath =
String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId,
getId());
info("log file path is: " + logFilePath);
HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps,
tokenFile, getLog());
}
}
|
Only incorporate user pig additional jar setting or system's but not both (#2006)
We ran into a bug in the production environment. Users' jars cannot override default pig libraries. It was found that AZ always adds pig additional jar if pig job type defines it under plugin.properties. The fix is straightforward. If a user defines the property, we use it directly by not including system default settings.
|
az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopPigJob.java
|
Only incorporate user pig additional jar setting or system's but not both (#2006)
|
<ide><path>z-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopPigJob.java
<ide> return udfImports;
<ide> }
<ide>
<add> /**
<add> * Merging all additional jars first from user specified property
<add> * and private.properties (in the jobtype property) for additionalJarProperty
<add> * TODO kunkun-tang: A refactor is necessary here. Recommend using Java Optional to better handle
<add> * parsing exceptions.
<add> */
<ide> protected List<String> getAdditionalJarsList() {
<del> List<String> additionalJars = new ArrayList<String>();
<del> mergeAdditionalJars(additionalJars, PIG_ADDITIONAL_JARS);
<del> mergeAdditionalJars(additionalJars, DEFAULT_PIG_ADDITIONAL_JARS);
<del> return additionalJars;
<del> }
<del>
<del> /**
<del> * Merging all additional jars first from user specified/plugin.properties
<del> * then private.properties for additionalJarProperty property
<del> */
<del> private void mergeAdditionalJars(List<String> additionalJars,
<del> String additionalJarProperty) {
<del> List<String> jobJars =
<del> getJobProps().getStringList(additionalJarProperty, null, ",");
<del> List<String> typeJars =
<del> getSysProps().getStringList(additionalJarProperty, null, ",");
<del> if (jobJars != null) {
<del> additionalJars.addAll(jobJars);
<del> }
<del> if (typeJars != null) {
<del> additionalJars.addAll(typeJars);
<del> }
<add>
<add> List<String> wholeAdditionalJarsList = new ArrayList<>();
<add>
<add> List<String> jobAdditionalJars =
<add> getJobProps().getStringList(PIG_ADDITIONAL_JARS, null, ",");
<add>
<add> List<String> jobDefinedDefaultJars =
<add> getJobProps().getStringList(DEFAULT_PIG_ADDITIONAL_JARS, null, ",");
<add> List<String> systemDefinedDefaultJars =
<add> getSysProps().getStringList(DEFAULT_PIG_ADDITIONAL_JARS, null, ",");
<add>
<add> /*
<add> if user defines the custom default pig Jar, we only incorporate the user
<add> settings; otherwise, only when system configurations have it, we add the system
<add> additional jar settings. We don't accept both at the same time.
<add> */
<add> if (jobAdditionalJars != null) {
<add> wholeAdditionalJarsList.addAll(jobAdditionalJars);
<add> }
<add>
<add> if (jobDefinedDefaultJars != null) {
<add> wholeAdditionalJarsList.addAll(jobDefinedDefaultJars);
<add> } else if (systemDefinedDefaultJars != null) {
<add> wholeAdditionalJarsList.addAll(systemDefinedDefaultJars);
<add> }
<add> return wholeAdditionalJarsList;
<ide> }
<ide>
<ide> protected String getHadoopUGI() {
|
|
Java
|
lgpl-2.1
|
53383610cd2f6f0e46033f3358f761881ab9fc22
| 0 |
GrammaticalFramework/JPGF,GrammaticalFramework/JPGF,GrammaticalFramework/JPGF,GrammaticalFramework/JPGF
|
package org.grammaticalframework.linearizer;
import org.grammaticalframework.Trees.Absyn.*;
import org.grammaticalframework.reader.*;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Random;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Vector;
public class Generator {
private Random random;
private PGF pgf;
private HashMap<String,HashSet<String>> dirRules;
private HashMap<String,HashSet<String>> indirRules;
/** generates a random expression of a given category
* does not handle dependent categories or categories with implicit arguments
**/
public Generator(String file, PGF _pgf) throws Exception {
this.random = new Random();
this.pgf = _pgf;
this.dirRules = new HashMap<String,HashSet<String>>();
this.indirRules = new HashMap<String,HashSet<String>>();
AbsCat[] absCats = pgf.getAbstract().getAbsCats();
AbsFun[] absFuns = pgf.getAbstract().getAbsFuns();
HashSet<String> dirFuns = new HashSet<String>();
HashSet<String> indirFuns = new HashSet<String>();
for(int i=0;i<absCats.length; i++) {
dirFuns = new HashSet<String>();
indirFuns = new HashSet<String>();
String[] strs = absCats[i].getFunctions();
for(int j=0; j<strs.length; j++)
for(int k=0; k<absFuns.length; k++)
if(strs[j].equals(absFuns[k].getName())) {
if(absFuns[k].getType().getHypos().length == 0)
dirFuns.add(strs[j]);
else indirFuns.add(strs[j]);
break;
}
dirRules.put(absCats[i].name(),dirFuns);
indirRules.put(absCats[i].name(), indirFuns);
}
}
/** generates a category with a random direct rule
* suitable for simple expressions
**/
public Tree getDirect(String type, HashSet<String> dirFuns) {
Iterator<String> it = dirFuns.iterator();
Vector<String> vs = new Vector<String>();
while(it.hasNext())
vs.add(it.next());
int rand = random.nextInt(vs.size());
return new Function(vs.elementAt(rand));
}
/** generates a category with a random indirect rule
* creates more complex expressions
**/
public Tree getIndirect(String type, HashSet<String> indirFuns) throws Exception
{Iterator<String> it = indirFuns.iterator();
Vector<String> vs = new Vector<String>();
while(it.hasNext())
vs.add(it.next());
int rand = random.nextInt(vs.size());
String funcName = vs.elementAt(rand);
AbsFun[] absFuns = pgf.getAbstract().getAbsFuns();
for(int i=0; i<absFuns.length;i++)
if(absFuns[i].getName().equals(funcName))
{Hypo[] hypos = absFuns[i].getType().getHypos();
String[] tempCats = new String[hypos.length];
Tree[] exps = new Tree[hypos.length];
for(int k=0; k<hypos.length;k++)
{tempCats[k]=hypos[k].getType().getName();
exps[k]=gen(tempCats[k]);
if(exps[k] == null) return null;}
Tree rez = new Function(funcName);
for(int j=0;j<exps.length;j++)
rez = new Application (rez, exps[j]);
return rez;}
return null;
}
/** generates a random expression of a given category
* the empirical probability of using direct rules is 60%
* this decreases the probability of having infinite trees for infinite grammars
**/
public Tree gen(String type) throws Exception
{if(type.equals("Integer")) return new Literal(new IntLiteral(generateInt()));
else if(type.equals("Float")) return new Literal(new FloatLiteral(generateFloat()));
else if(type.equals("String")) return new Literal(new StringLiteral(generateString()));
int depth = random.nextInt(5); //60% constants, 40% functions
HashSet<String> dirFuns = dirRules.get(type);
HashSet<String> indirFuns = indirRules.get(type);
boolean isEmptyDir = dirFuns.isEmpty();
boolean isEmptyIndir = indirFuns.isEmpty();
if(isEmptyDir && isEmptyIndir) throw new Exception ("Cannot generate any expression of type "+type);
if(isEmptyDir) return getIndirect(type,indirFuns);
if(isEmptyIndir) return getDirect(type,dirFuns);
if(depth <= 2 ) return getDirect(type,dirFuns);
return getIndirect(type,indirFuns);
}
/** generates a number of expressions of a given category
* the expressions are independent
* the probability of having simple expressions is higher
**/
public Vector<Tree> generateMany(String type, int count) throws Exception
{int contor = 0;
Vector<Tree> rez = new Vector<Tree>();
if(contor >= count) return rez;
HashSet<String> dirFuns = dirRules.get(type);
HashSet<String> indirFuns = indirRules.get(type);
Iterator<String> itDir = dirFuns.iterator();
while(itDir.hasNext())
{Tree interm = getDirect(type,dirFuns);
if(interm != null)
{contor ++;
rez.add(interm);
if(contor == count) return rez;}}
itDir = indirFuns.iterator();
while(itDir.hasNext())
{Tree interm = getIndirect(type,indirFuns);
if(interm != null)
{contor ++;
rez.add(interm);
if(contor == count) return rez;}}
return rez;
}
/** generates a random string
**/
public String generateString()
{String[] ss = { "x", "y", "foo", "bar" };
return ss[random.nextInt(ss.length)];}
/** generates a random integer
**/
public int generateInt()
{return random.nextInt(100000);}
/** generates a random float
**/
public double generateFloat()
{return random.nextDouble();}
/*
public static void main(String[] args)
{ try {
Generator gg = new Generator("Phrasebook.pgf");
Vector<Expr> rez = gg.generateMany("Greeting",9);
if(rez != null)
{ System.out.println("Rezultatul este "+rez.toString());
System.out.println("Dimensiunea este "+rez.size());}
else System.out.println("Rezultatul este nul");
}
catch(Exception e) {System.out.println("No such file"+e.toString());}
}
*/
}
|
src/main/java/org/grammaticalframework/linearizer/Generator.java
|
package org.grammaticalframework.linearizer;
import org.grammaticalframework.Trees.Absyn.*;
import org.grammaticalframework.reader.*;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Random;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Vector;
public class Generator {
private Random random;
private PGF pgf;
private HashMap<String,HashSet<String>> dirRules;
private HashMap<String,HashSet<String>> indirRules;
/** generates a random expression of a given category
* does not handle dependent categories or categories with implicit arguments
**/
public Generator(String file, PGF _pgf) throws Exception {
this.random = new Random();
this.pgf = _pgf;
this.dirRules = new HashMap<String,HashSet<String>>();
this.indirRules = new HashMap<String,HashSet<String>>();
AbsCat[] absCats = pgf.getAbstract().getAbsCats();
AbsFun[] absFuns = pgf.getAbstract().getAbsFuns();
HashSet<String> dirFuns = new HashSet<String>();
HashSet<String> indirFuns = new HashSet<String>();
for(int i=0;i<absCats.length; i++) {
dirFuns = new HashSet<String>();
indirFuns = new HashSet<String>();
String[] strs = absCats[i].getFunctions();
for(int j=0; j<strs.length; j++)
for(int k=0; k<absFuns.length; k++)
if(strs[j].equals(absFuns[k].getName())) {
if(absFuns[k].getType().getHypos().length == 0)
dirFuns.add(strs[j]);
else indirFuns.add(strs[j]);
break;
}
dirRules.put(absCats[i].name(),dirFuns);
indirRules.put(absCats[i].name(), indirFuns);
}
}
/** generates a category with a random direct rule
* suitable for simple expressions
**/
public Tree getDirect(String type, HashSet<String> dirFuns)
{Iterator<String> it = dirFuns.iterator();
Vector<String> vs = new Vector<String>();
while(it.hasNext())
vs.add(it.next());
int rand = random.nextInt(vs.size());
return new Function(vs.elementAt(rand));
}
/** generates a category with a random indirect rule
* creates more complex expressions
**/
public Tree getIndirect(String type, HashSet<String> indirFuns) throws Exception
{Iterator<String> it = indirFuns.iterator();
Vector<String> vs = new Vector<String>();
while(it.hasNext())
vs.add(it.next());
int rand = random.nextInt(vs.size());
String funcName = vs.elementAt(rand);
AbsFun[] absFuns = pgf.getAbstract().getAbsFuns();
for(int i=0; i<absFuns.length;i++)
if(absFuns[i].getName().equals(funcName))
{Hypo[] hypos = absFuns[i].getType().getHypos();
String[] tempCats = new String[hypos.length];
Tree[] exps = new Tree[hypos.length];
for(int k=0; k<hypos.length;k++)
{tempCats[k]=hypos[k].getType().getName();
exps[k]=gen(tempCats[k]);
if(exps[k] == null) return null;}
Tree rez = new Function(funcName);
for(int j=0;j<exps.length;j++)
rez = new Application (rez, exps[j]);
return rez;}
return null;
}
/** generates a random expression of a given category
* the empirical probability of using direct rules is 60%
* this decreases the probability of having infinite trees for infinite grammars
**/
public Tree gen(String type) throws Exception
{if(type.equals("Integer")) return new Literal(new IntLiteral(generateInt()));
else if(type.equals("Float")) return new Literal(new FloatLiteral(generateFloat()));
else if(type.equals("String")) return new Literal(new StringLiteral(generateString()));
int depth = random.nextInt(5); //60% constants, 40% functions
HashSet<String> dirFuns = dirRules.get(type);
HashSet<String> indirFuns = indirRules.get(type);
boolean isEmptyDir = dirFuns.isEmpty();
boolean isEmptyIndir = indirFuns.isEmpty();
if(isEmptyDir && isEmptyIndir) throw new Exception ("Cannot generate any expression of type "+type);
if(isEmptyDir) return getIndirect(type,indirFuns);
if(isEmptyIndir) return getDirect(type,dirFuns);
if(depth <= 2 ) return getDirect(type,dirFuns);
return getIndirect(type,indirFuns);
}
/** generates a number of expressions of a given category
* the expressions are independent
* the probability of having simple expressions is higher
**/
public Vector<Tree> generateMany(String type, int count) throws Exception
{int contor = 0;
Vector<Tree> rez = new Vector<Tree>();
if(contor >= count) return rez;
HashSet<String> dirFuns = dirRules.get(type);
HashSet<String> indirFuns = indirRules.get(type);
Iterator<String> itDir = dirFuns.iterator();
while(itDir.hasNext())
{Tree interm = getDirect(type,dirFuns);
if(interm != null)
{contor ++;
rez.add(interm);
if(contor == count) return rez;}}
itDir = indirFuns.iterator();
while(itDir.hasNext())
{Tree interm = getIndirect(type,indirFuns);
if(interm != null)
{contor ++;
rez.add(interm);
if(contor == count) return rez;}}
return rez;
}
/** generates a random string
**/
public String generateString()
{String[] ss = { "x", "y", "foo", "bar" };
return ss[random.nextInt(ss.length)];}
/** generates a random integer
**/
public int generateInt()
{return random.nextInt(100000);}
/** generates a random float
**/
public double generateFloat()
{return random.nextDouble();}
/*
public static void main(String[] args)
{ try {
Generator gg = new Generator("Phrasebook.pgf");
Vector<Expr> rez = gg.generateMany("Greeting",9);
if(rez != null)
{ System.out.println("Rezultatul este "+rez.toString());
System.out.println("Dimensiunea este "+rez.size());}
else System.out.println("Rezultatul este nul");
}
catch(Exception e) {System.out.println("No such file"+e.toString());}
}
*/
}
|
[Style] Layout
Ignore-this: 5501e9747c441e16bb835f4f7d5ae5d0
darcs-hash:20100621125749-e7b0d-173a878f712247446470f752c8c2c8f01f18a655.gz
|
src/main/java/org/grammaticalframework/linearizer/Generator.java
|
[Style] Layout
|
<ide><path>rc/main/java/org/grammaticalframework/linearizer/Generator.java
<ide> }
<ide>
<ide> /** generates a category with a random direct rule
<del> * suitable for simple expressions
<del>**/
<del>public Tree getDirect(String type, HashSet<String> dirFuns)
<del>{Iterator<String> it = dirFuns.iterator();
<del>Vector<String> vs = new Vector<String>();
<del>while(it.hasNext())
<del> vs.add(it.next());
<del>int rand = random.nextInt(vs.size());
<del>return new Function(vs.elementAt(rand));
<del>}
<add> * suitable for simple expressions
<add> **/
<add> public Tree getDirect(String type, HashSet<String> dirFuns) {
<add> Iterator<String> it = dirFuns.iterator();
<add> Vector<String> vs = new Vector<String>();
<add> while(it.hasNext())
<add> vs.add(it.next());
<add> int rand = random.nextInt(vs.size());
<add> return new Function(vs.elementAt(rand));
<add> }
<ide>
<ide>
<ide> /** generates a category with a random indirect rule
|
|
JavaScript
|
bsd-3-clause
|
67f7197d74bcfda1c9156c3be5ce6a74c8ea720d
| 0 |
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as SDK from '../sdk/sdk.js';
export class InputModel extends SDK.SDKModel.SDKModel {
/**
* @param {!SDK.SDKModel.Target} target
*/
constructor(target) {
super(target);
this._inputAgent = target.inputAgent();
/** @type {?number} */
this._activeTouchOffsetTop = null;
this._activeTouchParams = null;
}
/**
* @param {!Event} event
*/
emitKeyEvent(event) {
/** @type {!Protocol.Input.DispatchKeyEventRequestType} */
let type;
switch (event.type) {
case 'keydown':
type = Protocol.Input.DispatchKeyEventRequestType.KeyDown;
break;
case 'keyup':
type = Protocol.Input.DispatchKeyEventRequestType.KeyUp;
break;
case 'keypress':
type = Protocol.Input.DispatchKeyEventRequestType.Char;
break;
default:
return;
}
const keyboardEvent = /** @type {!KeyboardEvent} */ (event);
const text = event.type === 'keypress' ? String.fromCharCode(keyboardEvent.charCode) : undefined;
this._inputAgent.invoke_dispatchKeyEvent({
type: type,
modifiers: this._modifiersForEvent(keyboardEvent),
text: text,
unmodifiedText: text ? text.toLowerCase() : undefined,
// TODO: keyIdentifier is non-standard deprecated event property https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyIdentifier.
keyIdentifier: /** @type {*} */ (keyboardEvent).keyIdentifier,
code: keyboardEvent.code,
key: keyboardEvent.key,
windowsVirtualKeyCode: keyboardEvent.keyCode,
nativeVirtualKeyCode: keyboardEvent.keyCode,
autoRepeat: false,
isKeypad: false,
isSystemKey: false
});
}
/**
* @param {!Event} event
* @param {number} offsetTop
* @param {number} zoom
*/
emitTouchFromMouseEvent(event, offsetTop, zoom) {
const buttons = /** @type {!Array<!Protocol.Input.MouseButton>} */ (['none', 'left', 'middle', 'right']);
const types = /** @type {*} */
({
mousedown: 'mousePressed',
mouseup: 'mouseReleased',
mousemove: 'mouseMoved',
mousewheel: 'mouseWheel',
});
const eventType = /** @type {string} */ (event.type);
if (!(eventType in types)) {
return;
}
const mouseEvent = /** @type {!MouseEvent} */ (event);
if (!(mouseEvent.which in buttons)) {
return;
}
if (eventType !== 'mousewheel' && buttons[mouseEvent.which] === 'none') {
return;
}
if (eventType === 'mousedown' || this._activeTouchOffsetTop === null) {
this._activeTouchOffsetTop = offsetTop;
}
const x = Math.round(mouseEvent.offsetX / zoom);
let y = Math.round(mouseEvent.offsetY / zoom);
y = Math.round(y - this._activeTouchOffsetTop);
/** @type {!Protocol.Input.EmulateTouchFromMouseEventRequest} */
const params = {
type: types[eventType],
x: x,
y: y,
modifiers: 0,
button: buttons[mouseEvent.which],
clickCount: 0,
};
if (event.type === 'mousewheel') {
const wheelEvent = /** @type {!WheelEvent} */ (mouseEvent);
params.deltaX = wheelEvent.deltaX / zoom;
params.deltaY = -wheelEvent.deltaY / zoom;
} else {
this._activeTouchParams = params;
}
if (event.type === 'mouseup') {
this._activeTouchOffsetTop = null;
}
this._inputAgent.invoke_emulateTouchFromMouseEvent(params);
}
cancelTouch() {
if (this._activeTouchParams !== null) {
const params = this._activeTouchParams;
this._activeTouchParams = null;
params.type = /** @type {!Protocol.Input.EmulateTouchFromMouseEventRequestType} */ ('mouseReleased');
this._inputAgent.invoke_emulateTouchFromMouseEvent(params);
}
}
/**
* @param {!KeyboardEvent} event
* @return {number}
*/
_modifiersForEvent(event) {
return (event.altKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.metaKey ? 4 : 0) | (event.shiftKey ? 8 : 0);
}
}
SDK.SDKModel.SDKModel.register(InputModel, SDK.SDKModel.Capability.Input, false);
|
front_end/screencast/InputModel.js
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as SDK from '../sdk/sdk.js';
export class InputModel extends SDK.SDKModel.SDKModel {
/**
* @param {!SDK.SDKModel.Target} target
*/
constructor(target) {
super(target);
this._inputAgent = target.inputAgent();
/** @type {?number} */
this._activeTouchOffsetTop = null;
this._activeTouchParams = null;
}
/**
* @param {!Event} event
*/
emitKeyEvent(event) {
/** @type {!Protocol.Input.DispatchKeyEventRequestType} */
let type;
switch (event.type) {
case 'keydown':
type = Protocol.Input.DispatchKeyEventRequestType.KeyDown;
break;
case 'keyup':
type = Protocol.Input.DispatchKeyEventRequestType.KeyUp;
break;
case 'keypress':
type = Protocol.Input.DispatchKeyEventRequestType.Char;
break;
default:
return;
}
const keyboardEvent = /** @type {!KeyboardEvent} */ (event);
const text = event.type === 'keypress' ? String.fromCharCode(keyboardEvent.charCode) : undefined;
this._inputAgent.invoke_dispatchKeyEvent({
type: type,
modifiers: this._modifiersForEvent(keyboardEvent),
text: text,
unmodifiedText: text ? text.toLowerCase() : undefined,
// TODO: keyIdentifier is non-standard deprecated event property https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyIdentifier.
keyIdentifier: /** @type {*} */ (keyboardEvent).keyIdentifier,
code: keyboardEvent.code,
key: keyboardEvent.key,
windowsVirtualKeyCode: keyboardEvent.keyCode,
nativeVirtualKeyCode: keyboardEvent.keyCode,
autoRepeat: false,
isKeypad: false,
isSystemKey: false
});
}
/**
* @param {!Event} event
* @param {number} offsetTop
* @param {number} zoom
*/
emitTouchFromMouseEvent(event, offsetTop, zoom) {
const buttons = /** @type {!Array<!Protocol.Input.MouseButton>} */ (['none', 'left', 'middle', 'right']);
const types = /** @type {*} */
({
mousedown: 'mousePressed',
mouseup: 'mouseReleased',
mousemove: 'mouseMoved',
mousewheel: 'mouseWheel',
});
const eventType = /** @type {string} */ (event.type);
if (!(eventType in types)) {
return;
}
const mouseEvent = /** @type {!MouseEvent} */ (event);
if (!(mouseEvent.which in buttons)) {
return;
}
if (eventType !== 'mousewheel' && buttons[mouseEvent.which] === 'none') {
return;
}
if (eventType === 'mousedown' || this._activeTouchOffsetTop === null) {
this._activeTouchOffsetTop = offsetTop;
}
const x = Math.round(mouseEvent.offsetX / zoom);
let y = Math.round(mouseEvent.offsetY / zoom);
y = Math.round(y - this._activeTouchOffsetTop);
/** @type {!Protocol.Input.EmulateTouchFromMouseEventRequest} */
const params = {
type: types[eventType],
x: x,
y: y,
modifiers: 0,
button: buttons[mouseEvent.which],
clickCount: 0,
};
if (event.type === 'mousewheel') {
// TODO(crbug.com/1145518) Remove usage of MouseWheelEvent.
const mouseWheelEvent = /** @type {*} */ (mouseEvent);
params.deltaX = mouseWheelEvent.wheelDeltaX / zoom;
params.deltaY = mouseWheelEvent.wheelDeltaY / zoom;
} else {
this._activeTouchParams = params;
}
if (event.type === 'mouseup') {
this._activeTouchOffsetTop = null;
}
this._inputAgent.invoke_emulateTouchFromMouseEvent(params);
}
cancelTouch() {
if (this._activeTouchParams !== null) {
const params = this._activeTouchParams;
this._activeTouchParams = null;
params.type = /** @type {!Protocol.Input.EmulateTouchFromMouseEventRequestType} */ ('mouseReleased');
this._inputAgent.invoke_emulateTouchFromMouseEvent(params);
}
}
/**
* @param {!KeyboardEvent} event
* @return {number}
*/
_modifiersForEvent(event) {
return (event.altKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.metaKey ? 4 : 0) | (event.shiftKey ? 8 : 0);
}
}
SDK.SDKModel.SDKModel.register(InputModel, SDK.SDKModel.Capability.Input, false);
|
Changed to WheelEvent instead of non-standard MouseWheelEvent in screencast
Bug:1145518
Change-Id: I467a5535a852bb6e0223eb4c478daf9e321ebcba
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2550766
Commit-Queue: Paul Lewis <[email protected]>
Reviewed-by: Paul Lewis <[email protected]>
|
front_end/screencast/InputModel.js
|
Changed to WheelEvent instead of non-standard MouseWheelEvent in screencast
|
<ide><path>ront_end/screencast/InputModel.js
<ide> clickCount: 0,
<ide> };
<ide> if (event.type === 'mousewheel') {
<del> // TODO(crbug.com/1145518) Remove usage of MouseWheelEvent.
<del> const mouseWheelEvent = /** @type {*} */ (mouseEvent);
<del> params.deltaX = mouseWheelEvent.wheelDeltaX / zoom;
<del> params.deltaY = mouseWheelEvent.wheelDeltaY / zoom;
<add> const wheelEvent = /** @type {!WheelEvent} */ (mouseEvent);
<add> params.deltaX = wheelEvent.deltaX / zoom;
<add> params.deltaY = -wheelEvent.deltaY / zoom;
<ide> } else {
<ide> this._activeTouchParams = params;
<ide> }
|
|
JavaScript
|
agpl-3.0
|
bf65515e23ff5f5901fbc307696db0cbc2713ffa
| 0 |
PeteBa/OpenSprinkler-App,PeteBa/OpenSprinkler-App,OpenSprinkler/OpenSprinkler-App,OpenSprinkler/OpenSprinkler-App,OpenSprinkler/OpenSprinkler-App,PeteBa/OpenSprinkler-App
|
var isIEMobile = /IEMobile/.test(navigator.userAgent),
isAndroid = /Android|\bSilk\b/.test(navigator.userAgent),
isiOS = /iP(ad|hone|od)/.test(navigator.userAgent);
//Fix CSS for IE Mobile (Windows Phone 8)
if (isIEMobile) {
var a=document.createElement("style");
a.innerHTML="ul{list-style: none !important;}@media(max-width:940px){.wicon{margin:-10px -10px -15px -15px !important}#forecast .wicon{position:relative;left:37.5px;margin:0 auto !important}}";
document.head.appendChild(a);
}
//Attach FastClick handler
$(window).one("load", function(){
FastClick.attach(document.body);
});
$(document)
.ready(function() {
//Update the language on the page using the browser's locale
update_lang();
//Use the user's local time for preview
var now = new Date();
$("#log_start").val(new Date(now.getTime() - 604800000).toISOString().slice(0,10));
$("#preview_date, #log_end").val(now.toISOString().slice(0,10));
//Update site based on selector
$("#site-selector").on("change",function(){
update_site($(this).val());
});
//Bind start page buttons
$("#auto-scan").find("button").on("click",start_scan);
//Bind open panel button
$("#sprinklers").find("div[data-role='header'] > .ui-btn-left").off("click").on("click",function(){
open_panel();
return false;
});
//Bind stop all stations button
$("#stop-all").on("click",function(){
areYouSure(_("Are you sure you want to stop all stations?"), "", function() {
$.mobile.loading("show");
send_to_os("/cv?pw=&rsn=1").done(function(){
$.mobile.loading("hide");
$.when(
update_controller_settings(),
update_controller_status()
).then(check_status);
showerror(_("All stations have been stopped"));
});
});
});
// Prevent caching of AJAX requests on Android and Windows Phone devices
if (isAndroid) {
$(this).ajaxStart(function(){
try {
navigator.app.clearCache();
} catch (err) {}
});
} else if (isIEMobile) {
$.ajaxSetup({
"cache": false
});
}
//Use system browser for links on iOS and Windows Phone
if (isiOS || isIEMobile) {
$(".iab").attr("target","_system");
}
})
.ajaxError(function(x,t,m) {
if (t.status==401 && /https?:\/\/.*?\/(?:cv|sn|cs|cr|cp|dp|co|cl)/.exec(m.url)) {
showerror(_("Check device password and try again."));
return;
} else if (t.status===0) {
if (/https?:\/\/.*?\/(?:cv|sn|cs|cr|cp|dp|co|cl)/.exec(m.url)) {
// Ajax fails typically because the password is wrong
showerror(_("Check device password and try again."));
return;
}
}
if (m.url.search("yahooapis.com") !== -1 || m.url.search("api.wunderground.com") !== -1) {
hide_weather();
return;
}
if (t.statusText==="timeout") {
showerror(_("Connection timed-out. Please try again."));
return;
}
})
.one("deviceready", function() {
try {
//Change the status bar to match the headers
StatusBar.overlaysWebView(false);
StatusBar.styleLightContent();
StatusBar.backgroundColorByHexString("#1C1C1C");
} catch (err) {}
// Hide the splash screen
setTimeout(function(){
navigator.splashscreen.hide();
},500);
// Check if device is on a local network
checkAutoScan();
})
.one("mobileinit", function(){
//After jQuery mobile is loaded set intial configuration
$.mobile.defaultPageTransition = 'fade';
$.mobile.hoverDelay = 0;
})
.one("pagebeforechange", function(event) {
// Let the framework know we're going to handle the load
event.preventDefault();
//On initial load check if a valid site exists for auto connect
check_configured(true);
$.mobile.document.on("pagebeforechange",function(e,data){
var page = data.toPage,
hash, showBack;
if (typeof data.toPage !== "string") return;
hash = $.mobile.path.parseUrl(page).hash;
if (data.options.role !== "popup" && !$(".ui-popup-active").length) $.mobile.silentScroll(0);
if (hash == "#programs") {
get_programs(data.options.programToExpand);
} else if (hash == "#addprogram") {
add_program();
} else if (hash =="#status") {
$(hash).find("div[data-role='header'] > .ui-btn-right").on("click",refresh_status);
get_status();
} else if (hash == "#manual") {
get_manual();
} else if (hash == "#runonce") {
get_runonce();
} else if (hash == "#os-settings") {
show_settings();
} else if (hash == "#start") {
checkAutoScan();
} else if (hash == "#os-stations") {
show_stations();
} else if (hash == "#site-control") {
showBack = (data.options.showBack === false) ? false : true;
$("#site-control").find(".ui-toolbar-back-btn").toggle(showBack);
show_sites();
} else if (hash == "#weather_settings") {
show_weather_settings();
} else if (hash == "#addnew") {
show_addnew();
return false;
} else if (hash == "#raindelay") {
$(hash).find("form").on("submit",raindelay);
} else if (hash == "#site-select") {
show_site_select();
return false;
} else if (hash == "#sprinklers") {
if (!data.options.firstLoad) {
//Reset status bar to loading while an update is done
showLoading("#footer-running");
setTimeout(function(){
refresh_status();
},800);
} else {
check_status();
}
} else if (hash == "#settings") {
$.each(["en","mm"],function(a,id){
var $id = $("#"+id);
$id.prop("checked",window.controller.settings[id]);
if ($id.hasClass("ui-flipswitch-input")) $id.flipswitch("refresh");
$id.on("change",flipSwitched);
});
var settings = $(hash);
settings.find(".clear_logs > a").off("click").on("click",function(){
areYouSure(_("Are you sure you want to clear all your log data?"), "", function() {
$.mobile.loading("show");
send_to_os("/cl?pw=").done(function(){
$.mobile.loading("hide");
showerror(_("Logs have been cleared"));
});
});
return false;
});
settings.find(".reboot-os").off("click").on("click",function(){
areYouSure(_("Are you sure you want to reboot OpenSprinkler?"), "", function() {
$.mobile.loading("show");
send_to_os("/cv?pw=&rbt=1").done(function(){
$.mobile.loading("hide");
showerror(_("OpenSprinkler is rebooting now"));
});
});
return false;
});
settings.find(".clear-config").off("click").on("click",function(){
areYouSure(_("Are you sure you want to delete all settings and return to the default settings?"), "", function() {
storage.remove(["sites","current_site","lang","provider","wapikey","runonce"],function(){
update_lang();
changePage("#start");
});
});
return false;
});
settings.find(".show-providers").off("click").on("click",function(){
$("#providers").popup("destroy").remove();
storage.get(["provider","wapikey"],function(data){
data.provider = data.provider || "yahoo";
var popup = $(
'<div data-role="popup" id="providers" data-theme="a" data-dismissible="false" data-overlay-theme="b">'+
'<a data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a>'+
'<div class="ui-content">'+
'<form>'+
'<label for="weather_provider">'+_("Weather Provider")+
'<select data-mini="true" id="weather_provider">'+
'<option value="yahoo">'+_("Yahoo!")+'</option>'+
'<option '+((data.provider == "wunderground") ? 'selected ' : '')+'value="wunderground">'+_("Wunderground")+'</option>'+
'</select>'+
'</label>'+
'<label for="wapikey">'+_("Wunderground API Key")+'<input data-mini="true" type="text" id="wapikey" value="'+((data.wapikey) ? data.wapikey : '')+'" /></label>'+
'<input type="submit" value="'+_("Submit")+'" />'+
'</form>'+
'</div>'+
'</div>'
);
if (data.provider == "yahoo") popup.find("#wapikey").closest("label").hide();
popup.find("form").on("submit",function(e){
e.preventDefault();
var wapikey = $("#wapikey").val(),
provider = $("#weather_provider").val();
if (provider == "wunderground" && wapikey === "") {
showerror(_("An API key must be provided for Weather Underground"));
return;
}
storage.set({
"wapikey": wapikey,
"provider": provider
});
update_weather();
$("#providers").popup("close");
return false;
});
//Handle provider select change on weather settings
popup.on("change","#weather_provider",function(){
var val = $(this).val();
if (val === "wunderground") {
$("#wapikey").closest("label").show();
} else {
$("#wapikey").closest("label").hide();
}
popup.popup("reposition",{
"positionTo": "window"
});
});
popup.one("popupafterclose",function(){
document.activeElement.blur();
this.remove();
}).popup().enhanceWithin().popup("open");
return false;
});
});
$("#localization").find("a").off("click").on("click",function(){
var link = $(this),
lang = link.data("lang-code");
update_lang(lang);
});
settings.one("pagehide",function(){
$("#en,#mm").off("change");
settings.find(".clear_logs > a,.reboot-os,.clear-config,.show-providers").off("click");
$("#localization").find("a").off("click");
});
}
});
})
.on("resume",function(){
var page = $(".ui-page-active").attr("id"),
func = function(){};
// Check if device is still on a local network
checkAutoScan();
// If we don't have a current device IP set, there is nothing else to update
if (window.curr_ip === undefined) return;
// Indicate the weather and device status are being updated
showLoading("#weather,#footer-running");
if (page == "status") {
// Update the status page
func = get_status;
} else if (page == "sprinklers") {
// Update device status bar on main page
func = check_status;
}
update_controller(function(){
func();
update_weather();
},network_fail);
})
.on("pause",function(){
//Remove any status timers that may be running
removeTimers();
})
.on("pageshow",function(e){
var newpage = "#"+e.target.id,
$newpage = $(newpage);
fixInputClick($newpage);
// Render graph after the page is shown otherwise graphing function will fail
if (newpage == "#preview") {
$("#preview_date").on("change",get_preview);
$newpage.find(".preview-minus").on("click",function(){
changeday(-1);
});
$newpage.find(".preview-plus").on("click",function(){
changeday(1);
});
get_preview();
//Update the preview page on date change
$newpage.one("pagehide",function(){
$("#timeline").empty();
$("#preview_date").off("change");
$.mobile.window.off("resize");
$(".preview-minus,.preview-plus").off("click");
$("#timeline-navigation").find("a").off("click");
});
} else if (newpage == "#logs") {
get_logs();
} else if (newpage == "#sprinklers") {
$newpage.off("swiperight").on("swiperight", function() {
if ($(".ui-page-active").jqmData("panel") !== "open" && !$(".ui-page-active .ui-popup-active").length) {
open_panel();
}
});
}
})
.on("pagehide","#start",removeTimers)
.on("popupbeforeposition","#localization",check_curr_lang);
//Set AJAX timeout
$.ajaxSetup({
timeout: 6000
});
var switching = false;
function flipSwitched() {
if (switching) return;
//Find out what the switch was changed to
var flip = $(this),
id = flip.attr("id"),
changedTo = flip.is(":checked"),
method = (id == "mmm") ? "mm" : id,
defer;
if (changedTo) {
defer = send_to_os("/cv?pw=&"+method+"=1");
} else {
defer = send_to_os("/cv?pw=&"+method+"=0");
}
$.when(defer).then(function(){
update_controller_settings();
if (id == "mm" || id == "mmm") $("#manual a.green").removeClass("green");
},
function(){
switching = true;
setTimeout(function(){
switching = false;
},200);
flip.prop("checked",!changedTo).flipswitch("refresh");
});
}
// Wrapper function to communicate with OpenSprinkler
function send_to_os(dest,type) {
dest = dest.replace("pw=","pw="+window.curr_pw);
type = type || "text";
var obj = {
url: window.curr_prefix+window.curr_ip+dest,
type: "GET",
dataType: type
};
if (window.curr_auth) {
$.extend(obj,{
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(window.curr_auth_user + ":" + window.curr_auth_pw)); }
});
}
if (typeof window.curr_session != "undefined") {
$.extend(obj,{
beforeSend: function(xhr) { xhr.setRequestHeader("webpy_session_id", window.curr_session); }
});
}
return $.ajax(obj);
}
function network_fail(){
change_status(0,0,"red","<p id='running-text' class='center'>"+_("Network Error")+"</p>",function(){
showLoading("#weather,#footer-running");
refresh_status();
update_weather();
});
hide_weather();
}
// Gather new controller information and load home page
function newload() {
$.mobile.loading("show");
//Create object which will store device data
window.controller = {};
update_controller(
function(){
var log_button = $("#log_button"),
clear_logs = $(".clear_logs"),
pi = isOSPi();
$.mobile.loading("hide");
check_status();
update_weather();
// Hide log viewer button on home page if not supported
if ((typeof window.controller.options.fwv === "number" && window.controller.options.fwv < 206) || (typeof window.controller.options.fwv === "string" && window.controller.options.fwv.match(/1\.9\.0/)) === -1) {
log_button.hide();
} else {
log_button.css("display","");
}
// Hide clear logs button when using Arduino device (feature not enabled yet)
if (!pi) {
clear_logs.hide();
} else {
clear_logs.css("display","");
}
// Update export to email button in side panel
objToEmail(".email_config",window.controller);
// Check if automatic rain delay plugin is enabled on OSPi devices
checkWeatherPlugin();
// Transition to home page after succesful load
if ($.mobile.pageContainer.pagecontainer("getActivePage").attr("id") != "sprinklers") {
changePage("#sprinklers",{
"transition":"none",
"firstLoad": true
});
}
},
function(){
$.mobile.loading("hide");
if (Object.keys(getsites()).length) {
changePage("#site-control",{
'showBack': false
});
} else {
changePage("#start");
}
}
);
}
// Update controller information
function update_controller(callback,fail) {
callback = callback || function(){};
fail = fail || function(){};
$.when(
update_controller_programs(),
update_controller_stations(),
update_controller_options(),
update_controller_status(),
update_controller_settings()
).then(callback,fail);
}
function update_controller_programs(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/gp?d=0").done(function(programs){
var vars = programs.match(/(nprogs|nboards|mnp)=[\w|\d|.\"]+/g),
progs = /pd=\[\];(.*);/.exec(programs),
newdata = {}, tmp, prog;
for (var i=0; i<vars.length; i++) {
if (vars[i] === "") continue;
tmp = vars[i].split("=");
newdata[tmp[0]] = parseInt(tmp[1]);
}
newdata.pd = [];
if (progs !== null) {
progs = progs[1].split(";");
for (i=0; i<progs.length; i++) {
prog = progs[i].split("=");
prog = prog[1].replace("[", "");
prog = prog.replace("]", "");
newdata.pd[i] = parseIntArray(prog.split(","));
}
}
window.controller.programs = newdata;
callback();
});
} else {
return send_to_os("/jp","json").done(function(programs){
window.controller.programs = programs;
callback();
});
}
}
function update_controller_stations(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/vs").done(function(stations){
var names = /snames=\[(.*?)\];/.exec(stations),
masop = stations.match(/(?:masop|mo)\s?[=|:]\s?\[(.*?)\]/);
names = names[1].split(",");
names.pop();
for (var i=0; i<names.length; i++) {
names[i] = names[i].replace(/'/g,"");
}
masop = parseIntArray(masop[1].split(","));
window.controller.stations = {
"snames": names,
"masop": masop,
"maxlen": names.length
};
callback();
});
} else {
return send_to_os("/jn","json").done(function(stations){
window.controller.stations = stations;
callback();
});
}
}
function update_controller_options(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/vo").done(function(options){
var isOSPi = options.match(/var sd\s*=/),
vars = {}, tmp, i, o;
if (isOSPi) {
var varsRegex = /(tz|htp|htp2|nbrd|seq|sdt|mas|mton|mtoff|urs|rst|wl|ipas)\s?[=|:]\s?([\w|\d|.\"]+)/gm,
name;
while ((tmp = varsRegex.exec(options)) !== null) {
name = tmp[1].replace("nbrd","ext").replace("mtoff","mtof");
vars[name] = +tmp[2];
}
vars.ext--;
vars.fwv = "1.8.3-ospi";
} else {
var keyIndex = {1:"tz",2:"ntp",12:"hp0",13:"hp1",14:"ar",15:"ext",16:"seq",17:"sdt",18:"mas",19:"mton",20:"mtof",21:"urs",22:"rso",23:"wl",25:"ipas",26:"devid"};
tmp = /var opts=\[(.*)\];/.exec(options);
tmp = tmp[1].replace(/"/g,"").split(",");
for (i=0; i<tmp.length-1; i=i+4) {
o = +tmp[i+3];
if ($.inArray(o,[1,2,12,13,14,15,16,17,18,19,20,21,22,23,25,26]) !== -1) {
vars[keyIndex[o]] = +tmp[i+2];
}
}
vars.fwv = 183;
}
window.controller.options = vars;
callback();
});
} else {
return send_to_os("/jo","json").done(function(options){
window.controller.options = options;
callback();
});
}
}
function update_controller_status(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/sn0").then(
function(status){
var tmp = status.match(/\d+/);
tmp = parseIntArray(tmp[0].split(""));
window.controller.status = tmp;
callback();
},
function(){
window.controller.status = [];
});
} else {
return send_to_os("/js","json").then(
function(status){
window.controller.status = status.sn;
callback();
},
function(){
window.controller.status = [];
});
}
}
function update_controller_settings(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("").then(
function(settings){
var varsRegex = /(ver|devt|nbrd|tz|en|rd|rs|mm|rdst)\s?[=|:]\s?([\w|\d|.\"]+)/gm,
loc = settings.match(/loc\s?[=|:]\s?[\"|'](.*)[\"|']/),
lrun = settings.match(/lrun=\[(.*)\]/),
ps = settings.match(/ps=\[(.*)\];/),
vars = {}, tmp, i;
ps = ps[1].split("],[");
for (i = ps.length - 1; i >= 0; i--) {
ps[i] = parseIntArray(ps[i].replace(/\[|\]/g,"").split(","));
}
while ((tmp = varsRegex.exec(settings)) !== null) {
vars[tmp[1]] = +tmp[2];
}
vars.loc = loc[1];
vars.ps = ps;
vars.lrun = parseIntArray(lrun[1].split(","));
window.controller.settings = vars;
},
function(){
if (window.controller.settings && window.controller.stations) {
var ps = [], i;
for (i=0; i<window.controller.stations.maxlen; i++) {
ps.push([0,0]);
}
window.controller.settings.ps = ps;
}
});
} else {
return send_to_os("/jc","json").then(
function(settings){
window.controller.settings = settings;
callback();
},
function(){
if (window.controller.settings && window.controller.stations) {
var ps = [], i;
for (i=0; i<window.controller.stations.maxlen; i++) {
ps.push([0,0]);
}
window.controller.settings.ps = ps;
}
});
}
}
// Multisite functions
function check_configured(firstLoad) {
var sites = getsites(),
current = localStorage.getItem("current_site"),
names = Object.keys(sites);
if (sites === null || !names.length) {
if (firstLoad) {
changePage("#start");
}
return;
}
if (current === null || !(current in sites)) {
$.mobile.loading("hide");
site_select();
return;
}
update_site_list(names);
window.curr_ip = sites[current].os_ip;
window.curr_pw = sites[current].os_pw;
if (typeof sites[current].ssl !== "undefined" && sites[current].ssl === "1") {
window.curr_prefix = "https://";
} else {
window.curr_prefix = "http://";
}
if (typeof sites[current].auth_user !== "undefined" && typeof sites[current].auth_pw !== "undefined") {
window.curr_auth = true;
window.curr_auth_user = sites[current].auth_user;
window.curr_auth_pw = sites[current].auth_pw;
} else {
delete window.curr_auth;
}
if (sites[current].is183) {
window.curr_183 = true;
} else {
delete window.curr_183;
}
newload();
}
// Add a new site
function submit_newuser(ssl,useAuth) {
document.activeElement.blur();
$.mobile.loading("show");
var sites = getsites(),
ip = $("#os_ip").val(),
success = function(data){
$.mobile.loading("hide");
var is183;
if (typeof data === "string" && data.match(/var (en|sd)\s*=/)) is183 = true;
if (data.fwv !== undefined || is183 === true) {
var name = $("#os_name").val(),
ip = $("#os_ip").val().replace(/^https?:\/\//,"");
if (name === "") name = "Site "+(Object.keys(sites).length+1);
sites[name] = {};
sites[name].os_ip = window.curr_ip = ip;
sites[name].os_pw = window.curr_pw = $("#os_pw").val();
if (ssl) {
sites[name].ssl = "1";
window.curr_prefix = "https://";
} else {
window.curr_prefix = "http://";
}
if (useAuth) {
sites[name].auth_user = $("#os_auth_user").val();
sites[name].auth_pw = $("#os_auth_pw").val();
window.curr_auth = true;
window.curr_auth_user = sites[name].auth_user;
window.curr_auth_pw = sites[name].auth_pw;
} else {
delete window.curr_auth;
}
if (is183 === true) {
sites[name].is183 = "1";
window.curr_183 = true;
}
$("#os_name,#os_ip,#os_pw,#os_auth_user,#os_auth_pw").val("");
storage.set({
"sites": JSON.stringify(sites),
"current_site": name
},function(){
update_site_list(Object.keys(sites));
newload();
});
} else {
showerror(_("Check IP/Port and try again."));
}
},
fail = function (x){
if (!useAuth && x.status === 401) {
getAuth();
return;
}
if (ssl) {
$.mobile.loading("hide");
showerror(_("Check IP/Port and try again."));
} else {
submit_newuser(true);
}
},
getAuth = function(){
if ($("#addnew-auth").length) {
submit_newuser(ssl,true);
} else {
showAuth();
}
},
showAuth = function(){
$.mobile.loading("hide");
var html = $('<div class="ui-content" id="addnew-auth">' +
'<form method="post" novalidate>' +
'<p class="center smaller">'+_("Authorization Required")+'</p>' +
'<label for="os_auth_user">'+_("Username:")+'</label>' +
'<input autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" type="text" name="os_auth_user" id="os_auth_user" />' +
'<label for="os_auth_pw">'+_("Password:")+'</label>' +
'<input type="password" name="os_auth_pw" id="os_auth_pw" />' +
'<input type="submit" value="'+_("Submit")+'" />' +
'</form>' +
'</div>').enhanceWithin();
html.on("submit","form",function(){
submit_newuser(ssl,true);
return false;
});
$("#addnew-content").hide();
$("#addnew").append(html).popup("reposition",{positionTo:"window"});
},
prefix;
if (!ip) {
showerror(_("An IP address is required to continue."));
return;
}
if (useAuth !== true && $("#os_useauth").is(":checked")) {
getAuth();
return;
}
if ($("#os_usessl").is(":checked") === true) ssl = true;
if (ssl) {
prefix = "https://";
} else {
prefix = "http://";
}
if (useAuth) {
$("#addnew-auth").hide();
$("#addnew-content").show();
$("#addnew").popup("reposition",{positionTo:"window"});
}
//Submit form data to the server
$.ajax({
url: prefix+ip+"/jo",
type: "GET",
dataType: "json",
timeout: 3000,
global: false,
beforeSend: function(xhr) { if (useAuth) xhr.setRequestHeader("Authorization", "Basic " + btoa($("#os_auth_user").val() + ":" + $("#os_auth_pw").val())); },
error: function(x){
if (!useAuth && x.status === 401) {
getAuth();
return;
}
$.ajax({
url: prefix+ip,
type: "GET",
dataType: "text",
timeout: 3000,
global: false,
beforeSend: function(xhr) { if (useAuth) xhr.setRequestHeader("Authorization", "Basic " + btoa($("#os_auth_user").val() + ":" + $("#os_auth_pw").val())); },
success: success,
error: fail
});
},
success: success
});
}
function show_site_select(list) {
$("#site-select").popup("destroy").remove();
var popup = $('<div data-role="popup" id="site-select" data-theme="a" data-overlay-theme="b">' +
'<div data-role="header" data-theme="b">' +
'<h1>'+_("Select Site")+'</h1>' +
'</div>' +
'<div class="ui-content">' +
'<ul data-role="none" class="ui-listview ui-corner-all ui-shadow">' +
'</ul>' +
'</div>' +
'</div>');
if (list) popup.find("ul").html(list);
popup.one("popupafterclose",function(){
$(this).popup("destroy").remove();
}).popup({
history: false,
"positionTo": "window"
}).enhanceWithin().popup("open");
}
function show_addsite() {
if (typeof window.deviceip === "undefined") {
show_addnew();
} else {
var popup = $("#addsite");
$("#site-add-scan").one("click",function(){
$(".ui-popup-active").children().first().popup("close");
});
popup.popup("open").popup("reposition",{
"positionTo": "#site-add"
});
}
}
function show_addnew(autoIP,closeOld) {
$("#addnew").popup("destroy").remove();
var isAuto = (autoIP) ? true : false,
addnew = $('<div data-role="popup" id="addnew" data-theme="a">'+
'<div data-role="header" data-theme="b">'+
'<h1>'+_("New Device")+'</h1>' +
'</div>' +
'<div class="ui-content" id="addnew-content">' +
'<form method="post" novalidate>' +
((isAuto) ? '' : '<p class="center smaller">'+_("Note: The name is used to identify the OpenSprinkler within the app. OpenSprinkler IP can be either an IP or hostname. You can also specify a port by using IP:Port")+'</p>') +
'<label for="os_name">'+_("Open Sprinkler Name:")+'</label>' +
'<input autocorrect="off" spellcheck="false" type="text" name="os_name" id="os_name" placeholder="Home" />' +
((isAuto) ? '' : '<label for="os_ip">'+_("Open Sprinkler IP:")+'</label>') +
'<input '+((isAuto) ? 'data-role="none" style="display:none" ' : '')+'autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" type="url" name="os_ip" id="os_ip" value="'+((isAuto) ? autoIP : '')+'" placeholder="home.dyndns.org" />' +
'<label for="os_pw">'+_("Open Sprinkler Password:")+'</label>' +
'<input type="password" name="os_pw" id="os_pw" value="" />' +
((isAuto) ? '' : '<div data-theme="a" data-mini="true" data-role="collapsible"><h4>Advanced</h4><fieldset data-role="controlgroup" data-type="horizontal" data-mini="true" class="center">' +
'<input type="checkbox" name="os_useauth" id="os_useauth">' +
'<label for="os_useauth">'+_("Use Auth")+'</label>' +
'<input type="checkbox" name="os_usessl" id="os_usessl">' +
'<label for="os_usessl">'+_("Use SSL")+'</label>' +
'</fieldset></div>') +
'<input type="submit" data-theme="b" value="'+_("Submit")+'" />' +
'</form>' +
'</div>' +
'</div>');
addnew.find("form").on("submit",function(){
submit_newuser();
return false;
});
addnew.one("popupafterclose",function(){
$(this).popup("destroy").remove();
}).popup({
history: false,
"positionTo": "window"
}).enhanceWithin();
if (closeOld) {
$(".ui-popup-active").children().first().one("popupafterclose",function(){
addnew.popup("open");
}).popup("close");
} else {
addnew.popup("open");
}
fixInputClick(addnew);
addnew.find(".ui-collapsible-heading-toggle").on("click",function(){
var open = $(this).parents(".ui-collapsible").hasClass("ui-collapsible-collapsed"),
page = $.mobile.pageContainer.pagecontainer("getActivePage"),
height = parseInt(page.css("min-height"));
if (open) {
page.css("min-height",(height+65)+"px");
} else {
page.css("min-height",(height-65)+"px");
}
addnew.popup("reposition",{positionTo:"window"});
});
}
function show_sites() {
var list = "<div data-role='collapsible-set'>",
sites = getsites(),
total = Object.keys(sites).length,
page = $("#site-control");
page.find("div[data-role='header'] > .ui-btn-right").off("click").on("click",show_addsite);
page.find("#site-add-scan").off("click").on("click",start_scan);
page.find("#site-add-manual").off("click").on("click",function(){
show_addnew(false,true);
});
$.each(sites,function(a,b){
var c = a.replace(/ /g,"_");
list += "<fieldset "+((total == 1) ? "data-collapsed='false'" : "")+" id='site-"+c+"' data-role='collapsible'>";
list += "<legend>"+a+"</legend>";
list += "<a data-role='button' class='connectnow' data-site='"+a+"' href='#'>"+_("Connect Now")+"</a>";
list += "<form data-site='"+c+"' novalidate>";
list += "<label for='cnm-"+c+"'>"+_("Change Name")+"</label><input id='cnm-"+c+"' type='text' placeholder='"+a+"' />";
list += "<label for='cip-"+c+"'>"+_("Change IP")+"</label><input id='cip-"+c+"' type='url' placeholder='"+b.os_ip+"' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' />";
list += "<label for='cpw-"+c+"'>"+_("Change Password")+"</label><input id='cpw-"+c+"' type='password' />";
list += "<input type='submit' value='"+_("Save Changes to")+" "+a+"' /></form>";
list += "<a data-role='button' class='deletesite' data-site='"+a+"' href='#' data-theme='b'>"+_("Delete")+" "+a+"</a>";
list += "</fieldset>";
});
list = $(list+"</div>");
list.find(".connectnow").on("click",function(){
update_site(this.dataset.site);
return false;
});
list.find("form").on("submit",function(){
change_site(this.dataset.site);
return false;
});
list.find(".deletesite").on("click",function(){
delete_site(this.dataset.site);
return false;
});
page.find(".ui-content").html(list).enhanceWithin();
page.find(".ui-collapsible-set").collapsibleset();
page.one("pagehide",function(){
page.find("div[data-role='header'] > .ui-btn-right,#site-add-manual,#site-add-scan").off("click");
page.find(".ui-content").empty();
});
}
function delete_site(site) {
areYouSure(_("Are you sure you want to delete")+" '"+site+"'?","",function(){
var sites = getsites();
delete sites[site];
localStorage.setItem("sites",JSON.stringify(sites));
update_site_list(Object.keys(sites));
show_sites();
if ($.isEmptyObject(sites)) {
changePage("#start");
return false;
}
if (site === localStorage.getItem("current_site")) $("#site-control").find(".ui-toolbar-back-btn").toggle(false);
showerror(_("Site deleted successfully"));
return false;
});
}
// Modify site IP and/or password
function change_site(site) {
var sites = getsites(),
ip = $("#cip-"+site).val(),
pw = $("#cpw-"+site).val(),
nm = $("#cnm-"+site).val(),
rename;
site = site.replace(/_/g," ");
rename = (nm !== "" && nm != site);
if (ip !== "") sites[site].os_ip = ip;
if (pw !== "") sites[site].os_pw = pw;
if (rename) {
sites[nm] = sites[site];
delete sites[site];
site = nm;
storage.set({"current_site":site});
update_site_list(Object.keys(sites));
}
storage.set({"sites":JSON.stringify(sites)});
showerror(_("Site updated successfully"));
storage.get("current_site",function(data){
if (site === data.current_site) {
if (pw !== "") window.curr_pw = pw;
if (ip !== "") check_configured();
}
});
if (rename) show_sites();
}
// Display the site select popup
function site_select(names) {
var newlist = "";
names = names || Object.keys(getsites());
for (var i=0; i < names.length; i++) {
newlist += "<li><a class='ui-btn ui-btn-icon-right ui-icon-carat-r' href='#'>"+names[i]+"</a></li>";
}
newlist = $(newlist);
newlist.find("a").on("click",function(){
update_site(this.innerHTML);
return false;
});
show_site_select(newlist);
}
// Update the panel list of sites
function update_site_list(names) {
var list = "",
select = $("#site-selector");
storage.get("current_site",function(data){
$.each(names,function(a,b){
list += "<option "+(b==data.current_site ? "selected ":"")+"value='"+b+"'>"+b+"</option>";
});
select.html(list);
if (select.parent().parent().hasClass("ui-select")) select.selectmenu("refresh");
});
}
// Change the current site
function update_site(newsite) {
var sites = getsites();
if (newsite in sites) storage.set({"current_site":newsite},check_configured);
}
// Get the list of sites from the local storage
function getsites() {
var sites = localStorage.getItem("sites");
sites = (sites === null) ? {} : JSON.parse(sites);
return sites;
}
// Automatic device detection functions
function checkAutoScan() {
try {
// Request the device's IP address
networkinterface.getIPAddress(function(ip){
var chk = parseIntArray(ip.split("."));
// Check if the IP is on a private network, if not don't enable automatic scanning
if (!(chk[0] == 10 || (chk[0] == 172 && chk[1] > 17 && chk[1] < 32) || (chk[0] == 192 && chk[1] == 168))) {
resetStartMenu();
return;
}
//Change main menu items to reflect ability to automatically scan
var auto = $("#auto-scan"),
next = auto.next();
next.removeClass("ui-first-child").find("a.ui-btn").text(_("Manually Add Device"));
auto.show();
window.deviceip = ip;
});
} catch (err) {
resetStartMenu();
}
}
function resetStartMenu() {
// Change main menu to reflect manual controller entry
var auto = $("#auto-scan"),
next = auto.next();
delete window.deviceip;
next.addClass("ui-first-child").find("a.ui-btn").text(_("Add Controller"));
auto.hide();
}
function start_scan(port,type) {
var ip = window.deviceip.split("."),
scanprogress = 1,
devicesfound = 0,
newlist = "",
suffix = "",
oldsites = getsites(),
oldips = [],
i, url, notfound, found, baseip, check_scan_status, scanning, dtype;
type = type || 0;
for (i in oldsites) {
if (oldsites.hasOwnProperty(i)) {
oldips.push(oldsites[i].os_ip);
}
}
notfound = function(){
scanprogress++;
};
found = function (reply) {
scanprogress++;
var ip = $.mobile.path.parseUrl(this.url).authority,
fwv, tmp;
if ($.inArray(ip,oldips) !== -1) return;
if (this.dataType === "text") {
tmp = reply.match(/var\s*ver=(\d+)/);
if (!tmp) return;
fwv = tmp[1];
} else {
fwv = reply.fwv;
}
devicesfound++;
newlist += "<li><a class='ui-btn ui-btn-icon-right ui-icon-carat-r' href='#' data-ip='"+ip+"'>"+ip+"<p>"+_("Firmware")+": "+getOSVersion(fwv)+"</p></a></li>";
};
// Check if scanning is complete
check_scan_status = function() {
if (scanprogress == 245) {
$.mobile.loading("hide");
clearInterval(scanning);
if (!devicesfound) {
if (type === 0) {
start_scan(8080,1);
} else if (type === 1) {
start_scan(80,2);
} else if (type === 2) {
start_scan(8080,3);
} else {
showerror(_("No new devices were detected on your network"));
}
} else {
newlist = $(newlist);
newlist.find("a").on("click",function(){
add_found(this.dataset.ip);
return false;
});
show_site_select(newlist);
}
}
};
ip.pop();
baseip = ip.join(".");
if (type === 1) {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler Pi"),
textVisible: true,
theme: 'b'
});
} else if (type === 2) {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler (1.8.3)"),
textVisible: true,
theme: 'b'
});
} else if (type === 3) {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler Pi (1.8.3)"),
textVisible: true,
theme: 'b'
});
} else {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler"),
textVisible: true,
theme: 'b'
});
}
// Start scan
for (i = 1; i<=244; i++) {
ip = baseip+"."+i;
if (type < 2) {
suffix = "/jo";
dtype = "json";
} else {
dtype = "text";
}
url = "http://"+ip+((port && port != 80) ? ":"+port : "")+suffix;
$.ajax({
url: url,
type: "GET",
dataType: dtype,
timeout: 3000,
global: false,
error: notfound,
success: found
});
}
scanning = setInterval(check_scan_status,200);
}
// Show popup for new device after populating device IP with selected result
function add_found(ip) {
$("#site-select").one("popupafterclose", function(){
show_addnew(ip);
}).popup("close");
}
// Weather functions
function show_weather_settings() {
var page = $('<div data-role="page" id="weather_settings">' +
'<div data-theme="b" data-role="header" data-position="fixed" data-tap-toggle="false" data-add-back-btn="true">' +
'<h3>'+_("Weather Settings")+'</h3>' +
'<a href="#" class="ui-btn-right wsubmit">'+_("Submit")+'</a>' +
'</div>' +
'<div class="ui-content" role="main">' +
'<ul data-role="listview" data-inset="true">' +
'<li>' +
'<label for="weather_provider">'+_("Weather Provider")+'</label>' +
'<select data-mini="true" id="weather_provider">' +
'<option value="yahoo" '+(window.curr_wa.weather_provider == "yahoo" ? "selected" : "")+'>'+_("Yahoo!")+'</option>' +
'<option value="wunderground" '+(window.curr_wa.weather_provider == "wunderground" ? "selected" : "")+'>'+_("Wunderground")+'</option>' +
'</select>' +
(window.curr_wa.weather_provider == "wunderground" ? '<label for="wapikey">'+_("Wunderground API Key")+'</label><input data-mini="true" type="text" id="wapikey" value="'+window.curr_wa.wapikey+'" />' : "") +
'</li>' +
'</ul>' +
'<ul data-role="listview" data-inset="true"> ' +
'<li>' +
'<p class="rain-desc">'+_("When automatic rain delay is enabled, the weather will be checked for rain every hour. If the weather reports any condition suggesting rain, a rain delay is automatically issued using the below set delay duration.")+'</p>' +
'<div class="ui-field-contain">' +
'<label for="auto_delay">'+_("Auto Rain Delay")+'</label>' +
'<input type="checkbox" data-on-text="On" data-off-text="Off" data-role="flipswitch" name="auto_delay" id="auto_delay" '+(window.curr_wa.auto_delay == "on" ? "checked" : "")+'>' +
'</div>' +
'<div class="ui-field-contain duration-input">' +
'<label for="delay_duration">'+_("Delay Duration")+'</label>' +
'<button id="delay_duration" data-mini="true" value="'+(window.curr_wa.delay_duration*3600)+'">'+dhms2str(sec2dhms(window.curr_wa.delay_duration*3600))+'</button>' +
'</div>' +
'</li>' +
'</ul>' +
'<a class="wsubmit" href="#" data-role="button" data-theme="b" type="submit">'+_("Submit")+'</a>' +
'</div>' +
'</div>');
//Handle provider select change on weather settings
page
.on("change","#weather_provider",function(){
var val = $(this).val();
if (val === "wunderground") {
$("#wapikey,label[for='wapikey']").show("fast");
} else {
$("#wapikey,label[for='wapikey']").hide("fast");
}
})
.one("pagehide",function(){
$(this).remove();
})
.find(".wsubmit").on("click",function(){
submit_weather_settings();
return false;
});
page.find("#delay_duration").on("click",function(){
var dur = $(this),
name = page.find("label[for='"+dur.attr("id")+"']").text();
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
},345600,2);
});
page.appendTo("body");
}
function submit_weather_settings() {
var url = "/uwa?auto_delay="+($("#auto_delay").is(":checked") ? "on" : "off")+"&delay_duration="+parseInt($("#delay_duration").val()/3600)+"&weather_provider="+$("#weather_provider").val()+"&wapikey="+$("#wapikey").val();
send_to_os(url).then(
function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Weather settings have been saved"));
});
window.history.back();
checkWeatherPlugin();
},
function(){
showerror(_("Weather settings were not saved. Please try again."));
}
);
}
function convert_temp(temp,region) {
if (region == "United States" || region == "Bermuda" || region == "Palau") {
temp = temp+"°F";
} else {
temp = parseInt(Math.round((temp-32)*(5/9)))+"°C";
}
return temp;
}
function hide_weather() {
$("#weather-list").animate({
"margin-left": "-1000px"
},1000,function(){
$(this).hide();
});
}
function update_weather() {
storage.get(["provider","wapikey"],function(data){
if (window.controller.settings.loc === "") {
hide_weather();
return;
}
showLoading("#weather");
if (data.provider == "wunderground" && data.wapikey) {
update_wunderground_weather(data.wapikey);
} else {
update_yahoo_weather();
}
});
}
function update_yahoo_weather() {
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.placefinder%20where%20text=%22"+escape(window.controller.settings.loc)+"%22&format=json",function(woeid){
if (woeid.query.results === null) {
hide_weather();
return;
}
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20item%2Ctitle%2Clocation%20from%20weather.forecast%20where%20woeid%3D%22"+woeid.query.results.Result.woeid+"%22&format=json",function(data){
// Hide the weather if no data is returned
if (data.query.results.channel.item.title == "City not found") {
hide_weather();
return;
}
var now = data.query.results.channel.item.condition,
title = data.query.results.channel.title,
loc = /Yahoo! Weather - (.*)/.exec(title),
region = data.query.results.channel.location.country;
$("#weather")
.html("<div title='"+now.text+"' class='wicon cond"+now.code+"'></div><span>"+convert_temp(now.temp,region)+"</span><br><span class='location'>"+loc[1]+"</span>")
.on("click",show_forecast);
$("#weather-list").animate({
"margin-left": "0"
},1000).show();
update_yahoo_forecast(data.query.results.channel.item.forecast,loc[1],region,now);
});
});
}
function update_yahoo_forecast(data,loc,region,now) {
var list = "<li data-role='list-divider' data-theme='a' class='center'>"+loc+"</li>",
i;
list += "<li data-icon='false' class='center'><div title='"+now.text+"' class='wicon cond"+now.code+"'></div><span data-translate='Now'>"+_("Now")+"</span><br><span>"+convert_temp(now.temp,region)+"</span></li>";
for (i=0;i < data.length; i++) {
list += "<li data-icon='false' class='center'><span>"+data[i].date+"</span><br><div title='"+data[i].text+"' class='wicon cond"+data[i].code+"'></div><span data-translate='"+data[i].day+"'>"+_(data[i].day)+"</span><br><span data-translate='Low'>"+_("Low")+"</span><span>: "+convert_temp(data[i].low,region)+" </span><span data-translate='High'>"+_("High")+"</span><span>: "+convert_temp(data[i].high,region)+"</span></li>";
}
var forecast = $("#forecast_list");
forecast.html(list).enhanceWithin();
if (forecast.hasClass("ui-listview")) forecast.listview("refresh");
}
function update_wunderground_weather(wapikey) {
$.ajax({
dataType: "jsonp",
type: "GET",
url: "https://api.wunderground.com/api/"+wapikey+"/conditions/forecast/lang:EN/q/"+escape(window.controller.settings.loc)+".json",
success: function(data) {
var code, temp;
if (data.current_observation.icon_url.indexOf("nt_") !== -1) { code = "nt_"+data.current_observation.icon; }
else code = data.current_observation.icon;
var ww_forecast = {
"condition": {
"text": data.current_observation.weather,
"code": code,
"temp_c": data.current_observation.temp_c,
"temp_f": data.current_observation.temp_f,
"date": data.current_observation.observation_time,
"precip_today_in": data.current_observation.precip_today_in,
"precip_today_metric": data.current_observation.precip_today_metric,
"type": "wunderground"
},
"location": data.current_observation.display_location.full,
"region": data.current_observation.display_location.country_iso3166,
simpleforecast: {}
};
$.each(data.forecast.simpleforecast.forecastday,function(k,attr) {
ww_forecast.simpleforecast[k] = attr;
});
if (ww_forecast.region == "US" || ww_forecast.region == "BM" || ww_forecast.region == "PW") temp = Math.round(ww_forecast.condition.temp_f)+"°F";
else temp = ww_forecast.condition.temp_c+"°C";
$("#weather")
.html("<div title='"+ww_forecast.condition.text+"' class='wicon cond"+code+"'></div><span>"+temp+"</span><br><span class='location'>"+ww_forecast.location+"</span>")
.on("click",show_forecast);
$("#weather-list").animate({
"margin-left": "0"
},1000).show();
update_wunderground_forecast(ww_forecast);
}
});
}
function update_wunderground_forecast(data) {
var temp, precip;
if (data.region == "US" || data.region == "BM" || data.region == "PW") {
temp = data.condition.temp_f+"°F";
precip = data.condition.precip_today_in+" in";
} else {
temp = data.condition.temp_c+"°C";
precip = data.condition.precip_today_metric+" mm";
}
var list = "<li data-role='list-divider' data-theme='a' class='center'>"+data.location+"</li>";
list += "<li data-icon='false' class='center'><div title='"+data.condition.text+"' class='wicon cond"+data.condition.code+"'></div><span data-translate='Now'>"+_("Now")+"</span><br><span>"+temp+"</span><br><span data-translate='Precip'>"+_("Precip")+"</span><span>: "+precip+"</span></li>";
$.each(data.simpleforecast, function(k,attr) {
var precip;
if (data.region == "US" || data.region == "BM" || data.region == "PW") {
precip = attr.qpf_allday["in"];
if (precip === null) precip = 0;
list += "<li data-icon='false' class='center'><span>"+attr.date.monthname_short+" "+attr.date.day+"</span><br><div title='"+attr.conditions+"' class='wicon cond"+attr.icon+"'></div><span data-translate='"+attr.date.weekday_short+"'>"+_(attr.date.weekday_short)+"</span><br><span data-translate='Low'>"+_("Low")+"</span><span>: "+attr.low.fahrenheit+"°F </span><span data-translate='High'>"+_("High")+"</span><span>: "+attr.high.fahrenheit+"°F</span><br><span data-translate='Precip'>"+_("Precip")+"</span><span>: "+precip+" in</span></li>";
} else {
precip = attr.qpf_allday.mm;
if (precip === null) precip = 0;
list += "<li data-icon='false' class='center'><span>"+attr.date.monthname_short+" "+attr.date.day+"</span><br><div title='"+attr.conditions+"' class='wicon cond"+attr.icon+"'></div><span data-translate='"+attr.date.weekday_short+"'>"+_(attr.date.weekday_short)+"</span><br><span data-translate='Low'>"+_("Low")+"</span><span>: "+attr.low.celsius+"°C </span><span data-translate='High'>"+_("High")+"</span><span>: "+attr.high.celsius+"°C</span><br><span data-translate='Precip'>"+_("Precip")+"</span><span>: "+precip+" mm</span></li>";
}
});
var forecast = $("#forecast_list");
forecast.html(list).enhanceWithin();
if (forecast.hasClass("ui-listview")) forecast.listview("refresh");
}
function show_forecast() {
var page = $("#forecast");
page.find(".ui-header > .ui-btn-right").on("click",update_weather);
page.one("pagehide",function(){
page.find(".ui-header > .ui-btn-right").off("click");
});
changePage("#forecast");
return false;
}
function open_panel() {
var panel = $("#sprinklers-settings");
panel.panel("option","classes.modal","needsclick ui-panel-dismiss");
panel.find("a[href='#site-control']").off("click").one("click",function(){
changeFromPanel("site-control");
return false;
});
panel.find("a[href='#about']").off("click").one("click",function(){
changeFromPanel("about");
return false;
});
panel.find(".export_config").off("click").on("click",function(){
export_config();
return false;
});
panel.find(".import_config").off("click").on("click",function(){
import_config();
return false;
});
panel.one("panelclose",function(){
panel.find(".export_config,.import_config").off("click");
});
panel.panel('open');
}
// Device setting management functions
function show_settings() {
var list = "",
page = $("#os-settings"),
timezones, tz, i;
page.find("div[data-role='header'] > .ui-btn-right").on("click",submit_settings);
list = "<li><div class='ui-field-contain'><fieldset>";
if (typeof window.controller.options.tz !== "undefined") {
timezones = ["-12:00","-11:30","-11:00","-10:00","-09:30","-09:00","-08:30","-08:00","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","+00:00","+01:00","+02:00","+03:00","+03:30","+04:00","+04:30","+05:00","+05:30","+05:45","+06:00","+06:30","+07:00","+08:00","+08:45","+09:00","+09:30","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"];
tz = window.controller.options.tz-48;
tz = ((tz>=0)?"+":"-")+pad((Math.abs(tz)/4>>0))+":"+((Math.abs(tz)%4)*15/10>>0)+((Math.abs(tz)%4)*15%10);
list += "<label for='o1' class='select'>"+_("Timezone")+"</label><select data-mini='true' id='o1'>";
for (i=0; i<timezones.length; i++) {
list += "<option "+((timezones[i] == tz) ? "selected" : "")+" value='"+timezones[i]+"'>"+timezones[i]+"</option>";
}
list += "</select>";
}
if (typeof window.controller.options.mas !== "undefined") {
list += "<label for='o18' class='select'>"+_("Master Station")+"</label><select data-mini='true' id='o18'><option value='0'>"+_("None")+"</option>";
for (i=0; i<window.controller.stations.snames.length; i++) {
list += "<option "+(((i+1) == window.controller.options.mas) ? "selected" : "")+" value='"+(i+1)+"'>"+window.controller.stations.snames[i]+"</option>";
if (i == 7) break;
}
list += "</select>";
}
if (typeof window.controller.options.hp0 !== "undefined") {
list += "<label for='o12'>"+_("HTTP Port (restart required)")+"</label><input data-mini='true' type='number' pattern='[0-9]*' id='o12' value='"+(window.controller.options.hp1*256+window.controller.options.hp0)+"' />";
}
if (typeof window.controller.options.devid !== "undefined") {
list += "<label for='o26'>"+_("Device ID (restart required)")+"</label><input data-mini='true' type='number' pattern='[0-9]*' max='255' id='o26' value='"+window.controller.options.devid+"' />";
}
list += "<label for='loc'>"+_("Location")+"</label><input data-mini='true' type='text' id='loc' value='"+window.controller.settings.loc+"' />";
if (typeof window.controller.options.ext !== "undefined") {
list += "<label for='o15'>"+_("Extension Boards")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='5' id='o15' value='"+window.controller.options.ext+"' />";
}
if (typeof window.controller.options.sdt !== "undefined") {
list += "<label for='o17'>"+_("Station Delay (seconds)")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='240' id='o17' value='"+window.controller.options.sdt+"' />";
}
if (typeof window.controller.options.mton !== "undefined") {
list += "<label for='o19'>"+_("Master On Delay")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='60' id='o19' value='"+window.controller.options.mton+"' />";
}
if (typeof window.controller.options.mtof !== "undefined") {
list += "<label for='o20'>"+_("Master Off Delay")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='-60' max='60' id='o20' value='"+window.controller.options.mtof+"' />";
}
if (typeof window.controller.options.wl !== "undefined") {
list += "<label for='o23'>"+_("% Watering")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='250' id='o23' value='"+window.controller.options.wl+"' />";
}
if (typeof window.controller.options.ntp !== "undefined") {
list += "<label for='o2'><input data-mini='true' id='o2' type='checkbox' "+((window.controller.options.ntp === 1) ? "checked='checked'" : "")+" />"+_("NTP Sync")+"</label>";
}
if (typeof window.controller.options.ar !== "undefined") {
list += "<label for='o14'><input data-mini='true' id='o14' type='checkbox' "+((window.controller.options.ar === 1) ? "checked='checked'" : "")+" />"+_("Auto Reconnect")+"</label>";
}
if (typeof window.controller.options.seq !== "undefined") {
list += "<label for='o16'><input data-mini='true' id='o16' type='checkbox' "+((window.controller.options.seq === 1) ? "checked='checked'" : "")+" />"+_("Sequential")+"</label>";
}
if (typeof window.controller.options.urs !== "undefined") {
list += "<label for='o21'><input data-mini='true' id='o21' type='checkbox' "+((window.controller.options.urs === 1) ? "checked='checked'" : "")+" />"+_("Use Rain Sensor")+"</label>";
}
if (typeof window.controller.options.rso !== "undefined") {
list += "<label for='o22'><input data-mini='true' id='o22' type='checkbox' "+((window.controller.options.rso === 1) ? "checked='checked'" : "")+" />"+_("Normally Open (Rain Sensor)")+"</label>";
}
if (typeof window.controller.options.ipas !== "undefined") {
list += "<label for='o25'><input data-mini='true' id='o25' type='checkbox' "+((window.controller.options.ipas === 1) ? "checked='checked'" : "")+" />"+_("Ignore Password")+"</label>";
}
list += "</fieldset></div></li>";
page.find(".ui-content").html($('<ul data-role="listview" data-inset="true" id="os-settings-list"></ul>').html(list).listview().enhanceWithin());
page.one("pagehide",function(){
page.find(".ui-header > .ui-btn-right").off("click");
page.find(".ui-content").empty();
});
}
function submit_settings() {
var opt = {},
invalid = false,
isPi = isOSPi(),
keyNames = {1:"tz",2:"ntp",12:"htp",13:"htp2",14:"ar",15:"nbrd",16:"seq",17:"sdt",18:"mas",19:"mton",20:"mtoff",21:"urs",22:"rst",23:"wl",25:"ipas"},
key;
$("#os-settings-list").find(":input").each(function(a,b){
var $item = $(b),
id = $item.attr('id'),
data = $item.val();
switch (id) {
case "o1":
var tz = data.split(":");
tz[0] = parseInt(tz[0],10);
tz[1] = parseInt(tz[1],10);
tz[1]=(tz[1]/15>>0)/4.0;tz[0]=tz[0]+(tz[0]>=0?tz[1]:-tz[1]);
data = ((tz[0]+12)*4)>>0;
break;
case "o2":
case "o14":
case "o16":
case "o21":
case "o22":
case "o25":
data = $item.is(":checked") ? 1 : 0;
if (!data) return true;
break;
}
if (isPi) {
if (id == "loc") {
id = "oloc";
} else {
key = /\d+/.exec(id);
id = "o"+keyNames[key];
}
}
opt[id] = data;
});
if (invalid) return;
$.mobile.loading("show");
send_to_os("/co?pw=&"+$.param(opt)).done(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Settings have been saved"));
});
window.history.back();
update_controller(update_weather);
});
}
// Station managament function
function show_stations() {
var list = "<li class='wrap'>",
page = $("#os-stations"),
isMaster = window.controller.options.mas ? true : false,
hasIR = (typeof window.controller.stations.ignore_rain === "object") ? true : false,
useTableView = (hasIR || isMaster);
page.find("div[data-role='header'] > .ui-btn-right").on("click",submit_stations);
if (useTableView) {
list += "<table><tr><th class='center'>"+_("Station Name")+"</th>";
if (isMaster) list += "<th class='center'>"+_("Activate Master?")+"</th>";
if (hasIR) list += "<th class='center'>"+_("Ignore Rain?")+"</th>";
list += "</tr>";
}
$.each(window.controller.stations.snames,function(i, station) {
if (useTableView) list += "<tr><td>";
list += "<input data-mini='true' id='edit_station_"+i+"' type='text' value='"+station+"' />";
if (useTableView) {
list += "</td>";
if (isMaster) {
if (window.controller.options.mas == i+1) {
list += "<td class='use_master'><p id='um_"+i+"' class='center'>("+_("Master")+")</p></td>";
} else {
list += "<td data-role='controlgroup' data-type='horizontal' class='use_master'><label for='um_"+i+"'><input id='um_"+i+"' type='checkbox' "+((window.controller.stations.masop[parseInt(i/8)]&(1<<(i%8))) ? "checked='checked'" : "")+" /></label></td>";
}
}
if (hasIR) list += "<td data-role='controlgroup' data-type='horizontal' class='use_master'><label for='ir_"+i+"'><input id='ir_"+i+"' type='checkbox' "+((window.controller.stations.ignore_rain[parseInt(i/8)]&(1<<(i%8))) ? "checked='checked'" : "")+" /></label></td></tr>";
list += "</tr>";
}
i++;
});
if (useTableView) list += "</table>";
list += "</li>";
page.find(".ui-content").html($('<ul data-role="listview" data-inset="true" id="os-stations-list"></ul>').html(list).listview().enhanceWithin());
page.one("pagehide",function(){
page.find("div[data-role='header'] > .ui-btn-right").off("click");
page.find(".ui-content").empty();
});
}
function submit_stations() {
var names = {},
invalid = false,
v="",
r="",
bid=0,
bid2=0,
s=0,
s2=0,
m={},
i={},
masop="",
ignore_rain="";
$("#os-stations-list").find(":input,p[id^='um_']").each(function(a,b){
var $item = $(b), id = $item.attr('id'), data = $item.val();
switch (id) {
case "edit_station_" + id.slice("edit_station_".length):
id = "s" + id.split("_")[2];
if (data.length > 32) {
invalid = true;
$item.focus();
showerror(_("Station name must be 32 characters or less"));
return false;
}
names[id] = data;
return true;
case "um_" + id.slice("um_".length):
v = ($item.is(":checked") || $item.prop("tagName") == "P") ? "1".concat(v) : "0".concat(v);
s++;
if (parseInt(s/8) > bid) {
m["m"+bid]=parseInt(v,2); bid++; s=0; v="";
}
return true;
case "ir_" + id.slice("ir_".length):
r = ($item.is(":checked")) ? "1".concat(r) : "0".concat(r);
s2++;
if (parseInt(s2/8) > bid2) {
i["i"+bid2]=parseInt(r,2); bid2++; s2=0; r="";
}
return true;
}
});
m["m"+bid]=parseInt(v,2);
i["i"+bid2]=parseInt(r,2);
if ($("[id^='um_']").length) masop = "&"+$.param(m);
if ($("[id^='ir_']").length) ignore_rain = "&"+$.param(i);
if (invalid) return;
$.mobile.loading("show");
send_to_os("/cs?pw=&"+$.param(names)+masop+ignore_rain).done(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Stations have been updated"));
});
window.history.back();
update_controller();
});
}
// Current status related functions
function get_status() {
var runningTotal = {},
allPnames = [],
color = "",
list = "",
tz = window.controller.options.tz-48,
lastCheck;
if ($.mobile.pageContainer.pagecontainer("getActivePage").attr("id") === "status") {
$("#status .ui-content").empty();
}
tz = ((tz>=0)?"+":"-")+pad((Math.abs(tz)/4>>0))+":"+((Math.abs(tz)%4)*15/10>>0)+((Math.abs(tz)%4)*15%10);
var header = "<span id='clock-s' class='nobr'>"+dateToString(new Date(window.controller.settings.devt*1000))+"</span>"+tzToString(" ","GMT",tz);
if (typeof window.controller.settings.ct === "string" && window.controller.settings.ct !== "0" && typeof window.controller.settings.tu === "string") {
header += " <span>"+window.controller.settings.ct+"°"+window.controller.settings.tu+"</span>";
}
runningTotal.c = window.controller.settings.devt;
var master = window.controller.options.mas,
ptotal = 0;
var open = {};
$.each(window.controller.status, function (i, stn) {
if (stn) open[i] = stn;
});
open = Object.keys(open).length;
if (master && window.controller.status[master-1]) open--;
$.each(window.controller.stations.snames,function(i, station) {
var info = "";
if (master == i+1) {
station += " ("+_("Master")+")";
} else if (window.controller.settings.ps[i][0]) {
var rem=window.controller.settings.ps[i][1];
if (open > 1) {
if (rem > ptotal) ptotal = rem;
} else {
if (window.controller.settings.ps[i][0] !== 99 && rem !== 1) ptotal+=rem;
}
var pid = window.controller.settings.ps[i][0],
pname = pidname(pid);
if (window.controller.status[i] && (pid!=255&&pid!=99)) runningTotal[i] = rem;
allPnames[i] = pname;
info = "<p class='rem'>"+((window.controller.status[i]) ? _("Running") : _("Scheduled"))+" "+pname;
if (pid!=255&&pid!=99) info += " <span id='countdown-"+i+"' class='nobr'>(" + sec2hms(rem) + " "+_("remaining")+")</span>";
info += "</p>";
}
if (window.controller.status[i]) {
color = "green";
} else {
color = "red";
}
list += "<li class='"+color+"'><p class='sname'>"+station+"</p>"+info+"</li>";
});
var footer = "";
var lrdur = window.controller.settings.lrun[2];
if (lrdur !== 0) {
var lrpid = window.controller.settings.lrun[1];
var pname= pidname(lrpid);
footer = '<p>'+pname+' '+_('last ran station')+' '+window.controller.stations.snames[window.controller.settings.lrun[0]]+' '+_('for')+' '+(lrdur/60>>0)+'m '+(lrdur%60)+'s '+_('on')+' '+dateToString(new Date(window.controller.settings.lrun[3]*1000))+'</p>';
}
if (ptotal > 1) {
var scheduled = allPnames.length;
if (!open && scheduled) runningTotal.d = window.controller.options.sdt;
if (open == 1) ptotal += (scheduled-1)*window.controller.options.sdt;
allPnames = getUnique($.grep(allPnames,function(n){return(n);}));
var numProg = allPnames.length;
allPnames = allPnames.join(" "+_("and")+" ");
var pinfo = allPnames+" "+((numProg > 1) ? _("are") : _("is"))+" "+_("running")+" ";
pinfo += "<br><span id='countdown-p' class='nobr'>("+sec2hms(ptotal)+" "+_("remaining")+")</span>";
runningTotal.p = ptotal;
header += "<br>"+pinfo;
} else if (window.controller.settings.rd) {
header +="<br>"+_("Rain delay until")+" "+dateToString(new Date(window.controller.settings.rdst*1000));
} else if (window.controller.options.urs && window.controller.settings.rs) {
header +="<br>"+_("Rain detected");
}
$("#status .ui-content").append(
$('<p class="smaller center"></p>').html(header),
$('<ul data-role="listview" data-inset="true" id="status_list"></ul>').html(list).listview(),
$('<p class="smaller center"></p>').html(footer)
);
removeTimers();
$("#status").one("pagehide",function(){
removeTimers();
var page = $(this);
page.find(".ui-header > .ui-btn-right").off("click");
page.find(".ui-content").empty();
});
if (runningTotal.d !== undefined) {
delete runningTotal.p;
setTimeout(refresh_status,runningTotal.d*1000);
}
lastCheck = new Date().getTime();
window.interval_id = setInterval(function(){
var now = new Date().getTime(),
page = $(".ui-page-active").attr("id"),
diff = now - lastCheck;
if (diff > 3000) {
clearInterval(window.interval_id);
if (page == "status") refresh_status();
}
lastCheck = now;
$.each(runningTotal,function(a,b){
if (b <= 0) {
delete runningTotal[a];
if (a == "p") {
if (page == "status") {
refresh_status();
} else {
clearInterval(window.interval_id);
return;
}
} else {
$("#countdown-"+a).parent("p").text(_("Station delay")).parent("li").removeClass("green").addClass("red");
window.timeout_id = setTimeout(refresh_status,window.controller.options.sdt*1000);
}
} else {
if (a == "c") {
++runningTotal[a];
$("#clock-s").text(dateToString(new Date(runningTotal[a]*1000)));
} else {
--runningTotal[a];
$("#countdown-"+a).text("(" + sec2hms(runningTotal[a]) + " "+_("remaining")+")");
}
}
});
},1000);
}
function refresh_status() {
$.when(
update_controller_status(),
update_controller_settings()
).then(function(){
var page = $(".ui-page-active").attr("id");
if (page == "status") {
get_status();
} else if (page == "sprinklers") {
removeTimers();
check_status();
}
return;
},network_fail);
}
function removeTimers() {
//Remove any status timers that may be running
if (window.interval_id !== undefined) clearInterval(window.interval_id);
if (window.timeout_id !== undefined) clearTimeout(window.timeout_id);
}
// Actually change the status bar
function change_status(seconds,sdelay,color,line,onclick) {
var footer = $("#footer-running");
onclick = onclick || function(){};
removeTimers();
if (seconds > 1) update_timer(seconds,sdelay);
footer.removeClass().addClass(color).html(line).off("click").on("click",onclick).slideDown();
}
// Update status bar based on device status
function check_status() {
var open, ptotal, sample, pid, pname, line, match, tmp, i;
// Handle operation disabled
if (!window.controller.settings.en) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("System Disabled")+"</p>",function(){
areYouSure(_("Do you want to re-enable system operation?"),"",function(){
showLoading("#footer-running");
send_to_os("/cv?pw=&en=1").done(function(){
update_controller(check_status);
});
});
});
return;
}
// Handle open stations
open = {};
for (i=0; i<window.controller.status.length; i++) {
if (window.controller.status[i]) open[i] = window.controller.status[i];
}
if (window.controller.options.mas) delete open[window.controller.options.mas-1];
// Handle more than 1 open station
if (Object.keys(open).length >= 2) {
ptotal = 0;
for (i in open) {
if (open.hasOwnProperty(i)) {
tmp = window.controller.settings.ps[i][1];
if (tmp > ptotal) ptotal = tmp;
}
}
sample = Object.keys(open)[0];
pid = window.controller.settings.ps[sample][0];
pname = pidname(pid);
line = "<div id='running-icon'></div><p id='running-text'>";
line += pname+" "+_("is running on")+" "+Object.keys(open).length+" "+_("stations")+" ";
if (pid!=255&&pid!=99) line += "<span id='countdown' class='nobr'>("+sec2hms(ptotal)+" "+_("remaining")+")</span>";
line += "</p>";
change_status(ptotal,window.controller.options.sdt,"green",line,function(){
changePage("#status");
});
return;
}
// Handle a single station open
match = false;
for (i=0; i<window.controller.stations.snames.length; i++) {
if (window.controller.settings.ps[i][0] && window.controller.status[i] && window.controller.options.mas != i+1) {
match = true;
pid = window.controller.settings.ps[i][0];
pname = pidname(pid);
line = "<div id='running-icon'></div><p id='running-text'>";
line += pname+" "+_("is running on station")+" <span class='nobr'>"+window.controller.stations.snames[i]+"</span> ";
if (pid!=255&&pid!=99) line += "<span id='countdown' class='nobr'>("+sec2hms(window.controller.settings.ps[i][1])+" "+_("remaining")+")</span>";
line += "</p>";
break;
}
}
if (match) {
change_status(window.controller.settings.ps[i][1],window.controller.options.sdt,"green",line,function(){
changePage("#status");
});
return;
}
// Handle rain delay enabled
if (window.controller.settings.rd) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("Rain delay until")+" "+dateToString(new Date(window.controller.settings.rdst*1000))+"</p>",function(){
areYouSure(_("Do you want to turn off rain delay?"),"",function(){
showLoading("#footer-running");
send_to_os("/cv?pw=&rd=0").done(function(){
update_controller(check_status);
});
});
});
return;
}
// Handle rain sensor triggered
if (window.controller.options.urs && window.controller.settings.rs) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("Rain detected")+"</p>");
return;
}
// Handle manual mode enabled
if (window.controller.settings.mm) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("Manual mode enabled")+"</p>",function(){
areYouSure(_("Do you want to turn off manual mode?"),"",function(){
showLoading("#footer-running");
send_to_os("/cv?pw=&mm=0").done(function(){
update_controller(check_status);
});
});
});
return;
}
$("#footer-running").slideUp();
}
// Handle timer update on the home page for the status bar
function update_timer(total,sdelay) {
window.lastCheck = new Date().getTime();
window.interval_id = setInterval(function(){
var now = new Date().getTime();
var diff = now - window.lastCheck;
if (diff > 3000) {
clearInterval(window.interval_id);
showLoading("#footer-running");
update_controller(check_status);
}
window.lastCheck = now;
if (total <= 0) {
clearInterval(window.interval_id);
showLoading("#footer-running");
if (window.timeout_id !== undefined) clearTimeout(window.timeout_id);
window.timeout_id = setTimeout(function(){
update_controller(check_status);
},(sdelay*1000));
}
else
--total;
$("#countdown").text("(" + sec2hms(total) + " "+_("remaining")+")");
},1000);
}
// Manual control functions
function get_manual() {
var list = "<li data-role='list-divider' data-theme='a'>"+_("Sprinkler Stations")+"</li>",
page = $("#manual");
$.each(window.controller.stations.snames,function (i,station) {
if (window.controller.options.mas == i+1) {
list += '<li data-icon="false" class="center">'+station+' ('+_('Master')+')</li>';
} else {
list += '<li data-icon="false"><a class="mm_station center'+((window.controller.status[i]) ? ' green' : '')+'">'+station+'</a></li>';
}
});
page.find(".ui-content").append(
'<p class="center">'+_('With manual mode turned on, tap a station to toggle it.')+'</p>',
$('<ul data-role="listview" data-inset="true">'+
'<li class="ui-field-contain">'+
'<label for="mmm"><b>'+_('Manual Mode')+'</b></label>'+
'<input type="checkbox" data-on-text="On" data-off-text="Off" data-role="flipswitch" name="mmm" id="mmm"'+(window.controller.settings.mm ? ' checked' : '')+'>'+
'</li>'+
'</ul>').listview(),
$('<ul data-role="listview" data-inset="true" id="mm_list"></ul>').html(list).listview()
);
page.find("#mm_list").find(".mm_station").on("click",toggle);
page.find("#mmm").flipswitch().on("change",flipSwitched);
page.one("pagehide",function(){
page.find(".ui-content").empty();
});
}
function toggle() {
if (!window.controller.settings.mm) {
showerror(_("Manual mode is not enabled. Please enable manual mode then try again."));
return false;
}
var anchor = $(this),
list = $("#mm_list"),
listitems = list.children("li:not(li.ui-li-divider)"),
item = anchor.closest("li:not(li.ui-li-divider)"),
currPos = listitems.index(item) + 1;
if (anchor.hasClass("green")) {
send_to_os("/sn"+currPos+"=0").then(
function(){
update_controller_status();
},
function(){
anchor.addClass("green");
}
);
anchor.removeClass("green");
} else {
send_to_os("/sn"+currPos+"=1&t=0").then(
function(){
update_controller_status();
},
function(){
anchor.removeClass("green");
}
);
anchor.addClass("green");
}
return false;
}
// Runonce functions
function get_runonce() {
var list = "<p class='center'>"+_("Zero value excludes the station from the run-once program.")+"</p>",
runonce = $("#runonce_list"),
page = $("#runonce"),
i=0, n=0,
quickPick, data, progs, rprogs, z, program;
page.find("div[data-role='header'] > .ui-btn-right").on("click",submit_runonce);
progs = [];
if (window.controller.programs.pd.length) {
for (z=0; z < window.controller.programs.pd.length; z++) {
program = read_program(window.controller.programs.pd[z]);
var prog = [],
set_stations = program.stations.split("");
for (i=0;i<window.controller.stations.snames.length;i++) {
prog.push((parseInt(set_stations[i])) ? program.duration : 0);
}
progs.push(prog);
}
}
rprogs = progs;
quickPick = "<select data-mini='true' name='rprog' id='rprog'><option value='s' selected='selected'>"+_("Quick Programs")+"</option>";
data = localStorage.getItem("runonce");
if (data !== null) {
data = JSON.parse(data);
runonce.find(":input[data-type='range']").each(function(a,b){
$(b).val(data[i]/60);
i++;
});
rprogs.l = data;
quickPick += "<option value='l' >"+_("Last Used Program")+"</option>";
}
for (i=0; i<progs.length; i++) {
quickPick += "<option value='"+i+"'>"+_("Program")+" "+(i+1)+"</option>";
}
quickPick += "</select>";
list += quickPick+"<form>";
$.each(window.controller.stations.snames,function(i, station) {
list += "<div class='ui-field-contain duration-input'><label for='zone-"+n+"'>"+station+":</label><button data-mini='true' name='zone-"+n+"' id='zone-"+n+"' value='0'>0s</button></div>";
n++;
});
list += "</form><a class='ui-btn ui-corner-all ui-shadow rsubmit' href='#'>"+_("Submit")+"</a><a class='ui-btn ui-btn-b ui-corner-all ui-shadow rreset' href='#'>"+_("Reset")+"</a>";
runonce.html(list);
$("#rprog").on("change",function(){
var prog = $(this).val();
if (prog == "s") {
reset_runonce();
return;
}
if (typeof rprogs[prog] === "undefined") return;
fill_runonce(rprogs[prog]);
});
runonce.on("click",".rsubmit",submit_runonce).on("click",".rreset",reset_runonce);
runonce.find("[id^='zone-']").on("click",function(){
var dur = $(this),
name = runonce.find("label[for='"+dur.attr("id")+"']").text().slice(0,-1);
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
if (result > 0) {
dur.addClass("green");
} else {
dur.removeClass("green");
}
},65535);
return false;
});
runonce.enhanceWithin();
page.one("pagehide",function(){
page.find(".ui-header > .ui-btn-right").off("click");
$(this).find(".ui-content").empty();
});
}
function reset_runonce() {
$("#runonce").find("[id^='zone-']").val(0).text("0s").removeClass("green");
return false;
}
function fill_runonce(data){
var i=0;
$("#runonce").find("[id^='zone-']").each(function(a,b){
var ele = $(b);
ele.val(data[i]).text(dhms2str(sec2dhms(data[i])));
if (data[i] > 0) {
ele.addClass("green");
} else {
ele.removeClass("green");
}
i++;
});
}
function submit_runonce(runonce) {
if (!(runonce instanceof Array)) {
runonce = [];
$("#runonce").find("[id^='zone-']").each(function(a,b){
runonce.push(parseInt($(b).val()));
});
runonce.push(0);
}
storage.set({"runonce":JSON.stringify(runonce)});
send_to_os("/cr?pw=&t="+JSON.stringify(runonce)).done(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Run-once program has been scheduled"));
});
update_controller_status();
update_controller_settings();
window.history.back();
});
}
// Preview functions
function get_preview() {
var date = $("#preview_date").val(),
$timeline = $("#timeline"),
preview_data, process_programs, check_match, run_sched, time_to_text, day;
if (date === "") return;
date = date.split("-");
day = new Date(date[0],date[1]-1,date[2]);
$.mobile.loading("show");
$("#timeline-navigation").hide();
process_programs = function (month,day,year) {
preview_data = [];
var devday = Math.floor(window.controller.settings.devt/(60*60*24)),
simminutes = 0,
simt = Date.UTC(year,month-1,day,0,0,0,0),
simday = (simt/1000/3600/24)>>0,
st_array = new Array(window.controller.settings.nbrd*8),
pid_array = new Array(window.controller.settings.nbrd*8),
et_array = new Array(window.controller.settings.nbrd*8),
busy, match_found, prog;
for(var sid=0;sid<window.controller.settings.nbrd;sid++) {
st_array[sid]=0;pid_array[sid]=0;et_array[sid]=0;
}
do {
busy=0;
match_found=0;
for(var pid=0;pid<window.controller.programs.pd.length;pid++) {
prog=window.controller.programs.pd[pid];
if(check_match(prog,simminutes,simt,simday,devday)) {
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {
var bid=sid>>3;var s=sid%8;
if(window.controller.options.mas==(sid+1)) continue; // skip master station
if(prog[7+bid]&(1<<s)) {
et_array[sid]=prog[6]*window.controller.options.wl/100>>0;pid_array[sid]=pid+1;
match_found=1;
}
}
}
}
if(match_found) {
var acctime=simminutes*60;
if(window.controller.options.seq) {
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {
if(et_array[sid]) {
st_array[sid]=acctime;acctime+=et_array[sid];
et_array[sid]=acctime;acctime+=window.controller.options.sdt;
busy=1;
}
}
} else {
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {
if(et_array[sid]) {
st_array[sid]=simminutes*60;
et_array[sid]=simminutes*60+et_array[sid];
busy=1;
}
}
}
}
if (busy) {
var endminutes=run_sched(simminutes*60,st_array,pid_array,et_array,simt)/60>>0;
if(window.controller.options.seq&&simminutes!=endminutes) simminutes=endminutes;
else simminutes++;
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {st_array[sid]=0;pid_array[sid]=0;et_array[sid]=0;}
} else {
simminutes++;
}
} while(simminutes<24*60);
};
check_match = function (prog,simminutes,simt,simday,devday) {
if(prog[0]===0) return 0;
if ((prog[1]&0x80)&&(prog[2]>1)) {
var dn=prog[2],
drem=prog[1]&0x7f;
if((simday%dn)!=((devday+drem)%dn)) return 0;
} else {
var date = new Date(simt);
var wd=(date.getUTCDay()+6)%7;
if((prog[1]&(1<<wd))===0) return 0;
var dt=date.getUTCDate();
if((prog[1]&0x80)&&(prog[2]===0)) {if((dt%2)!==0) return 0;}
if((prog[1]&0x80)&&(prog[2]==1)) {
if(dt==31) return 0;
else if (dt==29 && date.getUTCMonth()==1) return 0;
else if ((dt%2)!=1) return 0;
}
}
if(simminutes<prog[3] || simminutes>prog[4]) return 0;
if(prog[5]===0) return 0;
if(((simminutes-prog[3])/prog[5]>>0)*prog[5] == (simminutes-prog[3])) {
return 1;
}
return 0;
};
run_sched = function (simseconds,st_array,pid_array,et_array,simt) {
var endtime=simseconds;
for(var sid=0;sid<window.controller.settings.nbrd*8;sid++) {
if(pid_array[sid]) {
if(window.controller.options.seq==1) {
if((window.controller.options.mas>0)&&(window.controller.options.mas!=sid+1)&&(window.controller.stations.masop[sid>>3]&(1<<(sid%8))))
preview_data.push({
'start': (st_array[sid]+window.controller.options.mton),
'end': (et_array[sid]+window.controller.options.mtof),
'content':'',
'className':'master',
'shortname':'M',
'group':'Master'
});
time_to_text(sid,st_array[sid],pid_array[sid],et_array[sid],simt);
endtime=et_array[sid];
} else {
time_to_text(sid,simseconds,pid_array[sid],et_array[sid],simt);
if((window.controller.options.mas>0)&&(window.controller.options.mas!=sid+1)&&(window.controller.stations.masop[sid>>3]&(1<<(sid%8))))
endtime=(endtime>et_array[sid])?endtime:et_array[sid];
}
}
}
if(window.controller.options.seq===0&&window.controller.options.mas>0) {
preview_data.push({
'start': simseconds,
'end': endtime,
'content':'',
'className':'master',
'shortname':'M',
'group':'Master'
});
}
return endtime;
};
time_to_text = function (sid,start,pid,end,simt) {
var className = "program-"+((pid+3)%4);
if ((window.controller.settings.rd!==0)&&(simt+start+(window.controller.options.tz-48)*900<=window.controller.settings.rdst)) className="delayed";
preview_data.push({
'start': start,
'end': end,
'className':className,
'content':'P'+pid,
'shortname':'S'+(sid+1),
'group': window.controller.stations.snames[sid]
});
};
process_programs(date[1],date[2],date[0]);
var empty = true;
if (!preview_data.length) {
$timeline.html("<p align='center'>"+_("No stations set to run on this day.")+"</p>");
} else {
empty = false;
var shortnames = [];
$.each(preview_data, function(){
this.start = new Date(date[0],date[1]-1,date[2],0,0,this.start);
this.end = new Date(date[0],date[1]-1,date[2],0,0,this.end);
shortnames[this.group] = this.shortname;
});
var options = {
'width': '100%',
'editable': false,
'axisOnTop': true,
'eventMargin': 10,
'eventMarginAxis': 0,
'min': new Date(date[0],date[1]-1,date[2],0),
'max': new Date(date[0],date[1]-1,date[2],24),
'selectable': true,
'showMajorLabels': false,
'zoomMax': 1000 * 60 * 60 * 24,
'zoomMin': 1000 * 60 * 60,
'groupsChangeable': false,
'showNavigation': false,
'groupsOrder': 'none',
'groupMinHeight': 20
};
var timeline = new links.Timeline(document.getElementById('timeline'),options);
links.events.addListener(timeline, "select", function(){
var row,
sel = timeline.getSelection();
if (sel.length) {
if (typeof sel[0].row !== "undefined") {
row = sel[0].row;
}
}
if (row === undefined) return;
var content = $(".timeline-event-content")[row];
var pid = parseInt($(content).html().substr(1)) - 1;
changePage("#programs",{
'programToExpand': pid
});
});
$.mobile.window.on("resize",function(){
timeline.redraw();
});
timeline.draw(preview_data);
if ($.mobile.window.width() <= 480) {
var currRange = timeline.getVisibleChartRange();
if ((currRange.end.getTime() - currRange.start.getTime()) > 6000000) timeline.setVisibleChartRange(currRange.start,new Date(currRange.start.getTime()+6000000));
}
$timeline.find(".timeline-groups-text").each(function(a,b){
var stn = $(b);
var name = shortnames[stn.text()];
stn.attr("data-shortname",name);
});
$(".timeline-groups-axis").children().first().html("<div class='timeline-axis-text center dayofweek' data-shortname='"+getDayName(day,"short")+"'>"+getDayName(day)+"</div>");
if (isAndroid) {
var navi = $("#timeline-navigation");
navi.find(".ui-icon-plus").off("click").on("click",function(){
timeline.zoom(0.4);
return false;
});
navi.find(".ui-icon-minus").off("click").on("click",function(){
timeline.zoom(-0.4);
return false;
});
navi.find(".ui-icon-carat-l").off("click").on("click",function(){
timeline.move(-0.2);
return false;
});
navi.find(".ui-icon-carat-r").off("click").on("click",function(){
timeline.move(0.2);
return false;
});
navi.show();
}
}
$.mobile.loading("hide");
}
function changeday(dir) {
var inputBox = $("#preview_date");
var date = inputBox.val();
if (date === "") return;
date = date.split("-");
var nDate = new Date(date[0],date[1]-1,date[2]);
nDate.setDate(nDate.getDate() + dir);
var m = pad(nDate.getMonth()+1);
var d = pad(nDate.getDate());
inputBox.val(nDate.getFullYear() + "-" + m + "-" + d);
get_preview();
}
// Logging functions
function get_logs() {
var logs = $("#logs"),
placeholder = $("#placeholder"),
logs_list = $("#logs_list"),
zones = $("#zones"),
graph_sort = $("#graph_sort"),
log_options = $("#log_options"),
data = [],
seriesChange = function() {
var grouping = logs.find("input:radio[name='g']:checked").val(),
pData = [],
sortedData;
sortedData = sortData(grouping);
zones.find("td[zone_num]:not('.unchecked')").each(function() {
var key = $(this).attr("zone_num");
if (!sortedData[key].length) sortedData[key]=[[0,0]];
if (key && sortedData[key]) {
if ((grouping == 'h') || (grouping == 'm') || (grouping == 'd'))
pData.push({
data:sortedData[key],
label:$(this).attr("name"),
color:parseInt(key),
bars: { order:key, show: true, barWidth:0.08}
});
else if (grouping == 'n')
pData.push({
data:sortedData[key],
label:$(this).attr("name"),
color:parseInt(key),
lines: { show:true }
});
}
});
if (grouping=='h') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { min: 0, max: 24, tickDecimals: 0, tickSize: 1 }
});
} else if (grouping=='d') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { tickDecimals: 0, min: -0.4, max: 6.4,
tickFormatter: function(v) { var dow=[_("Sun"),_("Mon"),_("Tue"),_("Wed"),_("Thr"),_("Fri"),_("Sat")]; return dow[v]; } }
});
} else if (grouping=='m') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { tickDecimals: 0, min: 0.6, max: 12.4, tickSize: 1,
tickFormatter: function(v) { var mon=["",_("Jan"),_("Feb"),_("Mar"),_("Apr"),_("May"),_("Jun"),_("Jul"),_("Aug"),_("Sep"),_("Oct"),_("Nov"),_("Dec")]; return mon[v]; } }
});
} else if (grouping=='n') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { mode: "time", min:sortedData.min.getTime(), max:sortedData.max.getTime()}
});
}
},
sortData = function(grouping) {
var sortedData = [],
max, min;
switch (grouping) {
case "h":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0]];
}
break;
case "m":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]];
}
break;
case "d":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0]];
}
break;
case "n":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [];
}
break;
}
$.each(data,function(a,b){
var stamp = parseInt(b[3] * 1000),
station = parseInt(b[1]),
date = new Date(stamp),
duration = parseInt(b[2]/60),
key;
switch (grouping) {
case "h":
key = date.getUTCHours();
break;
case "m":
key = date.getUTCMonth() + 1;
break;
case "d":
key = date.getUTCDay();
break;
case "n":
sortedData[station].push([stamp-1,0]);
sortedData[station].push([stamp,duration]);
sortedData[station].push([stamp+(duration*100*1000)+1,0]);
break;
}
if (grouping != "n" && duration > 0) {
sortedData[station][key][1] += duration;
}
if (min === undefined || min > date) min = date;
if (max === undefined || max < date) max = new Date(date.getTime() + (duration*100*1000)+1);
});
sortedData.min = min;
sortedData.max = max;
return sortedData;
},
toggleZone = function() {
var zone = $(this);
if (zone.hasClass("legendColorBox")) {
zone.find("div div").toggleClass("hideZone");
zone.next().toggleClass("unchecked");
} else if (zone.hasClass("legendLabel")) {
zone.prev().find("div div").toggleClass("hideZone");
zone.toggleClass("unchecked");
}
seriesChange();
},
showArrows = function() {
var height = zones.height(),
sleft = zones.scrollLeft(),
right = $("#graphScrollRight"),
left = $("#graphScrollLeft");
if (sleft > 13) {
left.show().css("margin-top",(height/2)-12.5);
} else {
left.hide();
}
var total = zones.find("table").width(), container = zones.width();
if ((total-container) > 0 && sleft < ((total-container) - 13)) {
right.show().css({
"margin-top":(height/2)-12.5,
"left":container
});
} else {
right.hide();
}
},
success = function(items){
if (items.length < 1) {
$.mobile.loading("hide");
reset_logs_page();
return;
}
data = items;
updateView();
objToEmail(".email_logs",data);
$.mobile.loading("hide");
},
updateView = function() {
if ($("#log_graph").prop("checked")) {
prepGraph();
} else {
prepTable();
}
},
prepGraph = function() {
if (data.length < 1) {
reset_logs_page();
return;
}
logs_list.empty().hide();
var state = ($.mobile.window.height() > 680) ? "expand" : "collapse";
setTimeout(function(){log_options.collapsible(state);},100);
placeholder.show();
var zones = $("#zones");
var freshLoad = zones.find("table").length;
zones.show();
graph_sort.show();
if (!freshLoad) {
var output = '<div class="ui-btn ui-btn-icon-notext ui-icon-carat-l btn-no-border" id="graphScrollLeft"></div><div class="ui-btn ui-btn-icon-notext ui-icon-carat-r btn-no-border" id="graphScrollRight"></div><table class="smaller"><tbody><tr>';
for (i=0; i<window.controller.stations.snames.length; i++) {
output += '<td class="legendColorBox"><div><div></div></div></td><td id="z'+i+'" zone_num='+i+' name="'+window.controller.stations.snames[i] + '" class="legendLabel">'+window.controller.stations.snames[i]+'</td>';
}
output += '</tr></tbody></table>';
zones.empty().append(output).enhanceWithin();
zones.find("td").on("click",toggleZone);
zones.find("#graphScrollLeft,#graphScrollRight").on("click",scrollZone);
}
seriesChange();
i = 0;
if (!freshLoad) {
zones.find("td.legendColorBox div div").each(function(a,b){
var border = $(placeholder.find(".legendColorBox div div").get(i)).css("border");
//Firefox and IE fix
if (border === "") {
border = $(placeholder.find(".legendColorBox div div").get(i)).attr("style").split(";");
$.each(border,function(a,b){
var c = b.split(":");
if (c[0] == "border") {
border = c[1];
return false;
}
});
}
$(b).css("border",border);
i++;
});
showArrows();
}
},
prepTable = function(){
if (data.length < 1) {
reset_logs_page();
return;
}
placeholder.empty().hide();
var table_header = "<table><thead><tr><th data-priority='1'>"+_("Runtime")+"</th><th data-priority='2'>"+_("Date/Time")+"</th></tr></thead><tbody>",
html = "<div data-role='collapsible-set' data-inset='true' data-theme='b' data-collapsed-icon='arrow-d' data-expanded-icon='arrow-u'>",
sortedData = [],
ct, k;
zones.hide();
graph_sort.hide();
logs_list.show();
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [];
}
$.each(data,function(a,b){
sortedData[parseInt(b[1])].push([parseInt(b[3] * 1000),parseInt(b[2])]);
});
for (i=0; i<sortedData.length; i++) {
ct=sortedData[i].length;
if (ct === 0) continue;
html += "<div data-role='collapsible' data-collapsed='true'><h2><div class='ui-btn-up-c ui-btn-corner-all custom-count-pos'>"+ct+" "+((ct == 1) ? _("run") : _("runs"))+"</div>"+window.controller.stations.snames[i]+"</h2>"+table_header;
for (k=0; k<sortedData[i].length; k++) {
var mins = Math.round(sortedData[i][k][1]/60);
var date = new Date(sortedData[i][k][0]);
html += "<tr><td>"+mins+" "+((mins == 1) ? _("min") : _("mins"))+"</td><td>"+dateToString(date).slice(0,-3)+"</td></tr>";
}
html += "</tbody></table></div>";
}
log_options.collapsible("collapse");
logs_list.html(html+"</div>").enhanceWithin();
},
reset_logs_page = function() {
placeholder.empty().hide();
log_options.collapsible("expand");
zones.empty().hide();
graph_sort.hide();
logs_list.show().html(_("No entries found in the selected date range"));
},
fail = function(){
$.mobile.loading("hide");
reset_logs_page();
},
dates = function() {
var sDate = $("#log_start").val().split("-"),
eDate = $("#log_end").val().split("-");
return {
start: new Date(sDate[0],sDate[1]-1,sDate[2]),
end: new Date(eDate[0],eDate[1]-1,eDate[2])
};
},
parms = function() {
return "start=" + (dates().start.getTime() / 1000) + "&end=" + ((dates().end.getTime() / 1000) + 86340);
},
requestData = function() {
var endtime = dates().end.getTime() / 1000,
starttime = dates().start.getTime() / 1000;
if (endtime < starttime) {
fail();
showerror(_("Start time cannot be greater than end time"));
return;
}
var delay = 0;
$.mobile.loading("show");
if (!isOSPi() && (endtime - starttime) > 604800) {
showerror(_("The requested time span exceeds the maxiumum of 7 days and has been adjusted"),3500);
var nDate = dates().start;
nDate.setDate(nDate.getDate() + 7);
var m = pad(nDate.getMonth()+1);
var d = pad(nDate.getDate());
$("#log_end").val(nDate.getFullYear() + "-" + m + "-" + d);
delay = 500;
}
setTimeout(function(){
send_to_os("/jl?"+parms(),"json").then(success,fail);
},delay);
},
i;
logs.find("input").blur();
$.mobile.loading("show");
//Update left/right arrows when zones are scrolled on log page
$("#zones").scroll(showArrows);
$.mobile.window.resize(function(){
showArrows();
seriesChange();
});
//Automatically update the log viewer when changing the date range
if (isiOS) {
$("#log_start,#log_end").on("blur",requestData);
} else {
$("#log_start,#log_end").change(function(){
clearTimeout(window.logtimeout);
window.logtimeout = setTimeout(requestData,1000);
});
}
//Automatically update log viewer when switching graphing method
graph_sort.find("input[name='g']").change(seriesChange);
//Bind refresh button
logs.find(".ui-header > .ui-btn-right").on("click",requestData);
//Bind view change buttons
logs.find("input:radio[name='log_type']").change(updateView);
//Show tooltip (station name) when point is clicked on the graph
placeholder.on("plothover",function(event, pos, item) {
$("#tooltip").remove();
clearTimeout(window.hovertimeout);
if (item) window.hovertimeout = setTimeout(function(){showTooltip(item.pageX, item.pageY, item.series.label, item.series.color);}, 100);
});
logs.one("pagehide",function(){
$.mobile.window.off("resize");
placeholder.off("plothover");
zones.off("scroll");
logs.off("change");
$("#log_start,#log_end").off("change");
logs.find(".ui-header > .ui-btn-right").off("change");
logs.find("input:radio[name='log_type']").off("change");
graph_sort.find("input[name='g']").off("change");
reset_logs_page();
});
requestData();
}
function scrollZone() {
var dir = ($(this).attr("id") == "graphScrollRight") ? "+=" : "-=";
var zones = $("#zones");
var w = zones.width();
zones.animate({scrollLeft: dir+w});
}
// Program management functions
function get_programs(pid) {
var programs = $("#programs"),
list = programs.find(".ui-content");
list.html($(make_all_programs())).enhanceWithin();
programs.find(".ui-collapsible-set").collapsibleset().on({
collapsiblecollapse: function(){
$(this).find(".ui-collapsible-content").empty();
},
collapsibleexpand: function(){
expandProgram($(this));
}
},".ui-collapsible");
update_program_header();
programs
.one("pagehide",function(){
$(this).find(".ui-content").empty();
})
.one("pagebeforeshow",function(){
if (typeof pid !== "number" && window.controller.programs.pd.length === 1) pid = 0;
if (typeof pid === "number") {
programs.find("fieldset[data-collapsed='false']").collapsible("collapse");
$("#program-"+pid).collapsible("expand");
}
});
}
function expandProgram(program) {
var id = parseInt(program.attr("id").split("-")[1]),
html = $(make_program(id));
program.find(".ui-collapsible-content").html(html).enhanceWithin();
program.find("input[name^='rad_days']").on("change",function(){
var progid = $(this).attr('id').split("-")[1], type = $(this).val().split("-")[0], old;
type = type.split("_")[1];
if (type == "n") {
old = "week";
} else {
old = "n";
}
$("#input_days_"+type+"-"+progid).show();
$("#input_days_"+old+"-"+progid).hide();
});
program.find("[id^='submit-']").on("click",function(){
submit_program($(this).attr("id").split("-")[1]);
return false;
});
program.find("[id^='duration-'],[id^='interval-']").on("click",function(){
var dur = $(this),
granularity = dur.attr("id").match("interval") ? 1 : 0,
name = program.find("label[for='"+dur.attr("id")+"']").text();
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
},65535,granularity);
return false;
});
program.find("[id^='s_checkall-']").on("click",function(){
var id = $(this).attr("id").split("-")[1];
program.find("[id^='station_'][id$='-"+id+"']").prop("checked",true).checkboxradio("refresh");
return false;
});
program.find("[id^='s_uncheckall-']").on("click",function(){
var id = $(this).attr("id").split("-")[1];
program.find("[id^='station_'][id$='-"+id+"']").prop("checked",false).checkboxradio("refresh");
return false;
});
program.find("[id^='delete-']").on("click",function(){
delete_program($(this).attr("id").split("-")[1]);
return false;
});
program.find("[id^='run-']").on("click",function(){
var id = $(this).attr("id").split("-")[1],
durr = parseInt($("#duration-"+id).val()),
stations = $("[id^='station_'][id$='-"+id+"']"),
runonce = [];
$.each(stations,function(a,b){
if ($(b).is(":checked")) {
runonce.push(durr);
} else {
runonce.push(0);
}
});
runonce.push(0);
submit_runonce(runonce);
return false;
});
fixInputClick(program);
}
// Translate program array into easier to use data
function read_program(program) {
var days0 = program[1],
days1 = program[2],
even = false,
odd = false,
interval = false,
days = "",
stations = "",
newdata = {};
newdata.en = program[0];
newdata.start = program[3];
newdata.end = program[4];
newdata.interval = program[5];
newdata.duration = program[6];
for (var n=0; n < window.controller.programs.nboards; n++) {
var bits = program[7+n];
for (var s=0; s < 8; s++) {
stations += (bits&(1<<s)) ? "1" : "0";
}
}
newdata.stations = stations;
if((days0&0x80)&&(days1>1)){
//This is an interval program
days=[days1,days0&0x7f];
interval = true;
} else {
//This is a weekly program
for(var d=0;d<7;d++) {
if (days0&(1<<d)) {
days += "1";
} else {
days += "0";
}
}
if((days0&0x80)&&(days1===0)) {even = true;}
if((days0&0x80)&&(days1==1)) {odd = true;}
}
newdata.days = days;
newdata.is_even = even;
newdata.is_odd = odd;
newdata.is_interval = interval;
return newdata;
}
// Translate program ID to it's name
function pidname(pid) {
var pname = _("Program")+" "+pid;
if(pid==255||pid==99) pname=_("Manual program");
if(pid==254||pid==98) pname=_("Run-once program");
return pname;
}
// Check each program and change the background color to red if disabled
function update_program_header() {
$("#programs_list").find("[id^=program-]").each(function(a,b){
var item = $(b),
heading = item.find(".ui-collapsible-heading-toggle"),
en = window.controller.programs.pd[a][0];
if (en) {
heading.removeClass("red");
} else {
heading.addClass("red");
}
});
}
//Make the list of all programs
function make_all_programs() {
if (window.controller.programs.pd.length === 0) {
return "<p class='center'>"+_("You have no programs currently added. Tap the Add button on the top right corner to get started.")+"</p>";
}
var list = "<p class='center'>"+_("Click any program below to expand/edit. Be sure to save changes by hitting submit below.")+"</p><div data-role='collapsible-set'>";
for (var i = 0; i < window.controller.programs.pd.length; i++) {
list += "<fieldset id='program-"+i+"' data-role='collapsible'><legend>"+_("Program")+" "+(i+1)+"</legend>";
list += "</fieldset>";
}
return list+"</div>";
}
//Generate a new program view
function fresh_program() {
var list = "<fieldset id='program-new'>";
list +=make_program("new");
list += "</fieldset>";
return list;
}
function make_program(n) {
var week = [_("M"),_("T"),_("W"),_("R"),_("F"),_("Sa"),_("Su")],
list = "",
days, i, j, set_stations, program;
if (n === "new") {
program = {"en":0,"is_interval":0,"is_even":0,"is_odd":0,"duration":0,"interval":0,"start":0,"end":0,"days":[0,0]};
} else {
program = read_program(window.controller.programs.pd[n]);
}
if (typeof program.days === "string") {
days = program.days.split("");
for(i=days.length;i--;) days[i] = days[i]|0;
} else {
days = [0,0,0,0,0,0,0];
}
if (typeof program.stations !== "undefined") {
set_stations = program.stations.split("");
for(i=set_stations.length;i--;) set_stations[i] = set_stations[i]|0;
}
list += "<label for='en-"+n+"'><input data-mini='true' type='checkbox' "+((program.en || n==="new") ? "checked='checked'" : "")+" name='en-"+n+"' id='en-"+n+"'>"+_("Enabled")+"</label>";
list += "<fieldset data-role='controlgroup' data-type='horizontal' class='center'>";
list += "<input data-mini='true' type='radio' name='rad_days-"+n+"' id='days_week-"+n+"' value='days_week-"+n+"' "+((program.is_interval) ? "" : "checked='checked'")+"><label for='days_week-"+n+"'>"+_("Weekly")+"</label>";
list += "<input data-mini='true' type='radio' name='rad_days-"+n+"' id='days_n-"+n+"' value='days_n-"+n+"' "+((program.is_interval) ? "checked='checked'" : "")+"><label for='days_n-"+n+"'>"+_("Interval")+"</label>";
list += "</fieldset><div id='input_days_week-"+n+"' "+((program.is_interval) ? "style='display:none'" : "")+">";
list += "<fieldset data-role='controlgroup' data-type='horizontal' class='center'><p class='tight'>"+_("Restrictions")+"</p>";
list += "<input data-mini='true' type='radio' name='rad_rst-"+n+"' id='days_norst-"+n+"' value='days_norst-"+n+"' "+((!program.is_even && !program.is_odd) ? "checked='checked'" : "")+"><label for='days_norst-"+n+"'>"+_("None")+"</label>";
list += "<input data-mini='true' type='radio' name='rad_rst-"+n+"' id='days_odd-"+n+"' value='days_odd-"+n+"' "+((!program.is_even && program.is_odd) ? "checked='checked'" : "")+"><label for='days_odd-"+n+"'>"+_("Odd Days")+"</label>";
list += "<input data-mini='true' type='radio' name='rad_rst-"+n+"' id='days_even-"+n+"' value='days_even-"+n+"' "+((!program.is_odd && program.is_even) ? "checked='checked'" : "")+"><label for='days_even-"+n+"'>"+_("Even Days")+"</label>";
list += "</fieldset>";
list += "<fieldset data-type='horizontal' data-role='controlgroup' class='center'><p class='tight'>"+_("Days of the Week")+"</p>";
for (j=0; j<week.length; j++) {
list += "<label for='d"+j+"-"+n+"'><input data-mini='true' type='checkbox' "+((!program.is_interval && days[j]) ? "checked='checked'" : "")+" name='d"+j+"-"+n+"' id='d"+j+"-"+n+"'>"+week[j]+"</label>";
}
list += "</fieldset></div>";
list += "<div "+((program.is_interval) ? "" : "style='display:none'")+" id='input_days_n-"+n+"' class='ui-grid-a'>";
list += "<div class='ui-block-a'><label for='every-"+n+"'>"+_("Interval (Days)")+"</label><input data-mini='true' type='number' name='every-"+n+"' pattern='[0-9]*' id='every-"+n+"' value='"+program.days[0]+"'></div>";
list += "<div class='ui-block-b'><label for='starting-"+n+"'>"+_("Starting In")+"</label><input data-mini='true' type='number' name='starting-"+n+"' pattern='[0-9]*' id='starting-"+n+"' value='"+program.days[1]+"'></div>";
list += "</div>";
list += "<fieldset data-role='controlgroup'><legend>"+_("Stations:")+"</legend>";
for (j=0; j<window.controller.stations.snames.length; j++) {
list += "<label for='station_"+j+"-"+n+"'><input data-mini='true' type='checkbox' "+(((typeof set_stations !== "undefined") && set_stations[j]) ? "checked='checked'" : "")+" name='station_"+j+"-"+n+"' id='station_"+j+"-"+n+"'>"+window.controller.stations.snames[j]+"</label>";
}
list += "</fieldset>";
list += "<fieldset data-role='controlgroup' data-type='horizontal' class='center'>";
list += "<a class='ui-btn ui-mini' name='s_checkall-"+n+"' id='s_checkall-"+n+"'>"+_("Check All")+"</a>";
list += "<a class='ui-btn ui-mini' name='s_uncheckall-"+n+"' id='s_uncheckall-"+n+"'>"+_("Uncheck All")+"</a>";
list += "</fieldset>";
list += "<div class='ui-grid-a'>";
list += "<div class='ui-block-a'><label for='start-"+n+"'>"+_("Start Time")+"</label><input data-mini='true' type='time' name='start-"+n+"' id='start-"+n+"' value='"+pad(parseInt(program.start/60)%24)+":"+pad(program.start%60)+"'></div>";
list += "<div class='ui-block-b'><label for='end-"+n+"'>"+_("End Time")+"</label><input data-mini='true' type='time' name='end-"+n+"' id='end-"+n+"' value='"+pad(parseInt(program.end/60)%24)+":"+pad(program.end%60)+"'></div>";
list += "</div>";
list += "<div class='ui-grid-a'>";
list += "<div class='ui-block-a'><label for='duration-"+n+"'>"+_("Station Duration")+"</label><button data-mini='true' name='duration-"+n+"' id='duration-"+n+"' value='"+program.duration+"'>"+dhms2str(sec2dhms(program.duration))+"</button></div>";
list += "<div class='ui-block-b'><label for='interval-"+n+"'>"+_("Program Interval")+"</label><button data-mini='true' name='interval-"+n+"' id='interval-"+n+"' value='"+program.interval*60+"'>"+dhms2str(sec2dhms(program.interval*60))+"</button></div>";
list += "</div>";
if (n === "new") {
list += "<input data-mini='true' type='submit' name='submit-"+n+"' id='submit-"+n+"' value='"+_("Save New Program")+"'>";
} else {
list += "<input data-mini='true' type='submit' name='submit-"+n+"' id='submit-"+n+"' value='"+_("Save Changes to Program")+" "+(n + 1)+"'>";
list += "<input data-mini='true' type='submit' name='run-"+n+"' id='run-"+n+"' value='"+_("Run Program")+" "+(n + 1)+"'>";
list += "<input data-mini='true' data-theme='b' type='submit' name='delete-"+n+"' id='delete-"+n+"' value='"+_("Delete Program")+" "+(n + 1)+"'>";
}
return list;
}
function add_program() {
var addprogram = $("#addprogram"),
list = addprogram.find(".ui-content");
list.html($(fresh_program())).enhanceWithin();
addprogram.find("div[data-role='header'] > .ui-btn-right").on("click",function(){
submit_program("new");
});
addprogram.find("input[name^='rad_days']").on("change",function(){
var progid = "new", type = $(this).val().split("-")[0], old;
type = type.split("_")[1];
if (type == "n") {
old = "week";
} else {
old = "n";
}
$("#input_days_"+type+"-"+progid).show();
$("#input_days_"+old+"-"+progid).hide();
});
addprogram.find("[id^='s_checkall-']").on("click",function(){
addprogram.find("[id^='station_'][id$='-new']").prop("checked",true).checkboxradio("refresh");
return false;
});
addprogram.find("[id^='s_uncheckall-']").on("click",function(){
addprogram.find("[id^='station_'][id$='-new']").prop("checked",false).checkboxradio("refresh");
return false;
});
addprogram.find("[id^='submit-']").on("click",function(){
submit_program("new");
return false;
});
addprogram.find("[id^='duration-'],[id^='interval-']").on("click",function(){
var dur = $(this),
granularity = dur.attr("id").match("interval") ? 1 : 0,
name = addprogram.find("label[for='"+dur.attr("id")+"']").text();
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
},65535,granularity);
return false;
});
addprogram.one("pagehide",function() {
addprogram.find(".ui-header > .ui-btn-right").off("click");
$(this).find(".ui-content").empty();
});
}
function delete_program(id) {
areYouSure(_("Are you sure you want to delete program")+" "+(parseInt(id)+1)+"?", "", function() {
$.mobile.loading("show");
send_to_os("/dp?pw=&pid="+id).done(function(){
$.mobile.loading("hide");
update_controller_programs(function(){
get_programs(false);
});
});
});
}
function submit_program(id) {
var program = [],
days=[0,0],
i, s;
program[0] = ($("#en-"+id).is(':checked')) ? 1 : 0;
if($("#days_week-"+id).is(':checked')) {
for(i=0;i<7;i++) {if($("#d"+i+"-"+id).is(':checked')) {days[0] |= (1<<i); }}
if($("#days_odd-"+id).is(':checked')) {days[0]|=0x80; days[1]=1;}
else if($("#days_even-"+id).is(':checked')) {days[0]|=0x80; days[1]=0;}
} else if($("#days_n-"+id).is(':checked')) {
days[1]=parseInt($("#every-"+id).val(),10);
if(!(days[1]>=2&&days[1]<=128)) {showerror(_("Error: Interval days must be between 2 and 128."));return;}
days[0]=parseInt($("#starting-"+id).val(),10);
if(!(days[0]>=0&&days[0]<days[1])) {showerror(_("Error: Starting in days wrong."));return;}
days[0]|=0x80;
}
program[1] = days[0];
program[2] = days[1];
var start = $("#start-"+id).val().split(":");
program[3] = parseInt(start[0])*60+parseInt(start[1]);
var end = $("#end-"+id).val().split(":");
program[4] = parseInt(end[0])*60+parseInt(end[1]);
if(program[3]>program[4]) {showerror(_("Error: Start time must be prior to end time."));return;}
program[5] = parseInt($("#interval-"+id).val()/60);
program[6] = parseInt($("#duration-"+id).val());
var sel = $("[id^=station_][id$=-"+id+"]"),
total = sel.length,
nboards = total / 8;
var stations=[0],station_selected=0,bid, sid;
for(bid=0;bid<nboards;bid++) {
stations[bid]=0;
for(s=0;s<8;s++) {
sid=bid*8+s;
if($("#station_"+sid+"-"+id).is(":checked")) {
stations[bid] |= 1<<s; station_selected=1;
}
}
}
if(station_selected===0) {showerror(_("Error: You have not selected any stations."));return;}
program = JSON.stringify(program.concat(stations));
$.mobile.loading("show");
if (id == "new") {
send_to_os("/cp?pw=&pid=-1&v="+program).done(function(){
$.mobile.loading("hide");
update_controller_programs(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Program added successfully"));
});
window.history.back();
});
});
} else {
send_to_os("/cp?pw=&pid="+id+"&v="+program).done(function(){
$.mobile.loading("hide");
update_controller_programs(function(){
update_program_header();
});
showerror(_("Program has been updated"));
});
}
}
function raindelay() {
$.mobile.loading("show");
send_to_os("/cv?pw=&rd="+$("#delay").val()).done(function(){
var popup = $("#raindelay");
popup.popup("close");
popup.find("form").off("submit");
$.mobile.loading("hide");
showLoading("#footer-running");
$.when(
update_controller_settings(),
update_controller_status()
).then(check_status);
showerror(_("Rain delay has been successfully set"));
});
return false;
}
// Export and Import functions
function export_config() {
storage.set({"backup":JSON.stringify(window.controller)},function(){
showerror(_("Backup saved on this device"));
});
}
function import_config(data) {
var piNames = {1:"tz",2:"ntp",12:"htp",13:"htp2",14:"ar",15:"nbrd",16:"seq",17:"sdt",18:"mas",19:"mton",20:"mtoff",21:"urs",22:"rst",23:"wl",25:"ipas"},
keyIndex = {"tz":1,"ntp":2,"hp0":12,"hp1":13,"ar":14,"ext":15,"seq":16,"sdt":17,"mas":18,"mton":19,"mtof":20,"urs":21,"rso":22,"wl":23,"ipas":25,"devid":26};
if (typeof data === "undefined") {
storage.get("backup",function(newdata){
if (newdata.backup) {
import_config(newdata.backup);
} else {
showerror(_("No backup available on this device"));
return;
}
});
return;
}
data = JSON.parse(data);
if (!data.settings) {
showerror(_("No backup available on this device"));
return;
}
areYouSure(_("Are you sure you want to restore the configuration?"), "", function() {
$.mobile.loading("show");
var cs = "/cs?pw=",
co = "/co?pw=",
cp_start = "/cp?pw=",
isPi = isOSPi(),
i, key;
for (i in data.options) {
if (data.options.hasOwnProperty(i) && keyIndex.hasOwnProperty(i)) {
key = keyIndex[i];
if ($.inArray(key, [2,14,16,21,22,25]) !== -1 && data.options[i] === 0) continue;
if (isPi) {
key = piNames[key];
if (key === undefined) continue;
} else {
key = key;
}
co += "&o"+key+"="+data.options[i];
}
}
co += "&"+(isPi?"o":"")+"loc="+data.settings.loc;
for (i=0; i<data.stations.snames.length; i++) {
cs += "&s"+i+"="+data.stations.snames[i];
}
for (i=0; i<data.stations.masop.length; i++) {
cs += "&m"+i+"="+data.stations.masop[i];
}
if (typeof data.stations.ignore_rain === "object") {
for (i=0; i<data.stations.ignore_rain.length; i++) {
cs += "&i"+i+"="+data.stations.ignore_rain[i];
}
}
$.when(
send_to_os(co),
send_to_os(cs),
$.each(data.programs.pd,function (i,prog) {
send_to_os(cp_start+"&pid=-1&v="+JSON.stringify(prog));
})
).then(
function(){
update_controller(function(){
$.mobile.loading("hide");
showerror(_("Backup restored to your device"));
update_weather();
});
},
function(){
$.mobile.loading("hide");
showerror(_("Unable to import configuration. Check device password and try again."));
}
);
});
}
// OSPi functions
function isOSPi() {
if (window.controller && typeof window.controller.options.fwv == "string" && window.controller.options.fwv.search(/ospi/i) !== -1) return true;
return false;
}
function checkWeatherPlugin() {
var weather_settings = $(".weather_settings");
window.curr_wa = [];
weather_settings.hide();
if (isOSPi()) {
send_to_os("/wj","json").done(function(results){
if (typeof results.auto_delay === "string") {
window.curr_wa = results;
weather_settings.css("display","");
}
});
}
}
function getOSVersion(fwv) {
if (typeof fwv == "string" && fwv.search(/ospi/i) !== -1) {
return fwv;
} else {
return (fwv/100>>0)+"."+((fwv/10>>0)%10)+"."+(fwv%10);
}
}
// Accessory functions for jQuery Mobile
function areYouSure(text1, text2, callback) {
var popup = $(
'<div data-role="popup" data-overlay-theme="b" id="sure">'+
'<h3 class="sure-1 center">'+text1+'</h3>'+
'<p class="sure-2 center">'+text2+'</p>'+
'<a class="sure-do ui-btn ui-btn-b ui-corner-all ui-shadow" href="#">'+_("Yes")+'</a>'+
'<a class="sure-dont ui-btn ui-corner-all ui-shadow" href="#">'+_("No")+'</a>'+
'</div>'
);
//Bind buttons
popup.find(".sure-do").one("click.sure", function() {
$("#sure").popup("close");
callback();
return false;
});
popup.find(".sure-dont").one("click.sure", function() {
$("#sure").popup("close");
return false;
});
popup.one("popupafterclose", function(){
$(this).popup("destroy").remove();
}).enhanceWithin();
$(".ui-page-active").append(popup);
$("#sure").popup({history: false, positionTo: "window"}).popup("open");
}
function showDurationBox(seconds,title,callback,maximum,granularity) {
$("#durationBox").popup("destroy").remove();
title = title || "Duration";
callback = callback || function(){};
granularity = granularity || 0;
var types = ["Days","Hours","Minutes","Seconds"],
conv = [86400,3600,60,1],
total = 4 - granularity,
start = 0,
arr = sec2dhms(seconds),
i;
if (maximum) {
for (i=conv.length-1; i>=0; i--) {
if (maximum < conv[i]) {
start = i+1;
total = (conv.length - start) - granularity;
break;
}
}
}
var incrbts = '<fieldset class="ui-grid-'+String.fromCharCode(95+(total))+' incr">',
inputs = '<div class="ui-grid-'+String.fromCharCode(95+(total))+' inputs">',
decrbts = '<fieldset class="ui-grid-'+String.fromCharCode(95+(total))+' decr">',
popup = $('<div data-role="popup" id="durationBox" data-theme="a" data-overlay-theme="b">' +
'<div data-role="header" data-theme="b">' +
'<h1>'+title+'</h1>' +
'</div>' +
'<div class="ui-content">' +
'<span>' +
'<a href="#" class="submit_duration" data-role="button" data-corners="true" data-shadow="true" data-mini="true">'+_("Set Duration")+'</a>' +
'</span>' +
'</div>' +
'</div>'),
changeValue = function(pos,dir){
var input = $(popup.find(".inputs input")[pos]),
val = parseInt(input.val());
if ((dir == -1 && val === 0) || (dir == 1 && (getValue() + conv[pos+start]) > maximum)) return;
input.val(val+dir);
},
getValue = function() {
return dhms2sec({
"days": parseInt(popup.find(".days").val()) || 0,
"hours": parseInt(popup.find(".hours").val()) || 0,
"minutes": parseInt(popup.find(".minutes").val()) || 0,
"seconds": parseInt(popup.find(".seconds").val()) || 0
});
};
for (i=start; i<conv.length - granularity; i++) {
incrbts += '<div '+((total > 1) ? 'class="ui-block-'+String.fromCharCode(97+i-start)+'"' : '')+'><a href="#" data-role="button" data-mini="true" data-corners="true" data-icon="plus" data-iconpos="bottom"></a></div>';
inputs += '<div '+((total > 1) ? 'class="ui-block-'+String.fromCharCode(97+i-start)+'"' : '')+'><label>'+_(types[i])+'</label><input class="'+types[i].toLowerCase()+'" type="number" pattern="[0-9]*" value="'+arr[types[i].toLowerCase()]+'"></div>';
decrbts += '<div '+((total > 1) ? 'class="ui-block-'+String.fromCharCode(97+i-start)+'"' : '')+'><a href="#" data-role="button" data-mini="true" data-corners="true" data-icon="minus" data-iconpos="bottom"></a></div>';
}
incrbts += '</fieldset>';
inputs += '</div>';
decrbts += '</fieldset>';
popup.find("span").prepend(incrbts+inputs+decrbts);
popup.find(".incr").children().on("click",function(){
var pos = $(this).index();
changeValue(pos,1);
return false;
});
popup.find(".decr").children().on("click",function(){
var pos = $(this).index();
changeValue(pos,-1);
return false;
});
popup
.css("max-width","350px")
.popup({
history: false,
"positionTo": "window"
})
.one("popupafterclose",function(){
$(this).popup("destroy").remove();
})
.on("click",".submit_duration",function(){
callback(getValue());
popup.popup("close");
return false;
})
.enhanceWithin().popup("open");
}
function changePage(toPage,opts) {
opts = opts || {};
if (toPage.indexOf("#") !== 0) toPage = "#"+toPage;
$.mobile.pageContainer.pagecontainer("change",toPage,opts);
}
// Close the panel before page transition to avoid bug in jQM 1.4+
function changeFromPanel(page) {
var $panel = $("#sprinklers-settings");
$panel.one("panelclose", function(){
changePage("#"+page);
});
$panel.panel("close");
}
function showTooltip(x, y, contents, color) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': color,
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
// Show loading indicator within element(s)
function showLoading(ele) {
$(ele).off("click").html("<p class='ui-icon ui-icon-loading mini-load'></p>");
}
// show error message
function showerror(msg,dur) {
dur = dur || 2500;
$.mobile.loading('show', {
text: msg,
textVisible: true,
textonly: true,
theme: 'b'
});
// hide after delay
setTimeout(function(){$.mobile.loading('hide');},dur);
}
// Accessory functions
function fixInputClick(page) {
// Handle Fast Click quirks
if (!FastClick.notNeeded(document.body)) {
page.find("input[type='checkbox']:not([data-role='flipswitch'])").addClass("needsclick");
page.find(".ui-collapsible-heading-toggle").on("click",function(){
var heading = $(this);
setTimeout(function(){
heading.removeClass("ui-btn-active");
},100);
});
}
}
// Convert all elements in array to integer
function parseIntArray(arr) {
for(var i=0; i<arr.length; i++) {arr[i] = +arr[i];}
return arr;
}
// Convert seconds into (HH:)MM:SS format. HH is only reported if greater than 0.
function sec2hms(diff) {
var str = "";
var hours = Math.max(0, parseInt( diff / 3600 ) % 24);
var minutes = Math.max(0, parseInt( diff / 60 ) % 60);
var seconds = diff % 60;
if (hours) str += pad(hours)+":";
return str+pad(minutes)+":"+pad(seconds);
}
// Convert seconds into array of days, hours, minutes and seconds.
function sec2dhms(diff) {
return {
"days": Math.max(0, parseInt(diff / 86400)),
"hours": Math.max(0, parseInt(diff % 86400 / 3600)),
"minutes": Math.max(0, parseInt((diff % 86400) % 3600 / 60)),
"seconds": Math.max(0, parseInt((diff % 86400) % 3600 % 60))
};
}
function dhms2str(arr) {
var str = "";
if (arr.days) str += arr.days+_("d")+" ";
if (arr.hours) str += arr.hours+_("h")+" ";
if (arr.minutes) str += arr.minutes+_("m")+" ";
if (arr.seconds) str += arr.seconds+_("s")+" ";
if (str === "") str = "0"+_("s");
return str.trim();
}
// Convert days, hours, minutes and seconds array into seconds (int).
function dhms2sec(arr) {
return parseInt((arr.days*86400)+(arr.hours*3600)+(arr.minutes*60)+arr.seconds);
}
// Generate email link for JSON data export
function objToEmail(ele,obj,subject) {
subject = subject || "Sprinklers Data Export on "+dateToString(new Date());
var body = JSON.stringify(obj);
$(ele).attr("href","mailto:?subject="+encodeURIComponent(subject)+"&body="+encodeURIComponent(body));
}
// Small wrapper to handle Chrome vs localStorage usage
var storage = {
get: function(query,callback) {
callback = callback || function(){};
try {
var data = {},
i;
if (typeof query == "object") {
for (i in query) {
if (query.hasOwnProperty(i)) {
data[query[i]] = localStorage.getItem(query[i]);
}
}
} else if (typeof query == "string") {
data[query] = localStorage.getItem(query);
}
callback(data);
} catch(e) {
chrome.storage.local.get(query,callback);
}
},
set: function(query,callback) {
callback = callback || function(){};
try {
var i;
if (typeof query == "object") {
for (i in query) {
if (query.hasOwnProperty(i)) {
localStorage.setItem(i,query[i]);
}
}
}
callback(true);
} catch(e) {
chrome.storage.local.get(query,callback);
}
},
remove: function(query,callback) {
callback = callback || function(){};
try {
var i;
if (typeof query == "object") {
for (i in query) {
if (query.hasOwnProperty(i)) {
localStorage.removeItem(query[i]);
}
}
} else if (typeof query == "string") {
localStorage.removeItem(query);
}
callback(true);
} catch(e) {
chrome.storage.local.get(query,callback);
}
}
};
// Return day of the week
function getDayName(day,type) {
var ldays = [_("Sunday"),_("Monday"),_("Tuesday"),_("Wednesday"),_("Thursday"),_("Friday"),_("Saturday")],
sdays = [_("Sun"),_("Mon"),_("Tue"),_("Wed"),_("Thu"),_("Fri"),_("Sat")];
if (type == "short") {
return sdays[day.getDay()];
} else {
return ldays[day.getDay()];
}
}
// Add ability to unique sort arrays
function getUnique(inputArray) {
var outputArray = [];
for (var i = 0; i < inputArray.length; i++) {
if ((jQuery.inArray(inputArray[i], outputArray)) == -1) outputArray.push(inputArray[i]);
}
return outputArray;
}
// pad a single digit with a leading zero
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
//Localization functions
function _(key) {
//Translate item (key) based on currently defined language
if (typeof window.language === "object" && window.language.hasOwnProperty(key)) {
var trans = window.language[key];
return trans ? trans : key;
} else {
//If English
return key;
}
}
function set_lang() {
//Update all static elements to the current language
$("[data-translate]").text(function() {
var el = $(this),
txt = el.data("translate");
if (el.is("input[type='submit']")) {
el.val(_(txt));
// Update button for jQuery Mobile
if (el.parent("div.ui-btn").length > 0) el.button("refresh");
} else {
return _(txt);
}
});
$(".ui-toolbar-back-btn").text(_("Back"));
$.mobile.toolbar.prototype.options.backBtnText = _("Back");
check_curr_lang();
}
function update_lang(lang) {
//Empty out the current language (English is provided as the key)
window.language = {};
if (typeof lang == "undefined") {
storage.get("lang",function(data){
//Identify the current browser's locale
var locale = "en";
locale = data.lang || navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage || locale;
update_lang(locale.substring(0,2));
});
return;
}
storage.set({"lang":lang});
if (lang == "en") {
set_lang();
return;
}
$.getJSON("locale/"+lang+".json",function(store){
window.language = store.messages;
set_lang();
}).fail(set_lang);
}
function check_curr_lang() {
storage.get("lang",function(data){
$("#localization").find("a").each(function(a,b){
var item = $(b);
if (item.data("lang-code") == data.lang) {
item.removeClass("ui-icon-carat-r").addClass("ui-icon-check");
} else {
item.removeClass("ui-icon-check").addClass("ui-icon-carat-r");
}
});
});
}
function dateToString(date) {
var lang = localStorage.getItem("lang");
if (lang == "de") {
date.setMinutes(date.getMinutes()+date.getTimezoneOffset());
return pad(date.getDate())+"."+pad(date.getMonth())+"."+date.getFullYear()+" "+pad(date.getHours())+":"+pad(date.getMinutes())+":"+pad(date.getSeconds());
}
return date.toUTCString().slice(0,-4);
}
function tzToString(prefix,tz,offset) {
var lang = localStorage.getItem("lang");
if (lang == "de") return "";
return prefix+tz+" "+offset;
}
|
js/main.js
|
var isIEMobile = /IEMobile/.test(navigator.userAgent),
isAndroid = /Android|\bSilk\b/.test(navigator.userAgent),
isiOS = /iP(ad|hone|od)/.test(navigator.userAgent);
//Fix CSS for IE Mobile (Windows Phone 8)
if (isIEMobile) {
var a=document.createElement("style");
a.innerHTML="ul{list-style: none !important;}@media(max-width:940px){.wicon{margin:-10px -10px -15px -15px !important}#forecast .wicon{position:relative;left:37.5px;margin:0 auto !important}}";
document.head.appendChild(a);
}
//Attach FastClick handler
$(window).one("load", function(){
FastClick.attach(document.body);
});
$(document)
.ready(function() {
//Update the language on the page using the browser's locale
update_lang(get_locale());
//Use the user's local time for preview
var now = new Date();
$("#log_start").val(new Date(now.getTime() - 604800000).toISOString().slice(0,10));
$("#preview_date, #log_end").val(now.toISOString().slice(0,10));
//Update site based on selector
$("#site-selector").on("change",function(){
update_site($(this).val());
});
//Bind start page buttons
$("#auto-scan").find("button").on("click",start_scan);
//Bind open panel button
$("#sprinklers").find("div[data-role='header'] > .ui-btn-left").off("click").on("click",function(){
open_panel();
return false;
});
//Bind stop all stations button
$("#stop-all").on("click",function(){
areYouSure(_("Are you sure you want to stop all stations?"), "", function() {
$.mobile.loading("show");
send_to_os("/cv?pw=&rsn=1").done(function(){
$.mobile.loading("hide");
$.when(
update_controller_settings(),
update_controller_status()
).then(check_status);
showerror(_("All stations have been stopped"));
});
});
});
// Prevent caching of AJAX requests on Android and Windows Phone devices
if (isAndroid) {
$(this).ajaxStart(function(){
try {
navigator.app.clearCache();
} catch (err) {}
});
} else if (isIEMobile) {
$.ajaxSetup({
"cache": false
});
}
//Use system browser for links on iOS and Windows Phone
if (isiOS || isIEMobile) {
$(".iab").attr("target","_system");
}
})
.ajaxError(function(x,t,m) {
if (t.status==401 && /https?:\/\/.*?\/(?:cv|sn|cs|cr|cp|dp|co|cl)/.exec(m.url)) {
showerror(_("Check device password and try again."));
return;
} else if (t.status===0) {
if (/https?:\/\/.*?\/(?:cv|sn|cs|cr|cp|dp|co|cl)/.exec(m.url)) {
// Ajax fails typically because the password is wrong
showerror(_("Check device password and try again."));
return;
}
}
if (m.url.search("yahooapis.com") !== -1 || m.url.search("api.wunderground.com") !== -1) {
hide_weather();
return;
}
if (t.statusText==="timeout") {
showerror(_("Connection timed-out. Please try again."));
return;
}
})
.one("deviceready", function() {
try {
//Change the status bar to match the headers
StatusBar.overlaysWebView(false);
StatusBar.styleLightContent();
StatusBar.backgroundColorByHexString("#1C1C1C");
} catch (err) {}
// Hide the splash screen
setTimeout(function(){
navigator.splashscreen.hide();
},500);
// Check if device is on a local network
checkAutoScan();
})
.one("mobileinit", function(){
//After jQuery mobile is loaded set intial configuration
$.mobile.defaultPageTransition = 'fade';
$.mobile.hoverDelay = 0;
})
.one("pagebeforechange", function(event) {
// Let the framework know we're going to handle the load
event.preventDefault();
//On initial load check if a valid site exists for auto connect
check_configured(true);
$.mobile.document.on("pagebeforechange",function(e,data){
var page = data.toPage,
hash, showBack;
if (typeof data.toPage !== "string") return;
hash = $.mobile.path.parseUrl(page).hash;
if (data.options.role !== "popup" && !$(".ui-popup-active").length) $.mobile.silentScroll(0);
if (hash == "#programs") {
get_programs(data.options.programToExpand);
} else if (hash == "#addprogram") {
add_program();
} else if (hash =="#status") {
$(hash).find("div[data-role='header'] > .ui-btn-right").on("click",refresh_status);
get_status();
} else if (hash == "#manual") {
get_manual();
} else if (hash == "#runonce") {
get_runonce();
} else if (hash == "#os-settings") {
show_settings();
} else if (hash == "#start") {
checkAutoScan();
} else if (hash == "#os-stations") {
show_stations();
} else if (hash == "#site-control") {
showBack = (data.options.showBack === false) ? false : true;
$("#site-control").find(".ui-toolbar-back-btn").toggle(showBack);
show_sites();
} else if (hash == "#weather_settings") {
show_weather_settings();
} else if (hash == "#addnew") {
show_addnew();
return false;
} else if (hash == "#raindelay") {
$(hash).find("form").on("submit",raindelay);
} else if (hash == "#site-select") {
show_site_select();
return false;
} else if (hash == "#sprinklers") {
if (!data.options.firstLoad) {
//Reset status bar to loading while an update is done
showLoading("#footer-running");
setTimeout(function(){
refresh_status();
},800);
} else {
check_status();
}
} else if (hash == "#settings") {
$.each(["en","mm"],function(a,id){
var $id = $("#"+id);
$id.prop("checked",window.controller.settings[id]);
if ($id.hasClass("ui-flipswitch-input")) $id.flipswitch("refresh");
$id.on("change",flipSwitched);
});
var settings = $(hash);
settings.find(".clear_logs > a").off("click").on("click",function(){
areYouSure(_("Are you sure you want to clear all your log data?"), "", function() {
$.mobile.loading("show");
send_to_os("/cl?pw=").done(function(){
$.mobile.loading("hide");
showerror(_("Logs have been cleared"));
});
});
return false;
});
settings.find(".reboot-os").off("click").on("click",function(){
areYouSure(_("Are you sure you want to reboot OpenSprinkler?"), "", function() {
$.mobile.loading("show");
send_to_os("/cv?pw=&rbt=1").done(function(){
$.mobile.loading("hide");
showerror(_("OpenSprinkler is rebooting now"));
});
});
return false;
});
settings.find(".clear-config").off("click").on("click",function(){
areYouSure(_("Are you sure you want to delete all settings and return to the default settings?"), "", function() {
localStorage.removeItem("sites");
localStorage.removeItem("current_site");
localStorage.removeItem("lang");
localStorage.removeItem("provider");
localStorage.removeItem("wapikey");
localStorage.removeItem("runonce");
update_lang(get_locale());
changePage("#start");
});
return false;
});
settings.find(".show-providers").off("click").on("click",function(){
$("#providers").popup("destroy").remove();
storage.get(["provider","wapikey"],function(data){
data.provider = data.provider || "yahoo";
var popup = $(
'<div data-role="popup" id="providers" data-theme="a" data-dismissible="false" data-overlay-theme="b">'+
'<a data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a>'+
'<div class="ui-content">'+
'<form>'+
'<label for="weather_provider">'+_("Weather Provider")+
'<select data-mini="true" id="weather_provider">'+
'<option value="yahoo">'+_("Yahoo!")+'</option>'+
'<option '+((data.provider == "wunderground") ? 'selected ' : '')+'value="wunderground">'+_("Wunderground")+'</option>'+
'</select>'+
'</label>'+
'<label for="wapikey">'+_("Wunderground API Key")+'<input data-mini="true" type="text" id="wapikey" value="'+((data.wapikey) ? data.wapikey : '')+'" /></label>'+
'<input type="submit" value="'+_("Submit")+'" />'+
'</form>'+
'</div>'+
'</div>'
);
if (data.provider == "yahoo") popup.find("#wapikey").closest("label").hide();
popup.find("form").on("submit",function(e){
e.preventDefault();
var wapikey = $("#wapikey").val(),
provider = $("#weather_provider").val();
if (provider == "wunderground" && wapikey === "") {
showerror(_("An API key must be provided for Weather Underground"));
return;
}
storage.set({
"wapikey": wapikey,
"provider": provider
});
update_weather();
$("#providers").popup("close");
return false;
});
//Handle provider select change on weather settings
popup.on("change","#weather_provider",function(){
var val = $(this).val();
if (val === "wunderground") {
$("#wapikey").closest("label").show();
} else {
$("#wapikey").closest("label").hide();
}
popup.popup("reposition",{
"positionTo": "window"
});
});
popup.one("popupafterclose",function(){
document.activeElement.blur();
this.remove();
}).popup().enhanceWithin().popup("open");
return false;
});
});
$("#localization").find("a").off("click").on("click",function(){
var link = $(this),
lang = link.data("lang-code");
update_lang(lang);
});
settings.one("pagehide",function(){
$("#en,#mm").off("change");
settings.find(".clear_logs > a,.reboot-os,.clear-config,.show-providers").off("click");
$("#localization").find("a").off("click");
});
}
});
})
.on("resume",function(){
var page = $(".ui-page-active").attr("id"),
func = function(){};
// Check if device is still on a local network
checkAutoScan();
// If we don't have a current device IP set, there is nothing else to update
if (window.curr_ip === undefined) return;
// Indicate the weather and device status are being updated
showLoading("#weather,#footer-running");
if (page == "status") {
// Update the status page
func = get_status;
} else if (page == "sprinklers") {
// Update device status bar on main page
func = check_status;
}
update_controller(function(){
func();
update_weather();
},network_fail);
})
.on("pause",function(){
//Remove any status timers that may be running
removeTimers();
})
.on("pageshow",function(e){
var newpage = "#"+e.target.id,
$newpage = $(newpage);
fixInputClick($newpage);
// Render graph after the page is shown otherwise graphing function will fail
if (newpage == "#preview") {
$("#preview_date").on("change",get_preview);
$newpage.find(".preview-minus").on("click",function(){
changeday(-1);
});
$newpage.find(".preview-plus").on("click",function(){
changeday(1);
});
get_preview();
//Update the preview page on date change
$newpage.one("pagehide",function(){
$("#timeline").empty();
$("#preview_date").off("change");
$.mobile.window.off("resize");
$(".preview-minus,.preview-plus").off("click");
$("#timeline-navigation").find("a").off("click");
});
} else if (newpage == "#logs") {
get_logs();
} else if (newpage == "#sprinklers") {
$newpage.off("swiperight").on("swiperight", function() {
if ($(".ui-page-active").jqmData("panel") !== "open" && !$(".ui-page-active .ui-popup-active").length) {
open_panel();
}
});
}
})
.on("pagehide","#start",removeTimers)
.on("popupbeforeposition","#localization",check_curr_lang);
//Set AJAX timeout
$.ajaxSetup({
timeout: 6000
});
var switching = false;
function flipSwitched() {
if (switching) return;
//Find out what the switch was changed to
var flip = $(this),
id = flip.attr("id"),
changedTo = flip.is(":checked"),
method = (id == "mmm") ? "mm" : id,
defer;
if (changedTo) {
defer = send_to_os("/cv?pw=&"+method+"=1");
} else {
defer = send_to_os("/cv?pw=&"+method+"=0");
}
$.when(defer).then(function(){
update_controller_settings();
if (id == "mm" || id == "mmm") $("#manual a.green").removeClass("green");
},
function(){
switching = true;
setTimeout(function(){
switching = false;
},200);
flip.prop("checked",!changedTo).flipswitch("refresh");
});
}
// Wrapper function to communicate with OpenSprinkler
function send_to_os(dest,type) {
dest = dest.replace("pw=","pw="+window.curr_pw);
type = type || "text";
var obj = {
url: window.curr_prefix+window.curr_ip+dest,
type: "GET",
dataType: type
};
if (window.curr_auth) {
$.extend(obj,{
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(window.curr_auth_user + ":" + window.curr_auth_pw)); }
});
}
if (typeof window.curr_session != "undefined") {
$.extend(obj,{
beforeSend: function(xhr) { xhr.setRequestHeader("webpy_session_id", window.curr_session); }
});
}
return $.ajax(obj);
}
function network_fail(){
change_status(0,0,"red","<p id='running-text' class='center'>"+_("Network Error")+"</p>",function(){
showLoading("#weather,#footer-running");
refresh_status();
update_weather();
});
hide_weather();
}
// Gather new controller information and load home page
function newload() {
$.mobile.loading("show");
//Create object which will store device data
window.controller = {};
update_controller(
function(){
var log_button = $("#log_button"),
clear_logs = $(".clear_logs"),
pi = isOSPi();
$.mobile.loading("hide");
check_status();
update_weather();
// Hide log viewer button on home page if not supported
if ((typeof window.controller.options.fwv === "number" && window.controller.options.fwv < 206) || (typeof window.controller.options.fwv === "string" && window.controller.options.fwv.match(/1\.9\.0/)) === -1) {
log_button.hide();
} else {
log_button.css("display","");
}
// Hide clear logs button when using Arduino device (feature not enabled yet)
if (!pi) {
clear_logs.hide();
} else {
clear_logs.css("display","");
}
// Update export to email button in side panel
objToEmail(".email_config",window.controller);
// Check if automatic rain delay plugin is enabled on OSPi devices
checkWeatherPlugin();
// Transition to home page after succesful load
if ($.mobile.pageContainer.pagecontainer("getActivePage").attr("id") != "sprinklers") {
changePage("#sprinklers",{
"transition":"none",
"firstLoad": true
});
}
},
function(){
$.mobile.loading("hide");
if (Object.keys(getsites()).length) {
changePage("#site-control",{
'showBack': false
});
} else {
changePage("#start");
}
}
);
}
// Update controller information
function update_controller(callback,fail) {
callback = callback || function(){};
fail = fail || function(){};
$.when(
update_controller_programs(),
update_controller_stations(),
update_controller_options(),
update_controller_status(),
update_controller_settings()
).then(callback,fail);
}
function update_controller_programs(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/gp?d=0").done(function(programs){
var vars = programs.match(/(nprogs|nboards|mnp)=[\w|\d|.\"]+/g),
progs = /pd=\[\];(.*);/.exec(programs),
newdata = {}, tmp, prog;
for (var i=0; i<vars.length; i++) {
if (vars[i] === "") continue;
tmp = vars[i].split("=");
newdata[tmp[0]] = parseInt(tmp[1]);
}
newdata.pd = [];
if (progs !== null) {
progs = progs[1].split(";");
for (i=0; i<progs.length; i++) {
prog = progs[i].split("=");
prog = prog[1].replace("[", "");
prog = prog.replace("]", "");
newdata.pd[i] = parseIntArray(prog.split(","));
}
}
window.controller.programs = newdata;
callback();
});
} else {
return send_to_os("/jp","json").done(function(programs){
window.controller.programs = programs;
callback();
});
}
}
function update_controller_stations(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/vs").done(function(stations){
var names = /snames=\[(.*?)\];/.exec(stations),
masop = stations.match(/(?:masop|mo)\s?[=|:]\s?\[(.*?)\]/);
names = names[1].split(",");
names.pop();
for (var i=0; i<names.length; i++) {
names[i] = names[i].replace(/'/g,"");
}
masop = parseIntArray(masop[1].split(","));
window.controller.stations = {
"snames": names,
"masop": masop,
"maxlen": names.length
};
callback();
});
} else {
return send_to_os("/jn","json").done(function(stations){
window.controller.stations = stations;
callback();
});
}
}
function update_controller_options(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/vo").done(function(options){
var isOSPi = options.match(/var sd\s*=/),
vars = {}, tmp, i, o;
if (isOSPi) {
var varsRegex = /(tz|htp|htp2|nbrd|seq|sdt|mas|mton|mtoff|urs|rst|wl|ipas)\s?[=|:]\s?([\w|\d|.\"]+)/gm,
name;
while ((tmp = varsRegex.exec(options)) !== null) {
name = tmp[1].replace("nbrd","ext").replace("mtoff","mtof");
vars[name] = +tmp[2];
}
vars.ext--;
vars.fwv = "1.8.3-ospi";
} else {
var keyIndex = {1:"tz",2:"ntp",12:"hp0",13:"hp1",14:"ar",15:"ext",16:"seq",17:"sdt",18:"mas",19:"mton",20:"mtof",21:"urs",22:"rso",23:"wl",25:"ipas",26:"devid"};
tmp = /var opts=\[(.*)\];/.exec(options);
tmp = tmp[1].replace(/"/g,"").split(",");
for (i=0; i<tmp.length-1; i=i+4) {
o = +tmp[i+3];
if ($.inArray(o,[1,2,12,13,14,15,16,17,18,19,20,21,22,23,25,26]) !== -1) {
vars[keyIndex[o]] = +tmp[i+2];
}
}
vars.fwv = 183;
}
window.controller.options = vars;
callback();
});
} else {
return send_to_os("/jo","json").done(function(options){
window.controller.options = options;
callback();
});
}
}
function update_controller_status(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("/sn0").then(
function(status){
var tmp = status.match(/\d+/);
tmp = parseIntArray(tmp[0].split(""));
window.controller.status = tmp;
callback();
},
function(){
window.controller.status = [];
});
} else {
return send_to_os("/js","json").then(
function(status){
window.controller.status = status.sn;
callback();
},
function(){
window.controller.status = [];
});
}
}
function update_controller_settings(callback) {
callback = callback || function(){};
if (window.curr_183 === true) {
return send_to_os("").then(
function(settings){
var varsRegex = /(ver|devt|nbrd|tz|en|rd|rs|mm|rdst)\s?[=|:]\s?([\w|\d|.\"]+)/gm,
loc = settings.match(/loc\s?[=|:]\s?[\"|'](.*)[\"|']/),
lrun = settings.match(/lrun=\[(.*)\]/),
ps = settings.match(/ps=\[(.*)\];/),
vars = {}, tmp, i;
ps = ps[1].split("],[");
for (i = ps.length - 1; i >= 0; i--) {
ps[i] = parseIntArray(ps[i].replace(/\[|\]/g,"").split(","));
}
while ((tmp = varsRegex.exec(settings)) !== null) {
vars[tmp[1]] = +tmp[2];
}
vars.loc = loc[1];
vars.ps = ps;
vars.lrun = parseIntArray(lrun[1].split(","));
window.controller.settings = vars;
},
function(){
if (window.controller.settings && window.controller.stations) {
var ps = [], i;
for (i=0; i<window.controller.stations.maxlen; i++) {
ps.push([0,0]);
}
window.controller.settings.ps = ps;
}
});
} else {
return send_to_os("/jc","json").then(
function(settings){
window.controller.settings = settings;
callback();
},
function(){
if (window.controller.settings && window.controller.stations) {
var ps = [], i;
for (i=0; i<window.controller.stations.maxlen; i++) {
ps.push([0,0]);
}
window.controller.settings.ps = ps;
}
});
}
}
// Multisite functions
function check_configured(firstLoad) {
var sites = getsites(),
current = localStorage.getItem("current_site"),
names = Object.keys(sites);
if (sites === null || !names.length) {
if (firstLoad) {
changePage("#start");
}
return;
}
if (current === null || !(current in sites)) {
$.mobile.loading("hide");
site_select();
return;
}
update_site_list(names);
window.curr_ip = sites[current].os_ip;
window.curr_pw = sites[current].os_pw;
if (typeof sites[current].ssl !== "undefined" && sites[current].ssl === "1") {
window.curr_prefix = "https://";
} else {
window.curr_prefix = "http://";
}
if (typeof sites[current].auth_user !== "undefined" && typeof sites[current].auth_pw !== "undefined") {
window.curr_auth = true;
window.curr_auth_user = sites[current].auth_user;
window.curr_auth_pw = sites[current].auth_pw;
} else {
delete window.curr_auth;
}
if (sites[current].is183) {
window.curr_183 = true;
} else {
delete window.curr_183;
}
newload();
}
// Add a new site
function submit_newuser(ssl,useAuth) {
document.activeElement.blur();
$.mobile.loading("show");
var sites = getsites(),
ip = $("#os_ip").val(),
success = function(data){
$.mobile.loading("hide");
var is183;
if (typeof data === "string" && data.match(/var (en|sd)\s*=/)) is183 = true;
if (data.fwv !== undefined || is183 === true) {
var name = $("#os_name").val(),
ip = $("#os_ip").val().replace(/^https?:\/\//,"");
if (name === "") name = "Site "+(Object.keys(sites).length+1);
sites[name] = {};
sites[name].os_ip = window.curr_ip = ip;
sites[name].os_pw = window.curr_pw = $("#os_pw").val();
if (ssl) {
sites[name].ssl = "1";
window.curr_prefix = "https://";
} else {
window.curr_prefix = "http://";
}
if (useAuth) {
sites[name].auth_user = $("#os_auth_user").val();
sites[name].auth_pw = $("#os_auth_pw").val();
window.curr_auth = true;
window.curr_auth_user = sites[name].auth_user;
window.curr_auth_pw = sites[name].auth_pw;
} else {
delete window.curr_auth;
}
if (is183 === true) {
sites[name].is183 = "1";
window.curr_183 = true;
}
$("#os_name,#os_ip,#os_pw,#os_auth_user,#os_auth_pw").val("");
localStorage.setItem("sites",JSON.stringify(sites));
localStorage.setItem("current_site",name);
update_site_list(Object.keys(sites));
newload();
} else {
showerror(_("Check IP/Port and try again."));
}
},
fail = function (x){
if (!useAuth && x.status === 401) {
getAuth();
return;
}
if (ssl) {
$.mobile.loading("hide");
showerror(_("Check IP/Port and try again."));
} else {
submit_newuser(true);
}
},
getAuth = function(){
if ($("#addnew-auth").length) {
submit_newuser(ssl,true);
} else {
showAuth();
}
},
showAuth = function(){
$.mobile.loading("hide");
var html = $('<div class="ui-content" id="addnew-auth">' +
'<form method="post" novalidate>' +
'<p class="center smaller">'+_("Authorization Required")+'</p>' +
'<label for="os_auth_user">'+_("Username:")+'</label>' +
'<input autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" type="text" name="os_auth_user" id="os_auth_user" />' +
'<label for="os_auth_pw">'+_("Password:")+'</label>' +
'<input type="password" name="os_auth_pw" id="os_auth_pw" />' +
'<input type="submit" value="'+_("Submit")+'" />' +
'</form>' +
'</div>').enhanceWithin();
html.on("submit","form",function(){
submit_newuser(ssl,true);
return false;
});
$("#addnew-content").hide();
$("#addnew").append(html).popup("reposition",{positionTo:"window"});
},
prefix;
if (!ip) {
showerror(_("An IP address is required to continue."));
return;
}
if (useAuth !== true && $("#os_useauth").is(":checked")) {
getAuth();
return;
}
if ($("#os_usessl").is(":checked") === true) ssl = true;
if (ssl) {
prefix = "https://";
} else {
prefix = "http://";
}
if (useAuth) {
$("#addnew-auth").hide();
$("#addnew-content").show();
$("#addnew").popup("reposition",{positionTo:"window"});
}
//Submit form data to the server
$.ajax({
url: prefix+ip+"/jo",
type: "GET",
dataType: "json",
timeout: 3000,
global: false,
beforeSend: function(xhr) { if (useAuth) xhr.setRequestHeader("Authorization", "Basic " + btoa($("#os_auth_user").val() + ":" + $("#os_auth_pw").val())); },
error: function(x){
if (!useAuth && x.status === 401) {
getAuth();
return;
}
$.ajax({
url: prefix+ip,
type: "GET",
dataType: "text",
timeout: 3000,
global: false,
beforeSend: function(xhr) { if (useAuth) xhr.setRequestHeader("Authorization", "Basic " + btoa($("#os_auth_user").val() + ":" + $("#os_auth_pw").val())); },
success: success,
error: fail
});
},
success: success
});
}
function show_site_select(list) {
$("#site-select").popup("destroy").remove();
var popup = $('<div data-role="popup" id="site-select" data-theme="a" data-overlay-theme="b">' +
'<div data-role="header" data-theme="b">' +
'<h1>'+_("Select Site")+'</h1>' +
'</div>' +
'<div class="ui-content">' +
'<ul data-role="none" class="ui-listview ui-corner-all ui-shadow">' +
'</ul>' +
'</div>' +
'</div>');
if (list) popup.find("ul").html(list);
popup.one("popupafterclose",function(){
$(this).popup("destroy").remove();
}).popup({
history: false,
"positionTo": "window"
}).enhanceWithin().popup("open");
}
function show_addsite() {
if (typeof window.deviceip === "undefined") {
show_addnew();
} else {
var popup = $("#addsite");
$("#site-add-scan").one("click",function(){
$(".ui-popup-active").children().first().popup("close");
});
popup.popup("open").popup("reposition",{
"positionTo": "#site-add"
});
}
}
function show_addnew(autoIP,closeOld) {
$("#addnew").popup("destroy").remove();
var isAuto = (autoIP) ? true : false,
addnew = $('<div data-role="popup" id="addnew" data-theme="a">'+
'<div data-role="header" data-theme="b">'+
'<h1>'+_("New Device")+'</h1>' +
'</div>' +
'<div class="ui-content" id="addnew-content">' +
'<form method="post" novalidate>' +
((isAuto) ? '' : '<p class="center smaller">'+_("Note: The name is used to identify the OpenSprinkler within the app. OpenSprinkler IP can be either an IP or hostname. You can also specify a port by using IP:Port")+'</p>') +
'<label for="os_name">'+_("Open Sprinkler Name:")+'</label>' +
'<input autocorrect="off" spellcheck="false" type="text" name="os_name" id="os_name" placeholder="Home" />' +
((isAuto) ? '' : '<label for="os_ip">'+_("Open Sprinkler IP:")+'</label>') +
'<input '+((isAuto) ? 'data-role="none" style="display:none" ' : '')+'autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" type="url" name="os_ip" id="os_ip" value="'+((isAuto) ? autoIP : '')+'" placeholder="home.dyndns.org" />' +
'<label for="os_pw">'+_("Open Sprinkler Password:")+'</label>' +
'<input type="password" name="os_pw" id="os_pw" value="" />' +
((isAuto) ? '' : '<div data-theme="a" data-mini="true" data-role="collapsible"><h4>Advanced</h4><fieldset data-role="controlgroup" data-type="horizontal" data-mini="true" class="center">' +
'<input type="checkbox" name="os_useauth" id="os_useauth">' +
'<label for="os_useauth">'+_("Use Auth")+'</label>' +
'<input type="checkbox" name="os_usessl" id="os_usessl">' +
'<label for="os_usessl">'+_("Use SSL")+'</label>' +
'</fieldset></div>') +
'<input type="submit" data-theme="b" value="'+_("Submit")+'" />' +
'</form>' +
'</div>' +
'</div>');
addnew.find("form").on("submit",function(){
submit_newuser();
return false;
});
addnew.one("popupafterclose",function(){
$(this).popup("destroy").remove();
}).popup({
history: false,
"positionTo": "window"
}).enhanceWithin();
if (closeOld) {
$(".ui-popup-active").children().first().one("popupafterclose",function(){
addnew.popup("open");
}).popup("close");
} else {
addnew.popup("open");
}
fixInputClick(addnew);
addnew.find(".ui-collapsible-heading-toggle").on("click",function(){
var open = $(this).parents(".ui-collapsible").hasClass("ui-collapsible-collapsed"),
page = $.mobile.pageContainer.pagecontainer("getActivePage"),
height = parseInt(page.css("min-height"));
if (open) {
page.css("min-height",(height+65)+"px");
} else {
page.css("min-height",(height-65)+"px");
}
addnew.popup("reposition",{positionTo:"window"});
});
}
function show_sites() {
var list = "<div data-role='collapsible-set'>",
sites = getsites(),
total = Object.keys(sites).length,
page = $("#site-control");
page.find("div[data-role='header'] > .ui-btn-right").off("click").on("click",show_addsite);
page.find("#site-add-scan").off("click").on("click",start_scan);
page.find("#site-add-manual").off("click").on("click",function(){
show_addnew(false,true);
});
$.each(sites,function(a,b){
var c = a.replace(/ /g,"_");
list += "<fieldset "+((total == 1) ? "data-collapsed='false'" : "")+" id='site-"+c+"' data-role='collapsible'>";
list += "<legend>"+a+"</legend>";
list += "<a data-role='button' class='connectnow' data-site='"+a+"' href='#'>"+_("Connect Now")+"</a>";
list += "<form data-site='"+c+"' novalidate>";
list += "<label for='cnm-"+c+"'>"+_("Change Name")+"</label><input id='cnm-"+c+"' type='text' placeholder='"+a+"' />";
list += "<label for='cip-"+c+"'>"+_("Change IP")+"</label><input id='cip-"+c+"' type='url' placeholder='"+b.os_ip+"' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' />";
list += "<label for='cpw-"+c+"'>"+_("Change Password")+"</label><input id='cpw-"+c+"' type='password' />";
list += "<input type='submit' value='"+_("Save Changes to")+" "+a+"' /></form>";
list += "<a data-role='button' class='deletesite' data-site='"+a+"' href='#' data-theme='b'>"+_("Delete")+" "+a+"</a>";
list += "</fieldset>";
});
list = $(list+"</div>");
list.find(".connectnow").on("click",function(){
update_site(this.dataset.site);
return false;
});
list.find("form").on("submit",function(){
change_site(this.dataset.site);
return false;
});
list.find(".deletesite").on("click",function(){
delete_site(this.dataset.site);
return false;
});
page.find(".ui-content").html(list).enhanceWithin();
page.find(".ui-collapsible-set").collapsibleset();
page.one("pagehide",function(){
page.find("div[data-role='header'] > .ui-btn-right,#site-add-manual,#site-add-scan").off("click");
page.find(".ui-content").empty();
});
}
function delete_site(site) {
areYouSure(_("Are you sure you want to delete")+" '"+site+"'?","",function(){
var sites = getsites();
delete sites[site];
localStorage.setItem("sites",JSON.stringify(sites));
update_site_list(Object.keys(sites));
show_sites();
if ($.isEmptyObject(sites)) {
changePage("#start");
return false;
}
if (site === localStorage.getItem("current_site")) $("#site-control").find(".ui-toolbar-back-btn").toggle(false);
showerror(_("Site deleted successfully"));
return false;
});
}
// Modify site IP and/or password
function change_site(site) {
var sites = getsites(),
ip = $("#cip-"+site).val(),
pw = $("#cpw-"+site).val(),
nm = $("#cnm-"+site).val(),
rename;
site = site.replace(/_/g," ");
rename = (nm !== "" && nm != site);
if (ip !== "") sites[site].os_ip = ip;
if (pw !== "") sites[site].os_pw = pw;
if (rename) {
sites[nm] = sites[site];
delete sites[site];
site = nm;
localStorage.setItem("current_site",site);
update_site_list(Object.keys(sites));
}
localStorage.setItem("sites",JSON.stringify(sites));
showerror(_("Site updated successfully"));
if (site === localStorage.getItem("current_site")) {
if (pw !== "") window.curr_pw = pw;
if (ip !== "") check_configured();
}
if (rename) show_sites();
}
// Display the site select popup
function site_select(names) {
var newlist = "";
names = names || Object.keys(getsites());
for (var i=0; i < names.length; i++) {
newlist += "<li><a class='ui-btn ui-btn-icon-right ui-icon-carat-r' href='#'>"+names[i]+"</a></li>";
}
newlist = $(newlist);
newlist.find("a").on("click",function(){
update_site(this.innerHTML);
return false;
});
show_site_select(newlist);
}
// Update the panel list of sites
function update_site_list(names) {
var list = "",
current = localStorage.getItem("current_site");
$.each(names,function(a,b){
list += "<option "+(b==current ? "selected ":"")+"value='"+b+"'>"+b+"</option>";
});
$("#site-selector").html(list);
try {
$("#site-selector").selectmenu("refresh");
} catch (err) {
}
}
// Change the current site
function update_site(newsite) {
var sites = getsites();
if (newsite in sites) {
localStorage.setItem("current_site",newsite);
check_configured();
}
}
// Get the list of sites from the local storage
function getsites() {
var sites = localStorage.getItem("sites");
sites = (sites === null) ? {} : JSON.parse(sites);
return sites;
}
// Automatic device detection functions
function checkAutoScan() {
try {
// Request the device's IP address
networkinterface.getIPAddress(function(ip){
var chk = parseIntArray(ip.split("."));
// Check if the IP is on a private network, if not don't enable automatic scanning
if (!(chk[0] == 10 || (chk[0] == 172 && chk[1] > 17 && chk[1] < 32) || (chk[0] == 192 && chk[1] == 168))) {
resetStartMenu();
return;
}
//Change main menu items to reflect ability to automatically scan
var auto = $("#auto-scan"),
next = auto.next();
next.removeClass("ui-first-child").find("a.ui-btn").text(_("Manually Add Device"));
auto.show();
window.deviceip = ip;
});
} catch (err) {
resetStartMenu();
}
}
function resetStartMenu() {
// Change main menu to reflect manual controller entry
var auto = $("#auto-scan"),
next = auto.next();
delete window.deviceip;
next.addClass("ui-first-child").find("a.ui-btn").text(_("Add Controller"));
auto.hide();
}
function start_scan(port,type) {
var ip = window.deviceip.split("."),
scanprogress = 1,
devicesfound = 0,
newlist = "",
suffix = "",
oldsites = getsites(),
oldips = [],
i, url, notfound, found, baseip, check_scan_status, scanning, dtype;
type = type || 0;
for (i in oldsites) {
if (oldsites.hasOwnProperty(i)) {
oldips.push(oldsites[i].os_ip);
}
}
notfound = function(){
scanprogress++;
};
found = function (reply) {
scanprogress++;
var ip = $.mobile.path.parseUrl(this.url).authority,
fwv, tmp;
if ($.inArray(ip,oldips) !== -1) return;
if (this.dataType === "text") {
tmp = reply.match(/var\s*ver=(\d+)/);
if (!tmp) return;
fwv = tmp[1];
} else {
fwv = reply.fwv;
}
devicesfound++;
newlist += "<li><a class='ui-btn ui-btn-icon-right ui-icon-carat-r' href='#' data-ip='"+ip+"'>"+ip+"<p>"+_("Firmware")+": "+getOSVersion(fwv)+"</p></a></li>";
};
// Check if scanning is complete
check_scan_status = function() {
if (scanprogress == 245) {
$.mobile.loading("hide");
clearInterval(scanning);
if (!devicesfound) {
if (type === 0) {
start_scan(8080,1);
} else if (type === 1) {
start_scan(80,2);
} else if (type === 2) {
start_scan(8080,3);
} else {
showerror(_("No new devices were detected on your network"));
}
} else {
newlist = $(newlist);
newlist.find("a").on("click",function(){
add_found(this.dataset.ip);
return false;
});
show_site_select(newlist);
}
}
};
ip.pop();
baseip = ip.join(".");
if (type === 1) {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler Pi"),
textVisible: true,
theme: 'b'
});
} else if (type === 2) {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler (1.8.3)"),
textVisible: true,
theme: 'b'
});
} else if (type === 3) {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler Pi (1.8.3)"),
textVisible: true,
theme: 'b'
});
} else {
$.mobile.loading('show', {
text: _("Scanning for OpenSprinkler"),
textVisible: true,
theme: 'b'
});
}
// Start scan
for (i = 1; i<=244; i++) {
ip = baseip+"."+i;
if (type < 2) {
suffix = "/jo";
dtype = "json";
} else {
dtype = "text";
}
url = "http://"+ip+((port && port != 80) ? ":"+port : "")+suffix;
$.ajax({
url: url,
type: "GET",
dataType: dtype,
timeout: 3000,
global: false,
error: notfound,
success: found
});
}
scanning = setInterval(check_scan_status,200);
}
// Show popup for new device after populating device IP with selected result
function add_found(ip) {
$("#site-select").one("popupafterclose", function(){
show_addnew(ip);
}).popup("close");
}
// Weather functions
function show_weather_settings() {
var page = $('<div data-role="page" id="weather_settings">' +
'<div data-theme="b" data-role="header" data-position="fixed" data-tap-toggle="false" data-add-back-btn="true">' +
'<h3>'+_("Weather Settings")+'</h3>' +
'<a href="#" class="ui-btn-right wsubmit">'+_("Submit")+'</a>' +
'</div>' +
'<div class="ui-content" role="main">' +
'<ul data-role="listview" data-inset="true">' +
'<li>' +
'<label for="weather_provider">'+_("Weather Provider")+'</label>' +
'<select data-mini="true" id="weather_provider">' +
'<option value="yahoo" '+(window.curr_wa.weather_provider == "yahoo" ? "selected" : "")+'>'+_("Yahoo!")+'</option>' +
'<option value="wunderground" '+(window.curr_wa.weather_provider == "wunderground" ? "selected" : "")+'>'+_("Wunderground")+'</option>' +
'</select>' +
(window.curr_wa.weather_provider == "wunderground" ? '<label for="wapikey">'+_("Wunderground API Key")+'</label><input data-mini="true" type="text" id="wapikey" value="'+window.curr_wa.wapikey+'" />' : "") +
'</li>' +
'</ul>' +
'<ul data-role="listview" data-inset="true"> ' +
'<li>' +
'<p class="rain-desc">'+_("When automatic rain delay is enabled, the weather will be checked for rain every hour. If the weather reports any condition suggesting rain, a rain delay is automatically issued using the below set delay duration.")+'</p>' +
'<div class="ui-field-contain">' +
'<label for="auto_delay">'+_("Auto Rain Delay")+'</label>' +
'<input type="checkbox" data-on-text="On" data-off-text="Off" data-role="flipswitch" name="auto_delay" id="auto_delay" '+(window.curr_wa.auto_delay == "on" ? "checked" : "")+'>' +
'</div>' +
'<div class="ui-field-contain duration-input">' +
'<label for="delay_duration">'+_("Delay Duration")+'</label>' +
'<button id="delay_duration" data-mini="true" value="'+(window.curr_wa.delay_duration*3600)+'">'+dhms2str(sec2dhms(window.curr_wa.delay_duration*3600))+'</button>' +
'</div>' +
'</li>' +
'</ul>' +
'<a class="wsubmit" href="#" data-role="button" data-theme="b" type="submit">'+_("Submit")+'</a>' +
'</div>' +
'</div>');
//Handle provider select change on weather settings
page
.on("change","#weather_provider",function(){
var val = $(this).val();
if (val === "wunderground") {
$("#wapikey,label[for='wapikey']").show("fast");
} else {
$("#wapikey,label[for='wapikey']").hide("fast");
}
})
.one("pagehide",function(){
$(this).remove();
})
.find(".wsubmit").on("click",function(){
submit_weather_settings();
return false;
});
page.find("#delay_duration").on("click",function(){
var dur = $(this),
name = page.find("label[for='"+dur.attr("id")+"']").text();
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
},345600,2);
});
page.appendTo("body");
}
function submit_weather_settings() {
var url = "/uwa?auto_delay="+($("#auto_delay").is(":checked") ? "on" : "off")+"&delay_duration="+parseInt($("#delay_duration").val()/3600)+"&weather_provider="+$("#weather_provider").val()+"&wapikey="+$("#wapikey").val();
send_to_os(url).then(
function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Weather settings have been saved"));
});
window.history.back();
checkWeatherPlugin();
},
function(){
showerror(_("Weather settings were not saved. Please try again."));
}
);
}
function convert_temp(temp,region) {
if (region == "United States" || region == "Bermuda" || region == "Palau") {
temp = temp+"°F";
} else {
temp = parseInt(Math.round((temp-32)*(5/9)))+"°C";
}
return temp;
}
function hide_weather() {
$("#weather-list").animate({
"margin-left": "-1000px"
},1000,function(){
$(this).hide();
});
}
function update_weather() {
var provider = localStorage.getItem("provider"),
wapikey = localStorage.getItem("wapikey");
if (window.controller.settings.loc === "") {
hide_weather();
return;
}
showLoading("#weather");
if (provider == "wunderground" && wapikey) {
update_wunderground_weather(wapikey);
} else {
update_yahoo_weather();
}
}
function update_yahoo_weather() {
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20woeid%20from%20geo.placefinder%20where%20text=%22"+escape(window.controller.settings.loc)+"%22&format=json",function(woeid){
if (woeid.query.results === null) {
hide_weather();
return;
}
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20item%2Ctitle%2Clocation%20from%20weather.forecast%20where%20woeid%3D%22"+woeid.query.results.Result.woeid+"%22&format=json",function(data){
// Hide the weather if no data is returned
if (data.query.results.channel.item.title == "City not found") {
hide_weather();
return;
}
var now = data.query.results.channel.item.condition,
title = data.query.results.channel.title,
loc = /Yahoo! Weather - (.*)/.exec(title),
region = data.query.results.channel.location.country;
$("#weather")
.html("<div title='"+now.text+"' class='wicon cond"+now.code+"'></div><span>"+convert_temp(now.temp,region)+"</span><br><span class='location'>"+loc[1]+"</span>")
.on("click",show_forecast);
$("#weather-list").animate({
"margin-left": "0"
},1000).show();
update_yahoo_forecast(data.query.results.channel.item.forecast,loc[1],region,now);
});
});
}
function update_yahoo_forecast(data,loc,region,now) {
var list = "<li data-role='list-divider' data-theme='a' class='center'>"+loc+"</li>",
i;
list += "<li data-icon='false' class='center'><div title='"+now.text+"' class='wicon cond"+now.code+"'></div><span data-translate='Now'>"+_("Now")+"</span><br><span>"+convert_temp(now.temp,region)+"</span></li>";
for (i=0;i < data.length; i++) {
list += "<li data-icon='false' class='center'><span>"+data[i].date+"</span><br><div title='"+data[i].text+"' class='wicon cond"+data[i].code+"'></div><span data-translate='"+data[i].day+"'>"+_(data[i].day)+"</span><br><span data-translate='Low'>"+_("Low")+"</span><span>: "+convert_temp(data[i].low,region)+" </span><span data-translate='High'>"+_("High")+"</span><span>: "+convert_temp(data[i].high,region)+"</span></li>";
}
var forecast = $("#forecast_list");
forecast.html(list).enhanceWithin();
if (forecast.hasClass("ui-listview")) forecast.listview("refresh");
}
function update_wunderground_weather(wapikey) {
$.ajax({
dataType: "jsonp",
type: "GET",
url: "https://api.wunderground.com/api/"+wapikey+"/conditions/forecast/lang:EN/q/"+escape(window.controller.settings.loc)+".json",
success: function(data) {
var code, temp;
if (data.current_observation.icon_url.indexOf("nt_") !== -1) { code = "nt_"+data.current_observation.icon; }
else code = data.current_observation.icon;
var ww_forecast = {
"condition": {
"text": data.current_observation.weather,
"code": code,
"temp_c": data.current_observation.temp_c,
"temp_f": data.current_observation.temp_f,
"date": data.current_observation.observation_time,
"precip_today_in": data.current_observation.precip_today_in,
"precip_today_metric": data.current_observation.precip_today_metric,
"type": "wunderground"
},
"location": data.current_observation.display_location.full,
"region": data.current_observation.display_location.country_iso3166,
simpleforecast: {}
};
$.each(data.forecast.simpleforecast.forecastday,function(k,attr) {
ww_forecast.simpleforecast[k] = attr;
});
if (ww_forecast.region == "US" || ww_forecast.region == "BM" || ww_forecast.region == "PW") temp = Math.round(ww_forecast.condition.temp_f)+"°F";
else temp = ww_forecast.condition.temp_c+"°C";
$("#weather")
.html("<div title='"+ww_forecast.condition.text+"' class='wicon cond"+code+"'></div><span>"+temp+"</span><br><span class='location'>"+ww_forecast.location+"</span>")
.on("click",show_forecast);
$("#weather-list").animate({
"margin-left": "0"
},1000).show();
update_wunderground_forecast(ww_forecast);
}
});
}
function update_wunderground_forecast(data) {
var temp, precip;
if (data.region == "US" || data.region == "BM" || data.region == "PW") {
temp = data.condition.temp_f+"°F";
precip = data.condition.precip_today_in+" in";
} else {
temp = data.condition.temp_c+"°C";
precip = data.condition.precip_today_metric+" mm";
}
var list = "<li data-role='list-divider' data-theme='a' class='center'>"+data.location+"</li>";
list += "<li data-icon='false' class='center'><div title='"+data.condition.text+"' class='wicon cond"+data.condition.code+"'></div><span data-translate='Now'>"+_("Now")+"</span><br><span>"+temp+"</span><br><span data-translate='Precip'>"+_("Precip")+"</span><span>: "+precip+"</span></li>";
$.each(data.simpleforecast, function(k,attr) {
var precip;
if (data.region == "US" || data.region == "BM" || data.region == "PW") {
precip = attr.qpf_allday["in"];
if (precip === null) precip = 0;
list += "<li data-icon='false' class='center'><span>"+attr.date.monthname_short+" "+attr.date.day+"</span><br><div title='"+attr.conditions+"' class='wicon cond"+attr.icon+"'></div><span data-translate='"+attr.date.weekday_short+"'>"+_(attr.date.weekday_short)+"</span><br><span data-translate='Low'>"+_("Low")+"</span><span>: "+attr.low.fahrenheit+"°F </span><span data-translate='High'>"+_("High")+"</span><span>: "+attr.high.fahrenheit+"°F</span><br><span data-translate='Precip'>"+_("Precip")+"</span><span>: "+precip+" in</span></li>";
} else {
precip = attr.qpf_allday.mm;
if (precip === null) precip = 0;
list += "<li data-icon='false' class='center'><span>"+attr.date.monthname_short+" "+attr.date.day+"</span><br><div title='"+attr.conditions+"' class='wicon cond"+attr.icon+"'></div><span data-translate='"+attr.date.weekday_short+"'>"+_(attr.date.weekday_short)+"</span><br><span data-translate='Low'>"+_("Low")+"</span><span>: "+attr.low.celsius+"°C </span><span data-translate='High'>"+_("High")+"</span><span>: "+attr.high.celsius+"°C</span><br><span data-translate='Precip'>"+_("Precip")+"</span><span>: "+precip+" mm</span></li>";
}
});
var forecast = $("#forecast_list");
forecast.html(list).enhanceWithin();
if (forecast.hasClass("ui-listview")) forecast.listview("refresh");
}
function show_forecast() {
var page = $("#forecast");
page.find(".ui-header > .ui-btn-right").on("click",update_weather);
page.one("pagehide",function(){
page.find(".ui-header > .ui-btn-right").off("click");
});
changePage("#forecast");
return false;
}
function open_panel() {
var panel = $("#sprinklers-settings");
panel.panel("option","classes.modal","needsclick ui-panel-dismiss");
panel.find("a[href='#site-control']").off("click").one("click",function(){
changeFromPanel("site-control");
return false;
});
panel.find("a[href='#about']").off("click").one("click",function(){
changeFromPanel("about");
return false;
});
panel.find(".export_config").off("click").on("click",function(){
export_config();
return false;
});
panel.find(".import_config").off("click").on("click",function(){
import_config();
return false;
});
panel.one("panelclose",function(){
panel.find(".export_config,.import_config").off("click");
});
panel.panel('open');
}
// Device setting management functions
function show_settings() {
var list = "",
page = $("#os-settings"),
timezones, tz, i;
page.find("div[data-role='header'] > .ui-btn-right").on("click",submit_settings);
list = "<li><div class='ui-field-contain'><fieldset>";
if (typeof window.controller.options.tz !== "undefined") {
timezones = ["-12:00","-11:30","-11:00","-10:00","-09:30","-09:00","-08:30","-08:00","-07:00","-06:00","-05:00","-04:30","-04:00","-03:30","-03:00","-02:30","-02:00","+00:00","+01:00","+02:00","+03:00","+03:30","+04:00","+04:30","+05:00","+05:30","+05:45","+06:00","+06:30","+07:00","+08:00","+08:45","+09:00","+09:30","+10:00","+10:30","+11:00","+11:30","+12:00","+12:45","+13:00","+13:45","+14:00"];
tz = window.controller.options.tz-48;
tz = ((tz>=0)?"+":"-")+pad((Math.abs(tz)/4>>0))+":"+((Math.abs(tz)%4)*15/10>>0)+((Math.abs(tz)%4)*15%10);
list += "<label for='o1' class='select'>"+_("Timezone")+"</label><select data-mini='true' id='o1'>";
for (i=0; i<timezones.length; i++) {
list += "<option "+((timezones[i] == tz) ? "selected" : "")+" value='"+timezones[i]+"'>"+timezones[i]+"</option>";
}
list += "</select>";
}
if (typeof window.controller.options.mas !== "undefined") {
list += "<label for='o18' class='select'>"+_("Master Station")+"</label><select data-mini='true' id='o18'><option value='0'>"+_("None")+"</option>";
for (i=0; i<window.controller.stations.snames.length; i++) {
list += "<option "+(((i+1) == window.controller.options.mas) ? "selected" : "")+" value='"+(i+1)+"'>"+window.controller.stations.snames[i]+"</option>";
if (i == 7) break;
}
list += "</select>";
}
if (typeof window.controller.options.hp0 !== "undefined") {
list += "<label for='o12'>"+_("HTTP Port (restart required)")+"</label><input data-mini='true' type='number' pattern='[0-9]*' id='o12' value='"+(window.controller.options.hp1*256+window.controller.options.hp0)+"' />";
}
if (typeof window.controller.options.devid !== "undefined") {
list += "<label for='o26'>"+_("Device ID (restart required)")+"</label><input data-mini='true' type='number' pattern='[0-9]*' max='255' id='o26' value='"+window.controller.options.devid+"' />";
}
list += "<label for='loc'>"+_("Location")+"</label><input data-mini='true' type='text' id='loc' value='"+window.controller.settings.loc+"' />";
if (typeof window.controller.options.ext !== "undefined") {
list += "<label for='o15'>"+_("Extension Boards")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='5' id='o15' value='"+window.controller.options.ext+"' />";
}
if (typeof window.controller.options.sdt !== "undefined") {
list += "<label for='o17'>"+_("Station Delay (seconds)")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='240' id='o17' value='"+window.controller.options.sdt+"' />";
}
if (typeof window.controller.options.mton !== "undefined") {
list += "<label for='o19'>"+_("Master On Delay")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='60' id='o19' value='"+window.controller.options.mton+"' />";
}
if (typeof window.controller.options.mtof !== "undefined") {
list += "<label for='o20'>"+_("Master Off Delay")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='-60' max='60' id='o20' value='"+window.controller.options.mtof+"' />";
}
if (typeof window.controller.options.wl !== "undefined") {
list += "<label for='o23'>"+_("% Watering")+"</label><input data-highlight='true' type='number' pattern='[0-9]*' data-type='range' min='0' max='250' id='o23' value='"+window.controller.options.wl+"' />";
}
if (typeof window.controller.options.ntp !== "undefined") {
list += "<label for='o2'><input data-mini='true' id='o2' type='checkbox' "+((window.controller.options.ntp === 1) ? "checked='checked'" : "")+" />"+_("NTP Sync")+"</label>";
}
if (typeof window.controller.options.ar !== "undefined") {
list += "<label for='o14'><input data-mini='true' id='o14' type='checkbox' "+((window.controller.options.ar === 1) ? "checked='checked'" : "")+" />"+_("Auto Reconnect")+"</label>";
}
if (typeof window.controller.options.seq !== "undefined") {
list += "<label for='o16'><input data-mini='true' id='o16' type='checkbox' "+((window.controller.options.seq === 1) ? "checked='checked'" : "")+" />"+_("Sequential")+"</label>";
}
if (typeof window.controller.options.urs !== "undefined") {
list += "<label for='o21'><input data-mini='true' id='o21' type='checkbox' "+((window.controller.options.urs === 1) ? "checked='checked'" : "")+" />"+_("Use Rain Sensor")+"</label>";
}
if (typeof window.controller.options.rso !== "undefined") {
list += "<label for='o22'><input data-mini='true' id='o22' type='checkbox' "+((window.controller.options.rso === 1) ? "checked='checked'" : "")+" />"+_("Normally Open (Rain Sensor)")+"</label>";
}
if (typeof window.controller.options.ipas !== "undefined") {
list += "<label for='o25'><input data-mini='true' id='o25' type='checkbox' "+((window.controller.options.ipas === 1) ? "checked='checked'" : "")+" />"+_("Ignore Password")+"</label>";
}
list += "</fieldset></div></li>";
page.find(".ui-content").html($('<ul data-role="listview" data-inset="true" id="os-settings-list"></ul>').html(list).listview().enhanceWithin());
page.one("pagehide",function(){
page.find(".ui-header > .ui-btn-right").off("click");
page.find(".ui-content").empty();
});
}
function submit_settings() {
var opt = {},
invalid = false,
isPi = isOSPi(),
keyNames = {1:"tz",2:"ntp",12:"htp",13:"htp2",14:"ar",15:"nbrd",16:"seq",17:"sdt",18:"mas",19:"mton",20:"mtoff",21:"urs",22:"rst",23:"wl",25:"ipas"},
key;
$("#os-settings-list").find(":input").each(function(a,b){
var $item = $(b),
id = $item.attr('id'),
data = $item.val();
switch (id) {
case "o1":
var tz = data.split(":");
tz[0] = parseInt(tz[0],10);
tz[1] = parseInt(tz[1],10);
tz[1]=(tz[1]/15>>0)/4.0;tz[0]=tz[0]+(tz[0]>=0?tz[1]:-tz[1]);
data = ((tz[0]+12)*4)>>0;
break;
case "o2":
case "o14":
case "o16":
case "o21":
case "o22":
case "o25":
data = $item.is(":checked") ? 1 : 0;
if (!data) return true;
break;
}
if (isPi) {
if (id == "loc") {
id = "oloc";
} else {
key = /\d+/.exec(id);
id = "o"+keyNames[key];
}
}
opt[id] = data;
});
if (invalid) return;
$.mobile.loading("show");
send_to_os("/co?pw=&"+$.param(opt)).done(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Settings have been saved"));
});
window.history.back();
update_controller(update_weather);
});
}
// Station managament function
function show_stations() {
var list = "<li class='wrap'>",
page = $("#os-stations"),
isMaster = window.controller.options.mas ? true : false,
hasIR = (typeof window.controller.stations.ignore_rain === "object") ? true : false,
useTableView = (hasIR || isMaster);
page.find("div[data-role='header'] > .ui-btn-right").on("click",submit_stations);
if (useTableView) {
list += "<table><tr><th class='center'>"+_("Station Name")+"</th>";
if (isMaster) list += "<th class='center'>"+_("Activate Master?")+"</th>";
if (hasIR) list += "<th class='center'>"+_("Ignore Rain?")+"</th>";
list += "</tr>";
}
$.each(window.controller.stations.snames,function(i, station) {
if (useTableView) list += "<tr><td>";
list += "<input data-mini='true' id='edit_station_"+i+"' type='text' value='"+station+"' />";
if (useTableView) {
list += "</td>";
if (isMaster) {
if (window.controller.options.mas == i+1) {
list += "<td class='use_master'><p id='um_"+i+"' class='center'>("+_("Master")+")</p></td>";
} else {
list += "<td data-role='controlgroup' data-type='horizontal' class='use_master'><label for='um_"+i+"'><input id='um_"+i+"' type='checkbox' "+((window.controller.stations.masop[parseInt(i/8)]&(1<<(i%8))) ? "checked='checked'" : "")+" /></label></td>";
}
}
if (hasIR) list += "<td data-role='controlgroup' data-type='horizontal' class='use_master'><label for='ir_"+i+"'><input id='ir_"+i+"' type='checkbox' "+((window.controller.stations.ignore_rain[parseInt(i/8)]&(1<<(i%8))) ? "checked='checked'" : "")+" /></label></td></tr>";
list += "</tr>";
}
i++;
});
if (useTableView) list += "</table>";
list += "</li>";
page.find(".ui-content").html($('<ul data-role="listview" data-inset="true" id="os-stations-list"></ul>').html(list).listview().enhanceWithin());
page.one("pagehide",function(){
page.find("div[data-role='header'] > .ui-btn-right").off("click");
page.find(".ui-content").empty();
});
}
function submit_stations() {
var names = {},
invalid = false,
v="",
r="",
bid=0,
bid2=0,
s=0,
s2=0,
m={},
i={},
masop="",
ignore_rain="";
$("#os-stations-list").find(":input,p[id^='um_']").each(function(a,b){
var $item = $(b), id = $item.attr('id'), data = $item.val();
switch (id) {
case "edit_station_" + id.slice("edit_station_".length):
id = "s" + id.split("_")[2];
if (data.length > 32) {
invalid = true;
$item.focus();
showerror(_("Station name must be 32 characters or less"));
return false;
}
names[id] = data;
return true;
case "um_" + id.slice("um_".length):
v = ($item.is(":checked") || $item.prop("tagName") == "P") ? "1".concat(v) : "0".concat(v);
s++;
if (parseInt(s/8) > bid) {
m["m"+bid]=parseInt(v,2); bid++; s=0; v="";
}
return true;
case "ir_" + id.slice("ir_".length):
r = ($item.is(":checked")) ? "1".concat(r) : "0".concat(r);
s2++;
if (parseInt(s2/8) > bid2) {
i["i"+bid2]=parseInt(r,2); bid2++; s2=0; r="";
}
return true;
}
});
m["m"+bid]=parseInt(v,2);
i["i"+bid2]=parseInt(r,2);
if ($("[id^='um_']").length) masop = "&"+$.param(m);
if ($("[id^='ir_']").length) ignore_rain = "&"+$.param(i);
if (invalid) return;
$.mobile.loading("show");
send_to_os("/cs?pw=&"+$.param(names)+masop+ignore_rain).done(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Stations have been updated"));
});
window.history.back();
update_controller();
});
}
// Current status related functions
function get_status() {
var runningTotal = {},
allPnames = [],
color = "",
list = "",
tz = window.controller.options.tz-48,
lastCheck;
if ($.mobile.pageContainer.pagecontainer("getActivePage").attr("id") === "status") {
$("#status .ui-content").empty();
}
tz = ((tz>=0)?"+":"-")+pad((Math.abs(tz)/4>>0))+":"+((Math.abs(tz)%4)*15/10>>0)+((Math.abs(tz)%4)*15%10);
var header = "<span id='clock-s' class='nobr'>"+dateToString(new Date(window.controller.settings.devt*1000))+"</span>"+tzToString(" ","GMT",tz);
if (typeof window.controller.settings.ct === "string" && window.controller.settings.ct !== "0" && typeof window.controller.settings.tu === "string") {
header += " <span>"+window.controller.settings.ct+"°"+window.controller.settings.tu+"</span>";
}
runningTotal.c = window.controller.settings.devt;
var master = window.controller.options.mas,
ptotal = 0;
var open = {};
$.each(window.controller.status, function (i, stn) {
if (stn) open[i] = stn;
});
open = Object.keys(open).length;
if (master && window.controller.status[master-1]) open--;
$.each(window.controller.stations.snames,function(i, station) {
var info = "";
if (master == i+1) {
station += " ("+_("Master")+")";
} else if (window.controller.settings.ps[i][0]) {
var rem=window.controller.settings.ps[i][1];
if (open > 1) {
if (rem > ptotal) ptotal = rem;
} else {
if (window.controller.settings.ps[i][0] !== 99 && rem !== 1) ptotal+=rem;
}
var pid = window.controller.settings.ps[i][0],
pname = pidname(pid);
if (window.controller.status[i] && (pid!=255&&pid!=99)) runningTotal[i] = rem;
allPnames[i] = pname;
info = "<p class='rem'>"+((window.controller.status[i]) ? _("Running") : _("Scheduled"))+" "+pname;
if (pid!=255&&pid!=99) info += " <span id='countdown-"+i+"' class='nobr'>(" + sec2hms(rem) + " "+_("remaining")+")</span>";
info += "</p>";
}
if (window.controller.status[i]) {
color = "green";
} else {
color = "red";
}
list += "<li class='"+color+"'><p class='sname'>"+station+"</p>"+info+"</li>";
});
var footer = "";
var lrdur = window.controller.settings.lrun[2];
if (lrdur !== 0) {
var lrpid = window.controller.settings.lrun[1];
var pname= pidname(lrpid);
footer = '<p>'+pname+' '+_('last ran station')+' '+window.controller.stations.snames[window.controller.settings.lrun[0]]+' '+_('for')+' '+(lrdur/60>>0)+'m '+(lrdur%60)+'s '+_('on')+' '+dateToString(new Date(window.controller.settings.lrun[3]*1000))+'</p>';
}
if (ptotal > 1) {
var scheduled = allPnames.length;
if (!open && scheduled) runningTotal.d = window.controller.options.sdt;
if (open == 1) ptotal += (scheduled-1)*window.controller.options.sdt;
allPnames = getUnique($.grep(allPnames,function(n){return(n);}));
var numProg = allPnames.length;
allPnames = allPnames.join(" "+_("and")+" ");
var pinfo = allPnames+" "+((numProg > 1) ? _("are") : _("is"))+" "+_("running")+" ";
pinfo += "<br><span id='countdown-p' class='nobr'>("+sec2hms(ptotal)+" "+_("remaining")+")</span>";
runningTotal.p = ptotal;
header += "<br>"+pinfo;
} else if (window.controller.settings.rd) {
header +="<br>"+_("Rain delay until")+" "+dateToString(new Date(window.controller.settings.rdst*1000));
} else if (window.controller.options.urs && window.controller.settings.rs) {
header +="<br>"+_("Rain detected");
}
$("#status .ui-content").append(
$('<p class="smaller center"></p>').html(header),
$('<ul data-role="listview" data-inset="true" id="status_list"></ul>').html(list).listview(),
$('<p class="smaller center"></p>').html(footer)
);
removeTimers();
$("#status").one("pagehide",function(){
removeTimers();
var page = $(this);
page.find(".ui-header > .ui-btn-right").off("click");
page.find(".ui-content").empty();
});
if (runningTotal.d !== undefined) {
delete runningTotal.p;
setTimeout(refresh_status,runningTotal.d*1000);
}
lastCheck = new Date().getTime();
window.interval_id = setInterval(function(){
var now = new Date().getTime(),
page = $(".ui-page-active").attr("id"),
diff = now - lastCheck;
if (diff > 3000) {
clearInterval(window.interval_id);
if (page == "status") refresh_status();
}
lastCheck = now;
$.each(runningTotal,function(a,b){
if (b <= 0) {
delete runningTotal[a];
if (a == "p") {
if (page == "status") {
refresh_status();
} else {
clearInterval(window.interval_id);
return;
}
} else {
$("#countdown-"+a).parent("p").text(_("Station delay")).parent("li").removeClass("green").addClass("red");
window.timeout_id = setTimeout(refresh_status,window.controller.options.sdt*1000);
}
} else {
if (a == "c") {
++runningTotal[a];
$("#clock-s").text(dateToString(new Date(runningTotal[a]*1000)));
} else {
--runningTotal[a];
$("#countdown-"+a).text("(" + sec2hms(runningTotal[a]) + " "+_("remaining")+")");
}
}
});
},1000);
}
function refresh_status() {
$.when(
update_controller_status(),
update_controller_settings()
).then(function(){
var page = $(".ui-page-active").attr("id");
if (page == "status") {
get_status();
} else if (page == "sprinklers") {
removeTimers();
check_status();
}
return;
},network_fail);
}
function removeTimers() {
//Remove any status timers that may be running
if (window.interval_id !== undefined) clearInterval(window.interval_id);
if (window.timeout_id !== undefined) clearTimeout(window.timeout_id);
}
// Actually change the status bar
function change_status(seconds,sdelay,color,line,onclick) {
var footer = $("#footer-running");
onclick = onclick || function(){};
removeTimers();
if (seconds > 1) update_timer(seconds,sdelay);
footer.removeClass().addClass(color).html(line).off("click").on("click",onclick).slideDown();
}
// Update status bar based on device status
function check_status() {
var open, ptotal, sample, pid, pname, line, match, tmp, i;
// Handle operation disabled
if (!window.controller.settings.en) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("System Disabled")+"</p>",function(){
areYouSure(_("Do you want to re-enable system operation?"),"",function(){
showLoading("#footer-running");
send_to_os("/cv?pw=&en=1").done(function(){
update_controller(check_status);
});
});
});
return;
}
// Handle open stations
open = {};
for (i=0; i<window.controller.status.length; i++) {
if (window.controller.status[i]) open[i] = window.controller.status[i];
}
if (window.controller.options.mas) delete open[window.controller.options.mas-1];
// Handle more than 1 open station
if (Object.keys(open).length >= 2) {
ptotal = 0;
for (i in open) {
if (open.hasOwnProperty(i)) {
tmp = window.controller.settings.ps[i][1];
if (tmp > ptotal) ptotal = tmp;
}
}
sample = Object.keys(open)[0];
pid = window.controller.settings.ps[sample][0];
pname = pidname(pid);
line = "<div id='running-icon'></div><p id='running-text'>";
line += pname+" "+_("is running on")+" "+Object.keys(open).length+" "+_("stations")+" ";
if (pid!=255&&pid!=99) line += "<span id='countdown' class='nobr'>("+sec2hms(ptotal)+" "+_("remaining")+")</span>";
line += "</p>";
change_status(ptotal,window.controller.options.sdt,"green",line,function(){
changePage("#status");
});
return;
}
// Handle a single station open
match = false;
for (i=0; i<window.controller.stations.snames.length; i++) {
if (window.controller.settings.ps[i][0] && window.controller.status[i] && window.controller.options.mas != i+1) {
match = true;
pid = window.controller.settings.ps[i][0];
pname = pidname(pid);
line = "<div id='running-icon'></div><p id='running-text'>";
line += pname+" "+_("is running on station")+" <span class='nobr'>"+window.controller.stations.snames[i]+"</span> ";
if (pid!=255&&pid!=99) line += "<span id='countdown' class='nobr'>("+sec2hms(window.controller.settings.ps[i][1])+" "+_("remaining")+")</span>";
line += "</p>";
break;
}
}
if (match) {
change_status(window.controller.settings.ps[i][1],window.controller.options.sdt,"green",line,function(){
changePage("#status");
});
return;
}
// Handle rain delay enabled
if (window.controller.settings.rd) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("Rain delay until")+" "+dateToString(new Date(window.controller.settings.rdst*1000))+"</p>",function(){
areYouSure(_("Do you want to turn off rain delay?"),"",function(){
showLoading("#footer-running");
send_to_os("/cv?pw=&rd=0").done(function(){
update_controller(check_status);
});
});
});
return;
}
// Handle rain sensor triggered
if (window.controller.options.urs && window.controller.settings.rs) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("Rain detected")+"</p>");
return;
}
// Handle manual mode enabled
if (window.controller.settings.mm) {
change_status(0,window.controller.options.sdt,"red","<p id='running-text' class='center'>"+_("Manual mode enabled")+"</p>",function(){
areYouSure(_("Do you want to turn off manual mode?"),"",function(){
showLoading("#footer-running");
send_to_os("/cv?pw=&mm=0").done(function(){
update_controller(check_status);
});
});
});
return;
}
$("#footer-running").slideUp();
}
// Handle timer update on the home page for the status bar
function update_timer(total,sdelay) {
window.lastCheck = new Date().getTime();
window.interval_id = setInterval(function(){
var now = new Date().getTime();
var diff = now - window.lastCheck;
if (diff > 3000) {
clearInterval(window.interval_id);
showLoading("#footer-running");
update_controller(check_status);
}
window.lastCheck = now;
if (total <= 0) {
clearInterval(window.interval_id);
showLoading("#footer-running");
if (window.timeout_id !== undefined) clearTimeout(window.timeout_id);
window.timeout_id = setTimeout(function(){
update_controller(check_status);
},(sdelay*1000));
}
else
--total;
$("#countdown").text("(" + sec2hms(total) + " "+_("remaining")+")");
},1000);
}
// Manual control functions
function get_manual() {
var list = "<li data-role='list-divider' data-theme='a'>"+_("Sprinkler Stations")+"</li>",
page = $("#manual");
$.each(window.controller.stations.snames,function (i,station) {
if (window.controller.options.mas == i+1) {
list += '<li data-icon="false" class="center">'+station+' ('+_('Master')+')</li>';
} else {
list += '<li data-icon="false"><a class="mm_station center'+((window.controller.status[i]) ? ' green' : '')+'">'+station+'</a></li>';
}
});
page.find(".ui-content").append(
'<p class="center">'+_('With manual mode turned on, tap a station to toggle it.')+'</p>',
$('<ul data-role="listview" data-inset="true">'+
'<li class="ui-field-contain">'+
'<label for="mmm"><b>'+_('Manual Mode')+'</b></label>'+
'<input type="checkbox" data-on-text="On" data-off-text="Off" data-role="flipswitch" name="mmm" id="mmm"'+(window.controller.settings.mm ? ' checked' : '')+'>'+
'</li>'+
'</ul>').listview(),
$('<ul data-role="listview" data-inset="true" id="mm_list"></ul>').html(list).listview()
);
page.find("#mm_list").find(".mm_station").on("click",toggle);
page.find("#mmm").flipswitch().on("change",flipSwitched);
page.one("pagehide",function(){
page.find(".ui-content").empty();
});
}
function toggle() {
if (!window.controller.settings.mm) {
showerror(_("Manual mode is not enabled. Please enable manual mode then try again."));
return false;
}
var anchor = $(this),
list = $("#mm_list"),
listitems = list.children("li:not(li.ui-li-divider)"),
item = anchor.closest("li:not(li.ui-li-divider)"),
currPos = listitems.index(item) + 1;
if (anchor.hasClass("green")) {
send_to_os("/sn"+currPos+"=0").then(
function(){
update_controller_status();
},
function(){
anchor.addClass("green");
}
);
anchor.removeClass("green");
} else {
send_to_os("/sn"+currPos+"=1&t=0").then(
function(){
update_controller_status();
},
function(){
anchor.removeClass("green");
}
);
anchor.addClass("green");
}
return false;
}
// Runonce functions
function get_runonce() {
var list = "<p class='center'>"+_("Zero value excludes the station from the run-once program.")+"</p>",
runonce = $("#runonce_list"),
page = $("#runonce"),
i=0, n=0,
quickPick, data, progs, rprogs, z, program;
page.find("div[data-role='header'] > .ui-btn-right").on("click",submit_runonce);
progs = [];
if (window.controller.programs.pd.length) {
for (z=0; z < window.controller.programs.pd.length; z++) {
program = read_program(window.controller.programs.pd[z]);
var prog = [],
set_stations = program.stations.split("");
for (i=0;i<window.controller.stations.snames.length;i++) {
prog.push((parseInt(set_stations[i])) ? program.duration : 0);
}
progs.push(prog);
}
}
rprogs = progs;
quickPick = "<select data-mini='true' name='rprog' id='rprog'><option value='s' selected='selected'>"+_("Quick Programs")+"</option>";
data = localStorage.getItem("runonce");
if (data !== null) {
data = JSON.parse(data);
runonce.find(":input[data-type='range']").each(function(a,b){
$(b).val(data[i]/60);
i++;
});
rprogs.l = data;
quickPick += "<option value='l' >"+_("Last Used Program")+"</option>";
}
for (i=0; i<progs.length; i++) {
quickPick += "<option value='"+i+"'>"+_("Program")+" "+(i+1)+"</option>";
}
quickPick += "</select>";
list += quickPick+"<form>";
$.each(window.controller.stations.snames,function(i, station) {
list += "<div class='ui-field-contain duration-input'><label for='zone-"+n+"'>"+station+":</label><button data-mini='true' name='zone-"+n+"' id='zone-"+n+"' value='0'>0s</button></div>";
n++;
});
list += "</form><a class='ui-btn ui-corner-all ui-shadow rsubmit' href='#'>"+_("Submit")+"</a><a class='ui-btn ui-btn-b ui-corner-all ui-shadow rreset' href='#'>"+_("Reset")+"</a>";
runonce.html(list);
$("#rprog").on("change",function(){
var prog = $(this).val();
if (prog == "s") {
reset_runonce();
return;
}
if (typeof rprogs[prog] === "undefined") return;
fill_runonce(rprogs[prog]);
});
runonce.on("click",".rsubmit",submit_runonce).on("click",".rreset",reset_runonce);
runonce.find("[id^='zone-']").on("click",function(){
var dur = $(this),
name = runonce.find("label[for='"+dur.attr("id")+"']").text().slice(0,-1);
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
if (result > 0) {
dur.addClass("green");
} else {
dur.removeClass("green");
}
},65535);
return false;
});
runonce.enhanceWithin();
page.one("pagehide",function(){
page.find(".ui-header > .ui-btn-right").off("click");
$(this).find(".ui-content").empty();
});
}
function reset_runonce() {
$("#runonce").find("[id^='zone-']").val(0).text("0s").removeClass("green");
return false;
}
function fill_runonce(data){
var i=0;
$("#runonce").find("[id^='zone-']").each(function(a,b){
var ele = $(b);
ele.val(data[i]).text(dhms2str(sec2dhms(data[i])));
if (data[i] > 0) {
ele.addClass("green");
} else {
ele.removeClass("green");
}
i++;
});
}
function submit_runonce(runonce) {
if (!(runonce instanceof Array)) {
runonce = [];
$("#runonce").find("[id^='zone-']").each(function(a,b){
runonce.push(parseInt($(b).val()));
});
runonce.push(0);
}
localStorage.setItem("runonce",JSON.stringify(runonce));
send_to_os("/cr?pw=&t="+JSON.stringify(runonce)).done(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Run-once program has been scheduled"));
});
update_controller_status();
update_controller_settings();
window.history.back();
});
}
// Preview functions
function get_preview() {
var date = $("#preview_date").val(),
$timeline = $("#timeline"),
preview_data, process_programs, check_match, run_sched, time_to_text, day;
if (date === "") return;
date = date.split("-");
day = new Date(date[0],date[1]-1,date[2]);
$.mobile.loading("show");
$("#timeline-navigation").hide();
process_programs = function (month,day,year) {
preview_data = [];
var devday = Math.floor(window.controller.settings.devt/(60*60*24)),
simminutes = 0,
simt = Date.UTC(year,month-1,day,0,0,0,0),
simday = (simt/1000/3600/24)>>0,
st_array = new Array(window.controller.settings.nbrd*8),
pid_array = new Array(window.controller.settings.nbrd*8),
et_array = new Array(window.controller.settings.nbrd*8),
busy, match_found, prog;
for(var sid=0;sid<window.controller.settings.nbrd;sid++) {
st_array[sid]=0;pid_array[sid]=0;et_array[sid]=0;
}
do {
busy=0;
match_found=0;
for(var pid=0;pid<window.controller.programs.pd.length;pid++) {
prog=window.controller.programs.pd[pid];
if(check_match(prog,simminutes,simt,simday,devday)) {
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {
var bid=sid>>3;var s=sid%8;
if(window.controller.options.mas==(sid+1)) continue; // skip master station
if(prog[7+bid]&(1<<s)) {
et_array[sid]=prog[6]*window.controller.options.wl/100>>0;pid_array[sid]=pid+1;
match_found=1;
}
}
}
}
if(match_found) {
var acctime=simminutes*60;
if(window.controller.options.seq) {
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {
if(et_array[sid]) {
st_array[sid]=acctime;acctime+=et_array[sid];
et_array[sid]=acctime;acctime+=window.controller.options.sdt;
busy=1;
}
}
} else {
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {
if(et_array[sid]) {
st_array[sid]=simminutes*60;
et_array[sid]=simminutes*60+et_array[sid];
busy=1;
}
}
}
}
if (busy) {
var endminutes=run_sched(simminutes*60,st_array,pid_array,et_array,simt)/60>>0;
if(window.controller.options.seq&&simminutes!=endminutes) simminutes=endminutes;
else simminutes++;
for(sid=0;sid<window.controller.settings.nbrd*8;sid++) {st_array[sid]=0;pid_array[sid]=0;et_array[sid]=0;}
} else {
simminutes++;
}
} while(simminutes<24*60);
};
check_match = function (prog,simminutes,simt,simday,devday) {
if(prog[0]===0) return 0;
if ((prog[1]&0x80)&&(prog[2]>1)) {
var dn=prog[2],
drem=prog[1]&0x7f;
if((simday%dn)!=((devday+drem)%dn)) return 0;
} else {
var date = new Date(simt);
var wd=(date.getUTCDay()+6)%7;
if((prog[1]&(1<<wd))===0) return 0;
var dt=date.getUTCDate();
if((prog[1]&0x80)&&(prog[2]===0)) {if((dt%2)!==0) return 0;}
if((prog[1]&0x80)&&(prog[2]==1)) {
if(dt==31) return 0;
else if (dt==29 && date.getUTCMonth()==1) return 0;
else if ((dt%2)!=1) return 0;
}
}
if(simminutes<prog[3] || simminutes>prog[4]) return 0;
if(prog[5]===0) return 0;
if(((simminutes-prog[3])/prog[5]>>0)*prog[5] == (simminutes-prog[3])) {
return 1;
}
return 0;
};
run_sched = function (simseconds,st_array,pid_array,et_array,simt) {
var endtime=simseconds;
for(var sid=0;sid<window.controller.settings.nbrd*8;sid++) {
if(pid_array[sid]) {
if(window.controller.options.seq==1) {
if((window.controller.options.mas>0)&&(window.controller.options.mas!=sid+1)&&(window.controller.stations.masop[sid>>3]&(1<<(sid%8))))
preview_data.push({
'start': (st_array[sid]+window.controller.options.mton),
'end': (et_array[sid]+window.controller.options.mtof),
'content':'',
'className':'master',
'shortname':'M',
'group':'Master'
});
time_to_text(sid,st_array[sid],pid_array[sid],et_array[sid],simt);
endtime=et_array[sid];
} else {
time_to_text(sid,simseconds,pid_array[sid],et_array[sid],simt);
if((window.controller.options.mas>0)&&(window.controller.options.mas!=sid+1)&&(window.controller.stations.masop[sid>>3]&(1<<(sid%8))))
endtime=(endtime>et_array[sid])?endtime:et_array[sid];
}
}
}
if(window.controller.options.seq===0&&window.controller.options.mas>0) {
preview_data.push({
'start': simseconds,
'end': endtime,
'content':'',
'className':'master',
'shortname':'M',
'group':'Master'
});
}
return endtime;
};
time_to_text = function (sid,start,pid,end,simt) {
var className = "program-"+((pid+3)%4);
if ((window.controller.settings.rd!==0)&&(simt+start+(window.controller.options.tz-48)*900<=window.controller.settings.rdst)) className="delayed";
preview_data.push({
'start': start,
'end': end,
'className':className,
'content':'P'+pid,
'shortname':'S'+(sid+1),
'group': window.controller.stations.snames[sid]
});
};
process_programs(date[1],date[2],date[0]);
var empty = true;
if (!preview_data.length) {
$timeline.html("<p align='center'>"+_("No stations set to run on this day.")+"</p>");
} else {
empty = false;
var shortnames = [];
$.each(preview_data, function(){
this.start = new Date(date[0],date[1]-1,date[2],0,0,this.start);
this.end = new Date(date[0],date[1]-1,date[2],0,0,this.end);
shortnames[this.group] = this.shortname;
});
var options = {
'width': '100%',
'editable': false,
'axisOnTop': true,
'eventMargin': 10,
'eventMarginAxis': 0,
'min': new Date(date[0],date[1]-1,date[2],0),
'max': new Date(date[0],date[1]-1,date[2],24),
'selectable': true,
'showMajorLabels': false,
'zoomMax': 1000 * 60 * 60 * 24,
'zoomMin': 1000 * 60 * 60,
'groupsChangeable': false,
'showNavigation': false,
'groupsOrder': 'none',
'groupMinHeight': 20
};
var timeline = new links.Timeline(document.getElementById('timeline'),options);
links.events.addListener(timeline, "select", function(){
var row,
sel = timeline.getSelection();
if (sel.length) {
if (typeof sel[0].row !== "undefined") {
row = sel[0].row;
}
}
if (row === undefined) return;
var content = $(".timeline-event-content")[row];
var pid = parseInt($(content).html().substr(1)) - 1;
changePage("#programs",{
'programToExpand': pid
});
});
$.mobile.window.on("resize",function(){
timeline.redraw();
});
timeline.draw(preview_data);
if ($.mobile.window.width() <= 480) {
var currRange = timeline.getVisibleChartRange();
if ((currRange.end.getTime() - currRange.start.getTime()) > 6000000) timeline.setVisibleChartRange(currRange.start,new Date(currRange.start.getTime()+6000000));
}
$timeline.find(".timeline-groups-text").each(function(a,b){
var stn = $(b);
var name = shortnames[stn.text()];
stn.attr("data-shortname",name);
});
$(".timeline-groups-axis").children().first().html("<div class='timeline-axis-text center dayofweek' data-shortname='"+getDayName(day,"short")+"'>"+getDayName(day)+"</div>");
if (isAndroid) {
var navi = $("#timeline-navigation");
navi.find(".ui-icon-plus").off("click").on("click",function(){
timeline.zoom(0.4);
return false;
});
navi.find(".ui-icon-minus").off("click").on("click",function(){
timeline.zoom(-0.4);
return false;
});
navi.find(".ui-icon-carat-l").off("click").on("click",function(){
timeline.move(-0.2);
return false;
});
navi.find(".ui-icon-carat-r").off("click").on("click",function(){
timeline.move(0.2);
return false;
});
navi.show();
}
}
$.mobile.loading("hide");
}
function changeday(dir) {
var inputBox = $("#preview_date");
var date = inputBox.val();
if (date === "") return;
date = date.split("-");
var nDate = new Date(date[0],date[1]-1,date[2]);
nDate.setDate(nDate.getDate() + dir);
var m = pad(nDate.getMonth()+1);
var d = pad(nDate.getDate());
inputBox.val(nDate.getFullYear() + "-" + m + "-" + d);
get_preview();
}
// Logging functions
function get_logs() {
var logs = $("#logs"),
placeholder = $("#placeholder"),
logs_list = $("#logs_list"),
zones = $("#zones"),
graph_sort = $("#graph_sort"),
log_options = $("#log_options"),
data = [],
seriesChange = function() {
var grouping = logs.find("input:radio[name='g']:checked").val(),
pData = [],
sortedData;
sortedData = sortData(grouping);
zones.find("td[zone_num]:not('.unchecked')").each(function() {
var key = $(this).attr("zone_num");
if (!sortedData[key].length) sortedData[key]=[[0,0]];
if (key && sortedData[key]) {
if ((grouping == 'h') || (grouping == 'm') || (grouping == 'd'))
pData.push({
data:sortedData[key],
label:$(this).attr("name"),
color:parseInt(key),
bars: { order:key, show: true, barWidth:0.08}
});
else if (grouping == 'n')
pData.push({
data:sortedData[key],
label:$(this).attr("name"),
color:parseInt(key),
lines: { show:true }
});
}
});
if (grouping=='h') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { min: 0, max: 24, tickDecimals: 0, tickSize: 1 }
});
} else if (grouping=='d') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { tickDecimals: 0, min: -0.4, max: 6.4,
tickFormatter: function(v) { var dow=[_("Sun"),_("Mon"),_("Tue"),_("Wed"),_("Thr"),_("Fri"),_("Sat")]; return dow[v]; } }
});
} else if (grouping=='m') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { tickDecimals: 0, min: 0.6, max: 12.4, tickSize: 1,
tickFormatter: function(v) { var mon=["",_("Jan"),_("Feb"),_("Mar"),_("Apr"),_("May"),_("Jun"),_("Jul"),_("Aug"),_("Sep"),_("Oct"),_("Nov"),_("Dec")]; return mon[v]; } }
});
} else if (grouping=='n') {
$.plot(placeholder, pData, {
grid: { hoverable: true },
yaxis: {min: 0, tickFormatter: function(val, axis) { return val < axis.max ? Math.round(val*100)/100 : "min";} },
xaxis: { mode: "time", min:sortedData.min.getTime(), max:sortedData.max.getTime()}
});
}
},
sortData = function(grouping) {
var sortedData = [],
max, min;
switch (grouping) {
case "h":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],[21,0],[22,0],[23,0]];
}
break;
case "m":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0]];
}
break;
case "d":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0]];
}
break;
case "n":
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [];
}
break;
}
$.each(data,function(a,b){
var stamp = parseInt(b[3] * 1000),
station = parseInt(b[1]),
date = new Date(stamp),
duration = parseInt(b[2]/60),
key;
switch (grouping) {
case "h":
key = date.getUTCHours();
break;
case "m":
key = date.getUTCMonth() + 1;
break;
case "d":
key = date.getUTCDay();
break;
case "n":
sortedData[station].push([stamp-1,0]);
sortedData[station].push([stamp,duration]);
sortedData[station].push([stamp+(duration*100*1000)+1,0]);
break;
}
if (grouping != "n" && duration > 0) {
sortedData[station][key][1] += duration;
}
if (min === undefined || min > date) min = date;
if (max === undefined || max < date) max = new Date(date.getTime() + (duration*100*1000)+1);
});
sortedData.min = min;
sortedData.max = max;
return sortedData;
},
toggleZone = function() {
var zone = $(this);
if (zone.hasClass("legendColorBox")) {
zone.find("div div").toggleClass("hideZone");
zone.next().toggleClass("unchecked");
} else if (zone.hasClass("legendLabel")) {
zone.prev().find("div div").toggleClass("hideZone");
zone.toggleClass("unchecked");
}
seriesChange();
},
showArrows = function() {
var height = zones.height(),
sleft = zones.scrollLeft(),
right = $("#graphScrollRight"),
left = $("#graphScrollLeft");
if (sleft > 13) {
left.show().css("margin-top",(height/2)-12.5);
} else {
left.hide();
}
var total = zones.find("table").width(), container = zones.width();
if ((total-container) > 0 && sleft < ((total-container) - 13)) {
right.show().css({
"margin-top":(height/2)-12.5,
"left":container
});
} else {
right.hide();
}
},
success = function(items){
if (items.length < 1) {
$.mobile.loading("hide");
reset_logs_page();
return;
}
data = items;
updateView();
objToEmail(".email_logs",data);
$.mobile.loading("hide");
},
updateView = function() {
if ($("#log_graph").prop("checked")) {
prepGraph();
} else {
prepTable();
}
},
prepGraph = function() {
if (data.length < 1) {
reset_logs_page();
return;
}
logs_list.empty().hide();
var state = ($.mobile.window.height() > 680) ? "expand" : "collapse";
setTimeout(function(){log_options.collapsible(state);},100);
placeholder.show();
var zones = $("#zones");
var freshLoad = zones.find("table").length;
zones.show();
graph_sort.show();
if (!freshLoad) {
var output = '<div class="ui-btn ui-btn-icon-notext ui-icon-carat-l btn-no-border" id="graphScrollLeft"></div><div class="ui-btn ui-btn-icon-notext ui-icon-carat-r btn-no-border" id="graphScrollRight"></div><table class="smaller"><tbody><tr>';
for (i=0; i<window.controller.stations.snames.length; i++) {
output += '<td class="legendColorBox"><div><div></div></div></td><td id="z'+i+'" zone_num='+i+' name="'+window.controller.stations.snames[i] + '" class="legendLabel">'+window.controller.stations.snames[i]+'</td>';
}
output += '</tr></tbody></table>';
zones.empty().append(output).enhanceWithin();
zones.find("td").on("click",toggleZone);
zones.find("#graphScrollLeft,#graphScrollRight").on("click",scrollZone);
}
seriesChange();
i = 0;
if (!freshLoad) {
zones.find("td.legendColorBox div div").each(function(a,b){
var border = $(placeholder.find(".legendColorBox div div").get(i)).css("border");
//Firefox and IE fix
if (border === "") {
border = $(placeholder.find(".legendColorBox div div").get(i)).attr("style").split(";");
$.each(border,function(a,b){
var c = b.split(":");
if (c[0] == "border") {
border = c[1];
return false;
}
});
}
$(b).css("border",border);
i++;
});
showArrows();
}
},
prepTable = function(){
if (data.length < 1) {
reset_logs_page();
return;
}
placeholder.empty().hide();
var table_header = "<table><thead><tr><th data-priority='1'>"+_("Runtime")+"</th><th data-priority='2'>"+_("Date/Time")+"</th></tr></thead><tbody>",
html = "<div data-role='collapsible-set' data-inset='true' data-theme='b' data-collapsed-icon='arrow-d' data-expanded-icon='arrow-u'>",
sortedData = [],
ct, k;
zones.hide();
graph_sort.hide();
logs_list.show();
for (i=0; i<window.controller.stations.snames.length; i++) {
sortedData[i] = [];
}
$.each(data,function(a,b){
sortedData[parseInt(b[1])].push([parseInt(b[3] * 1000),parseInt(b[2])]);
});
for (i=0; i<sortedData.length; i++) {
ct=sortedData[i].length;
if (ct === 0) continue;
html += "<div data-role='collapsible' data-collapsed='true'><h2><div class='ui-btn-up-c ui-btn-corner-all custom-count-pos'>"+ct+" "+((ct == 1) ? _("run") : _("runs"))+"</div>"+window.controller.stations.snames[i]+"</h2>"+table_header;
for (k=0; k<sortedData[i].length; k++) {
var mins = Math.round(sortedData[i][k][1]/60);
var date = new Date(sortedData[i][k][0]);
html += "<tr><td>"+mins+" "+((mins == 1) ? _("min") : _("mins"))+"</td><td>"+dateToString(date).slice(0,-3)+"</td></tr>";
}
html += "</tbody></table></div>";
}
log_options.collapsible("collapse");
logs_list.html(html+"</div>").enhanceWithin();
},
reset_logs_page = function() {
placeholder.empty().hide();
log_options.collapsible("expand");
zones.empty().hide();
graph_sort.hide();
logs_list.show().html(_("No entries found in the selected date range"));
},
fail = function(){
$.mobile.loading("hide");
reset_logs_page();
},
dates = function() {
var sDate = $("#log_start").val().split("-"),
eDate = $("#log_end").val().split("-");
return {
start: new Date(sDate[0],sDate[1]-1,sDate[2]),
end: new Date(eDate[0],eDate[1]-1,eDate[2])
};
},
parms = function() {
return "start=" + (dates().start.getTime() / 1000) + "&end=" + ((dates().end.getTime() / 1000) + 86340);
},
requestData = function() {
var endtime = dates().end.getTime() / 1000,
starttime = dates().start.getTime() / 1000;
if (endtime < starttime) {
fail();
showerror(_("Start time cannot be greater than end time"));
return;
}
var delay = 0;
$.mobile.loading("show");
if (!isOSPi() && (endtime - starttime) > 604800) {
showerror(_("The requested time span exceeds the maxiumum of 7 days and has been adjusted"),3500);
var nDate = dates().start;
nDate.setDate(nDate.getDate() + 7);
var m = pad(nDate.getMonth()+1);
var d = pad(nDate.getDate());
$("#log_end").val(nDate.getFullYear() + "-" + m + "-" + d);
delay = 500;
}
setTimeout(function(){
send_to_os("/jl?"+parms(),"json").then(success,fail);
},delay);
},
i;
logs.find("input").blur();
$.mobile.loading("show");
//Update left/right arrows when zones are scrolled on log page
$("#zones").scroll(showArrows);
$.mobile.window.resize(function(){
showArrows();
seriesChange();
});
//Automatically update the log viewer when changing the date range
if (isiOS) {
$("#log_start,#log_end").on("blur",requestData);
} else {
$("#log_start,#log_end").change(function(){
clearTimeout(window.logtimeout);
window.logtimeout = setTimeout(requestData,1000);
});
}
//Automatically update log viewer when switching graphing method
graph_sort.find("input[name='g']").change(seriesChange);
//Bind refresh button
logs.find(".ui-header > .ui-btn-right").on("click",requestData);
//Bind view change buttons
logs.find("input:radio[name='log_type']").change(updateView);
//Show tooltip (station name) when point is clicked on the graph
placeholder.on("plothover",function(event, pos, item) {
$("#tooltip").remove();
clearTimeout(window.hovertimeout);
if (item) window.hovertimeout = setTimeout(function(){showTooltip(item.pageX, item.pageY, item.series.label, item.series.color);}, 100);
});
logs.one("pagehide",function(){
$.mobile.window.off("resize");
placeholder.off("plothover");
zones.off("scroll");
logs.off("change");
$("#log_start,#log_end").off("change");
logs.find(".ui-header > .ui-btn-right").off("change");
logs.find("input:radio[name='log_type']").off("change");
graph_sort.find("input[name='g']").off("change");
reset_logs_page();
});
requestData();
}
function scrollZone() {
var dir = ($(this).attr("id") == "graphScrollRight") ? "+=" : "-=";
var zones = $("#zones");
var w = zones.width();
zones.animate({scrollLeft: dir+w});
}
// Program management functions
function get_programs(pid) {
var programs = $("#programs"),
list = programs.find(".ui-content");
list.html($(make_all_programs())).enhanceWithin();
programs.find(".ui-collapsible-set").collapsibleset().on({
collapsiblecollapse: function(){
$(this).find(".ui-collapsible-content").empty();
},
collapsibleexpand: function(){
expandProgram($(this));
}
},".ui-collapsible");
update_program_header();
programs
.one("pagehide",function(){
$(this).find(".ui-content").empty();
})
.one("pagebeforeshow",function(){
if (typeof pid !== "number" && window.controller.programs.pd.length === 1) pid = 0;
if (typeof pid === "number") {
programs.find("fieldset[data-collapsed='false']").collapsible("collapse");
$("#program-"+pid).collapsible("expand");
}
});
}
function expandProgram(program) {
var id = parseInt(program.attr("id").split("-")[1]),
html = $(make_program(id));
program.find(".ui-collapsible-content").html(html).enhanceWithin();
program.find("input[name^='rad_days']").on("change",function(){
var progid = $(this).attr('id').split("-")[1], type = $(this).val().split("-")[0], old;
type = type.split("_")[1];
if (type == "n") {
old = "week";
} else {
old = "n";
}
$("#input_days_"+type+"-"+progid).show();
$("#input_days_"+old+"-"+progid).hide();
});
program.find("[id^='submit-']").on("click",function(){
submit_program($(this).attr("id").split("-")[1]);
return false;
});
program.find("[id^='duration-'],[id^='interval-']").on("click",function(){
var dur = $(this),
granularity = dur.attr("id").match("interval") ? 1 : 0,
name = program.find("label[for='"+dur.attr("id")+"']").text();
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
},65535,granularity);
return false;
});
program.find("[id^='s_checkall-']").on("click",function(){
var id = $(this).attr("id").split("-")[1];
program.find("[id^='station_'][id$='-"+id+"']").prop("checked",true).checkboxradio("refresh");
return false;
});
program.find("[id^='s_uncheckall-']").on("click",function(){
var id = $(this).attr("id").split("-")[1];
program.find("[id^='station_'][id$='-"+id+"']").prop("checked",false).checkboxradio("refresh");
return false;
});
program.find("[id^='delete-']").on("click",function(){
delete_program($(this).attr("id").split("-")[1]);
return false;
});
program.find("[id^='run-']").on("click",function(){
var id = $(this).attr("id").split("-")[1],
durr = parseInt($("#duration-"+id).val()),
stations = $("[id^='station_'][id$='-"+id+"']"),
runonce = [];
$.each(stations,function(a,b){
if ($(b).is(":checked")) {
runonce.push(durr);
} else {
runonce.push(0);
}
});
runonce.push(0);
submit_runonce(runonce);
return false;
});
fixInputClick(program);
}
// Translate program array into easier to use data
function read_program(program) {
var days0 = program[1],
days1 = program[2],
even = false,
odd = false,
interval = false,
days = "",
stations = "",
newdata = {};
newdata.en = program[0];
newdata.start = program[3];
newdata.end = program[4];
newdata.interval = program[5];
newdata.duration = program[6];
for (var n=0; n < window.controller.programs.nboards; n++) {
var bits = program[7+n];
for (var s=0; s < 8; s++) {
stations += (bits&(1<<s)) ? "1" : "0";
}
}
newdata.stations = stations;
if((days0&0x80)&&(days1>1)){
//This is an interval program
days=[days1,days0&0x7f];
interval = true;
} else {
//This is a weekly program
for(var d=0;d<7;d++) {
if (days0&(1<<d)) {
days += "1";
} else {
days += "0";
}
}
if((days0&0x80)&&(days1===0)) {even = true;}
if((days0&0x80)&&(days1==1)) {odd = true;}
}
newdata.days = days;
newdata.is_even = even;
newdata.is_odd = odd;
newdata.is_interval = interval;
return newdata;
}
// Translate program ID to it's name
function pidname(pid) {
var pname = _("Program")+" "+pid;
if(pid==255||pid==99) pname=_("Manual program");
if(pid==254||pid==98) pname=_("Run-once program");
return pname;
}
// Check each program and change the background color to red if disabled
function update_program_header() {
$("#programs_list").find("[id^=program-]").each(function(a,b){
var item = $(b),
heading = item.find(".ui-collapsible-heading-toggle"),
en = window.controller.programs.pd[a][0];
if (en) {
heading.removeClass("red");
} else {
heading.addClass("red");
}
});
}
//Make the list of all programs
function make_all_programs() {
if (window.controller.programs.pd.length === 0) {
return "<p class='center'>"+_("You have no programs currently added. Tap the Add button on the top right corner to get started.")+"</p>";
}
var list = "<p class='center'>"+_("Click any program below to expand/edit. Be sure to save changes by hitting submit below.")+"</p><div data-role='collapsible-set'>";
for (var i = 0; i < window.controller.programs.pd.length; i++) {
list += "<fieldset id='program-"+i+"' data-role='collapsible'><legend>"+_("Program")+" "+(i+1)+"</legend>";
list += "</fieldset>";
}
return list+"</div>";
}
//Generate a new program view
function fresh_program() {
var list = "<fieldset id='program-new'>";
list +=make_program("new");
list += "</fieldset>";
return list;
}
function make_program(n) {
var week = [_("M"),_("T"),_("W"),_("R"),_("F"),_("Sa"),_("Su")],
list = "",
days, i, j, set_stations, program;
if (n === "new") {
program = {"en":0,"is_interval":0,"is_even":0,"is_odd":0,"duration":0,"interval":0,"start":0,"end":0,"days":[0,0]};
} else {
program = read_program(window.controller.programs.pd[n]);
}
if (typeof program.days === "string") {
days = program.days.split("");
for(i=days.length;i--;) days[i] = days[i]|0;
} else {
days = [0,0,0,0,0,0,0];
}
if (typeof program.stations !== "undefined") {
set_stations = program.stations.split("");
for(i=set_stations.length;i--;) set_stations[i] = set_stations[i]|0;
}
list += "<label for='en-"+n+"'><input data-mini='true' type='checkbox' "+((program.en || n==="new") ? "checked='checked'" : "")+" name='en-"+n+"' id='en-"+n+"'>"+_("Enabled")+"</label>";
list += "<fieldset data-role='controlgroup' data-type='horizontal' class='center'>";
list += "<input data-mini='true' type='radio' name='rad_days-"+n+"' id='days_week-"+n+"' value='days_week-"+n+"' "+((program.is_interval) ? "" : "checked='checked'")+"><label for='days_week-"+n+"'>"+_("Weekly")+"</label>";
list += "<input data-mini='true' type='radio' name='rad_days-"+n+"' id='days_n-"+n+"' value='days_n-"+n+"' "+((program.is_interval) ? "checked='checked'" : "")+"><label for='days_n-"+n+"'>"+_("Interval")+"</label>";
list += "</fieldset><div id='input_days_week-"+n+"' "+((program.is_interval) ? "style='display:none'" : "")+">";
list += "<fieldset data-role='controlgroup' data-type='horizontal' class='center'><p class='tight'>"+_("Restrictions")+"</p>";
list += "<input data-mini='true' type='radio' name='rad_rst-"+n+"' id='days_norst-"+n+"' value='days_norst-"+n+"' "+((!program.is_even && !program.is_odd) ? "checked='checked'" : "")+"><label for='days_norst-"+n+"'>"+_("None")+"</label>";
list += "<input data-mini='true' type='radio' name='rad_rst-"+n+"' id='days_odd-"+n+"' value='days_odd-"+n+"' "+((!program.is_even && program.is_odd) ? "checked='checked'" : "")+"><label for='days_odd-"+n+"'>"+_("Odd Days")+"</label>";
list += "<input data-mini='true' type='radio' name='rad_rst-"+n+"' id='days_even-"+n+"' value='days_even-"+n+"' "+((!program.is_odd && program.is_even) ? "checked='checked'" : "")+"><label for='days_even-"+n+"'>"+_("Even Days")+"</label>";
list += "</fieldset>";
list += "<fieldset data-type='horizontal' data-role='controlgroup' class='center'><p class='tight'>"+_("Days of the Week")+"</p>";
for (j=0; j<week.length; j++) {
list += "<label for='d"+j+"-"+n+"'><input data-mini='true' type='checkbox' "+((!program.is_interval && days[j]) ? "checked='checked'" : "")+" name='d"+j+"-"+n+"' id='d"+j+"-"+n+"'>"+week[j]+"</label>";
}
list += "</fieldset></div>";
list += "<div "+((program.is_interval) ? "" : "style='display:none'")+" id='input_days_n-"+n+"' class='ui-grid-a'>";
list += "<div class='ui-block-a'><label for='every-"+n+"'>"+_("Interval (Days)")+"</label><input data-mini='true' type='number' name='every-"+n+"' pattern='[0-9]*' id='every-"+n+"' value='"+program.days[0]+"'></div>";
list += "<div class='ui-block-b'><label for='starting-"+n+"'>"+_("Starting In")+"</label><input data-mini='true' type='number' name='starting-"+n+"' pattern='[0-9]*' id='starting-"+n+"' value='"+program.days[1]+"'></div>";
list += "</div>";
list += "<fieldset data-role='controlgroup'><legend>"+_("Stations:")+"</legend>";
for (j=0; j<window.controller.stations.snames.length; j++) {
list += "<label for='station_"+j+"-"+n+"'><input data-mini='true' type='checkbox' "+(((typeof set_stations !== "undefined") && set_stations[j]) ? "checked='checked'" : "")+" name='station_"+j+"-"+n+"' id='station_"+j+"-"+n+"'>"+window.controller.stations.snames[j]+"</label>";
}
list += "</fieldset>";
list += "<fieldset data-role='controlgroup' data-type='horizontal' class='center'>";
list += "<a class='ui-btn ui-mini' name='s_checkall-"+n+"' id='s_checkall-"+n+"'>"+_("Check All")+"</a>";
list += "<a class='ui-btn ui-mini' name='s_uncheckall-"+n+"' id='s_uncheckall-"+n+"'>"+_("Uncheck All")+"</a>";
list += "</fieldset>";
list += "<div class='ui-grid-a'>";
list += "<div class='ui-block-a'><label for='start-"+n+"'>"+_("Start Time")+"</label><input data-mini='true' type='time' name='start-"+n+"' id='start-"+n+"' value='"+pad(parseInt(program.start/60)%24)+":"+pad(program.start%60)+"'></div>";
list += "<div class='ui-block-b'><label for='end-"+n+"'>"+_("End Time")+"</label><input data-mini='true' type='time' name='end-"+n+"' id='end-"+n+"' value='"+pad(parseInt(program.end/60)%24)+":"+pad(program.end%60)+"'></div>";
list += "</div>";
list += "<div class='ui-grid-a'>";
list += "<div class='ui-block-a'><label for='duration-"+n+"'>"+_("Station Duration")+"</label><button data-mini='true' name='duration-"+n+"' id='duration-"+n+"' value='"+program.duration+"'>"+dhms2str(sec2dhms(program.duration))+"</button></div>";
list += "<div class='ui-block-b'><label for='interval-"+n+"'>"+_("Program Interval")+"</label><button data-mini='true' name='interval-"+n+"' id='interval-"+n+"' value='"+program.interval*60+"'>"+dhms2str(sec2dhms(program.interval*60))+"</button></div>";
list += "</div>";
if (n === "new") {
list += "<input data-mini='true' type='submit' name='submit-"+n+"' id='submit-"+n+"' value='"+_("Save New Program")+"'>";
} else {
list += "<input data-mini='true' type='submit' name='submit-"+n+"' id='submit-"+n+"' value='"+_("Save Changes to Program")+" "+(n + 1)+"'>";
list += "<input data-mini='true' type='submit' name='run-"+n+"' id='run-"+n+"' value='"+_("Run Program")+" "+(n + 1)+"'>";
list += "<input data-mini='true' data-theme='b' type='submit' name='delete-"+n+"' id='delete-"+n+"' value='"+_("Delete Program")+" "+(n + 1)+"'>";
}
return list;
}
function add_program() {
var addprogram = $("#addprogram"),
list = addprogram.find(".ui-content");
list.html($(fresh_program())).enhanceWithin();
addprogram.find("div[data-role='header'] > .ui-btn-right").on("click",function(){
submit_program("new");
});
addprogram.find("input[name^='rad_days']").on("change",function(){
var progid = "new", type = $(this).val().split("-")[0], old;
type = type.split("_")[1];
if (type == "n") {
old = "week";
} else {
old = "n";
}
$("#input_days_"+type+"-"+progid).show();
$("#input_days_"+old+"-"+progid).hide();
});
addprogram.find("[id^='s_checkall-']").on("click",function(){
addprogram.find("[id^='station_'][id$='-new']").prop("checked",true).checkboxradio("refresh");
return false;
});
addprogram.find("[id^='s_uncheckall-']").on("click",function(){
addprogram.find("[id^='station_'][id$='-new']").prop("checked",false).checkboxradio("refresh");
return false;
});
addprogram.find("[id^='submit-']").on("click",function(){
submit_program("new");
return false;
});
addprogram.find("[id^='duration-'],[id^='interval-']").on("click",function(){
var dur = $(this),
granularity = dur.attr("id").match("interval") ? 1 : 0,
name = addprogram.find("label[for='"+dur.attr("id")+"']").text();
showDurationBox(dur.val(),name,function(result){
dur.val(result);
dur.text(dhms2str(sec2dhms(result)));
},65535,granularity);
return false;
});
addprogram.one("pagehide",function() {
addprogram.find(".ui-header > .ui-btn-right").off("click");
$(this).find(".ui-content").empty();
});
}
function delete_program(id) {
areYouSure(_("Are you sure you want to delete program")+" "+(parseInt(id)+1)+"?", "", function() {
$.mobile.loading("show");
send_to_os("/dp?pw=&pid="+id).done(function(){
$.mobile.loading("hide");
update_controller_programs(function(){
get_programs(false);
});
});
});
}
function submit_program(id) {
var program = [],
days=[0,0],
i, s;
program[0] = ($("#en-"+id).is(':checked')) ? 1 : 0;
if($("#days_week-"+id).is(':checked')) {
for(i=0;i<7;i++) {if($("#d"+i+"-"+id).is(':checked')) {days[0] |= (1<<i); }}
if($("#days_odd-"+id).is(':checked')) {days[0]|=0x80; days[1]=1;}
else if($("#days_even-"+id).is(':checked')) {days[0]|=0x80; days[1]=0;}
} else if($("#days_n-"+id).is(':checked')) {
days[1]=parseInt($("#every-"+id).val(),10);
if(!(days[1]>=2&&days[1]<=128)) {showerror(_("Error: Interval days must be between 2 and 128."));return;}
days[0]=parseInt($("#starting-"+id).val(),10);
if(!(days[0]>=0&&days[0]<days[1])) {showerror(_("Error: Starting in days wrong."));return;}
days[0]|=0x80;
}
program[1] = days[0];
program[2] = days[1];
var start = $("#start-"+id).val().split(":");
program[3] = parseInt(start[0])*60+parseInt(start[1]);
var end = $("#end-"+id).val().split(":");
program[4] = parseInt(end[0])*60+parseInt(end[1]);
if(program[3]>program[4]) {showerror(_("Error: Start time must be prior to end time."));return;}
program[5] = parseInt($("#interval-"+id).val()/60);
program[6] = parseInt($("#duration-"+id).val());
var sel = $("[id^=station_][id$=-"+id+"]"),
total = sel.length,
nboards = total / 8;
var stations=[0],station_selected=0,bid, sid;
for(bid=0;bid<nboards;bid++) {
stations[bid]=0;
for(s=0;s<8;s++) {
sid=bid*8+s;
if($("#station_"+sid+"-"+id).is(":checked")) {
stations[bid] |= 1<<s; station_selected=1;
}
}
}
if(station_selected===0) {showerror(_("Error: You have not selected any stations."));return;}
program = JSON.stringify(program.concat(stations));
$.mobile.loading("show");
if (id == "new") {
send_to_os("/cp?pw=&pid=-1&v="+program).done(function(){
$.mobile.loading("hide");
update_controller_programs(function(){
$.mobile.document.one("pageshow",function(){
showerror(_("Program added successfully"));
});
window.history.back();
});
});
} else {
send_to_os("/cp?pw=&pid="+id+"&v="+program).done(function(){
$.mobile.loading("hide");
update_controller_programs(function(){
update_program_header();
});
showerror(_("Program has been updated"));
});
}
}
function raindelay() {
$.mobile.loading("show");
send_to_os("/cv?pw=&rd="+$("#delay").val()).done(function(){
var popup = $("#raindelay");
popup.popup("close");
popup.find("form").off("submit");
$.mobile.loading("hide");
showLoading("#footer-running");
$.when(
update_controller_settings(),
update_controller_status()
).then(check_status);
showerror(_("Rain delay has been successfully set"));
});
return false;
}
// Export and Import functions
function export_config() {
localStorage.setItem("backup", JSON.stringify(window.controller));
showerror(_("Backup saved on this device"));
}
function import_config(data) {
var piNames = {1:"tz",2:"ntp",12:"htp",13:"htp2",14:"ar",15:"nbrd",16:"seq",17:"sdt",18:"mas",19:"mton",20:"mtoff",21:"urs",22:"rst",23:"wl",25:"ipas"},
keyIndex = {"tz":1,"ntp":2,"hp0":12,"hp1":13,"ar":14,"ext":15,"seq":16,"sdt":17,"mas":18,"mton":19,"mtof":20,"urs":21,"rso":22,"wl":23,"ipas":25,"devid":26};
if (typeof data === "undefined") {
data = localStorage.getItem("backup");
if (data === null) {
showerror(_("No backup available on this device"));
return;
}
}
data = JSON.parse(data);
if (!data.settings) {
showerror(_("No backup available on this device"));
return;
}
areYouSure(_("Are you sure you want to restore the configuration?"), "", function() {
$.mobile.loading("show");
var cs = "/cs?pw=",
co = "/co?pw=",
cp_start = "/cp?pw=",
isPi = isOSPi(),
i, key;
for (i in data.options) {
if (data.options.hasOwnProperty(i) && keyIndex.hasOwnProperty(i)) {
key = keyIndex[i];
if ($.inArray(key, [2,14,16,21,22,25]) !== -1 && data.options[i] === 0) continue;
if (isPi) {
key = piNames[key];
if (key === undefined) continue;
} else {
key = key;
}
co += "&o"+key+"="+data.options[i];
}
}
co += "&"+(isPi?"o":"")+"loc="+data.settings.loc;
for (i=0; i<data.stations.snames.length; i++) {
cs += "&s"+i+"="+data.stations.snames[i];
}
for (i=0; i<data.stations.masop.length; i++) {
cs += "&m"+i+"="+data.stations.masop[i];
}
if (typeof data.stations.ignore_rain === "object") {
for (i=0; i<data.stations.ignore_rain.length; i++) {
cs += "&i"+i+"="+data.stations.ignore_rain[i];
}
}
$.when(
send_to_os(co),
send_to_os(cs),
$.each(data.programs.pd,function (i,prog) {
send_to_os(cp_start+"&pid=-1&v="+JSON.stringify(prog));
})
).then(
function(){
update_controller(function(){
$.mobile.loading("hide");
showerror(_("Backup restored to your device"));
update_weather();
});
},
function(){
$.mobile.loading("hide");
showerror(_("Unable to import configuration. Check device password and try again."));
}
);
});
}
// OSPi functions
function isOSPi() {
if (window.controller && typeof window.controller.options.fwv == "string" && window.controller.options.fwv.search(/ospi/i) !== -1) return true;
return false;
}
function checkWeatherPlugin() {
var weather_settings = $(".weather_settings");
window.curr_wa = [];
weather_settings.hide();
if (isOSPi()) {
send_to_os("/wj","json").done(function(results){
if (typeof results.auto_delay === "string") {
window.curr_wa = results;
weather_settings.css("display","");
}
});
}
}
function getOSVersion(fwv) {
if (typeof fwv == "string" && fwv.search(/ospi/i) !== -1) {
return fwv;
} else {
return (fwv/100>>0)+"."+((fwv/10>>0)%10)+"."+(fwv%10);
}
}
// Accessory functions for jQuery Mobile
function areYouSure(text1, text2, callback) {
var popup = $(
'<div data-role="popup" data-overlay-theme="b" id="sure">'+
'<h3 class="sure-1 center">'+text1+'</h3>'+
'<p class="sure-2 center">'+text2+'</p>'+
'<a class="sure-do ui-btn ui-btn-b ui-corner-all ui-shadow" href="#">'+_("Yes")+'</a>'+
'<a class="sure-dont ui-btn ui-corner-all ui-shadow" href="#">'+_("No")+'</a>'+
'</div>'
);
//Bind buttons
popup.find(".sure-do").one("click.sure", function() {
$("#sure").popup("close");
callback();
return false;
});
popup.find(".sure-dont").one("click.sure", function() {
$("#sure").popup("close");
return false;
});
popup.one("popupafterclose", function(){
$(this).popup("destroy").remove();
}).enhanceWithin();
$(".ui-page-active").append(popup);
$("#sure").popup({history: false, positionTo: "window"}).popup("open");
}
function showDurationBox(seconds,title,callback,maximum,granularity) {
$("#durationBox").popup("destroy").remove();
title = title || "Duration";
callback = callback || function(){};
granularity = granularity || 0;
var types = ["Days","Hours","Minutes","Seconds"],
conv = [86400,3600,60,1],
total = 4 - granularity,
start = 0,
arr = sec2dhms(seconds),
i;
if (maximum) {
for (i=conv.length-1; i>=0; i--) {
if (maximum < conv[i]) {
start = i+1;
total = (conv.length - start) - granularity;
break;
}
}
}
var incrbts = '<fieldset class="ui-grid-'+String.fromCharCode(95+(total))+' incr">',
inputs = '<div class="ui-grid-'+String.fromCharCode(95+(total))+' inputs">',
decrbts = '<fieldset class="ui-grid-'+String.fromCharCode(95+(total))+' decr">',
popup = $('<div data-role="popup" id="durationBox" data-theme="a" data-overlay-theme="b">' +
'<div data-role="header" data-theme="b">' +
'<h1>'+title+'</h1>' +
'</div>' +
'<div class="ui-content">' +
'<span>' +
'<a href="#" class="submit_duration" data-role="button" data-corners="true" data-shadow="true" data-mini="true">'+_("Set Duration")+'</a>' +
'</span>' +
'</div>' +
'</div>'),
changeValue = function(pos,dir){
var input = $(popup.find(".inputs input")[pos]),
val = parseInt(input.val());
if ((dir == -1 && val === 0) || (dir == 1 && (getValue() + conv[pos+start]) > maximum)) return;
input.val(val+dir);
},
getValue = function() {
return dhms2sec({
"days": parseInt(popup.find(".days").val()) || 0,
"hours": parseInt(popup.find(".hours").val()) || 0,
"minutes": parseInt(popup.find(".minutes").val()) || 0,
"seconds": parseInt(popup.find(".seconds").val()) || 0
});
};
for (i=start; i<conv.length - granularity; i++) {
incrbts += '<div '+((total > 1) ? 'class="ui-block-'+String.fromCharCode(97+i-start)+'"' : '')+'><a href="#" data-role="button" data-mini="true" data-corners="true" data-icon="plus" data-iconpos="bottom"></a></div>';
inputs += '<div '+((total > 1) ? 'class="ui-block-'+String.fromCharCode(97+i-start)+'"' : '')+'><label>'+_(types[i])+'</label><input class="'+types[i].toLowerCase()+'" type="number" pattern="[0-9]*" value="'+arr[types[i].toLowerCase()]+'"></div>';
decrbts += '<div '+((total > 1) ? 'class="ui-block-'+String.fromCharCode(97+i-start)+'"' : '')+'><a href="#" data-role="button" data-mini="true" data-corners="true" data-icon="minus" data-iconpos="bottom"></a></div>';
}
incrbts += '</fieldset>';
inputs += '</div>';
decrbts += '</fieldset>';
popup.find("span").prepend(incrbts+inputs+decrbts);
popup.find(".incr").children().on("click",function(){
var pos = $(this).index();
changeValue(pos,1);
return false;
});
popup.find(".decr").children().on("click",function(){
var pos = $(this).index();
changeValue(pos,-1);
return false;
});
popup
.css("max-width","350px")
.popup({
history: false,
"positionTo": "window"
})
.one("popupafterclose",function(){
$(this).popup("destroy").remove();
})
.on("click",".submit_duration",function(){
callback(getValue());
popup.popup("close");
return false;
})
.enhanceWithin().popup("open");
}
function changePage(toPage,opts) {
opts = opts || {};
if (toPage.indexOf("#") !== 0) toPage = "#"+toPage;
$.mobile.pageContainer.pagecontainer("change",toPage,opts);
}
// Close the panel before page transition to avoid bug in jQM 1.4+
function changeFromPanel(page) {
var $panel = $("#sprinklers-settings");
$panel.one("panelclose", function(){
changePage("#"+page);
});
$panel.panel("close");
}
function showTooltip(x, y, contents, color) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': color,
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
// Show loading indicator within element(s)
function showLoading(ele) {
$(ele).off("click").html("<p class='ui-icon ui-icon-loading mini-load'></p>");
}
// show error message
function showerror(msg,dur) {
dur = dur || 2500;
$.mobile.loading('show', {
text: msg,
textVisible: true,
textonly: true,
theme: 'b'
});
// hide after delay
setTimeout(function(){$.mobile.loading('hide');},dur);
}
// Accessory functions
function fixInputClick(page) {
// Handle Fast Click quirks
if (!FastClick.notNeeded(document.body)) {
page.find("input[type='checkbox']:not([data-role='flipswitch'])").addClass("needsclick");
page.find(".ui-collapsible-heading-toggle").on("click",function(){
var heading = $(this);
setTimeout(function(){
heading.removeClass("ui-btn-active");
},100);
});
}
}
// Convert all elements in array to integer
function parseIntArray(arr) {
for(var i=0; i<arr.length; i++) {arr[i] = +arr[i];}
return arr;
}
// Convert seconds into (HH:)MM:SS format. HH is only reported if greater than 0.
function sec2hms(diff) {
var str = "";
var hours = Math.max(0, parseInt( diff / 3600 ) % 24);
var minutes = Math.max(0, parseInt( diff / 60 ) % 60);
var seconds = diff % 60;
if (hours) str += pad(hours)+":";
return str+pad(minutes)+":"+pad(seconds);
}
// Convert seconds into array of days, hours, minutes and seconds.
function sec2dhms(diff) {
return {
"days": Math.max(0, parseInt(diff / 86400)),
"hours": Math.max(0, parseInt(diff % 86400 / 3600)),
"minutes": Math.max(0, parseInt((diff % 86400) % 3600 / 60)),
"seconds": Math.max(0, parseInt((diff % 86400) % 3600 % 60))
};
}
function dhms2str(arr) {
var str = "";
if (arr.days) str += arr.days+_("d")+" ";
if (arr.hours) str += arr.hours+_("h")+" ";
if (arr.minutes) str += arr.minutes+_("m")+" ";
if (arr.seconds) str += arr.seconds+_("s")+" ";
if (str === "") str = "0"+_("s");
return str.trim();
}
// Convert days, hours, minutes and seconds array into seconds (int).
function dhms2sec(arr) {
return parseInt((arr.days*86400)+(arr.hours*3600)+(arr.minutes*60)+arr.seconds);
}
// Generate email link for JSON data export
function objToEmail(ele,obj,subject) {
subject = subject || "Sprinklers Data Export on "+dateToString(new Date());
var body = JSON.stringify(obj);
$(ele).attr("href","mailto:?subject="+encodeURIComponent(subject)+"&body="+encodeURIComponent(body));
}
// Small wrapper to handle Chrome vs localStorage usage
var storage = {
get: function(query,callback) {
callback = callback || function(){};
try {
var data = {},
i;
if (typeof query == "object") {
for (i in query) {
if (query.hasOwnProperty(i)) {
data[query[i]] = localStorage.getItem(query[i]);
}
}
} else if (typeof query == "string") {
data[query] = localStorage.getItem(query);
}
callback(data);
} catch(e) {
chrome.storage.local.get(query,callback);
}
},
set: function(query,callback) {
callback = callback || function(){};
try {
var i;
if (typeof query == "object") {
for (i in query) {
if (query.hasOwnProperty(i)) {
localStorage.setItem(i,query[i]);
}
}
}
callback(true);
} catch(e) {
chrome.storage.local.get(query,callback);
}
},
remove: function(query,callback) {
callback = callback || function(){};
try {
var i;
if (typeof query == "object") {
for (i in query) {
if (query.hasOwnProperty(i)) {
localStorage.removeItem(query[i]);
}
}
} else if (typeof query == "string") {
localStorage.removeItem(query);
}
callback(true);
} catch(e) {
chrome.storage.local.get(query,callback);
}
}
};
// Return day of the week
function getDayName(day,type) {
var ldays = [_("Sunday"),_("Monday"),_("Tuesday"),_("Wednesday"),_("Thursday"),_("Friday"),_("Saturday")],
sdays = [_("Sun"),_("Mon"),_("Tue"),_("Wed"),_("Thu"),_("Fri"),_("Sat")];
if (type == "short") {
return sdays[day.getDay()];
} else {
return ldays[day.getDay()];
}
}
// Add ability to unique sort arrays
function getUnique(inputArray) {
var outputArray = [];
for (var i = 0; i < inputArray.length; i++) {
if ((jQuery.inArray(inputArray[i], outputArray)) == -1) outputArray.push(inputArray[i]);
}
return outputArray;
}
// pad a single digit with a leading zero
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
//Localization functions
function _(key) {
//Translate item (key) based on currently defined language
if (typeof window.language === "object" && window.language.hasOwnProperty(key)) {
var trans = window.language[key];
return trans ? trans : key;
} else {
//If English
return key;
}
}
function set_lang() {
//Update all static elements to the current language
$("[data-translate]").text(function() {
var el = $(this),
txt = el.data("translate");
if (el.is("input[type='submit']")) {
el.val(_(txt));
// Update button for jQuery Mobile
if (el.parent("div.ui-btn").length > 0) el.button("refresh");
} else {
return _(txt);
}
});
$(".ui-toolbar-back-btn").text(_("Back"));
$.mobile.toolbar.prototype.options.backBtnText = _("Back");
}
function get_locale() {
//Identify the current browser's locale
var locale = "en",
lang = localStorage.getItem("lang");
locale = lang || navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage || locale;
return locale.substring(0,2);
}
function update_lang(lang) {
//Empty out the current language (English is provided as the key)
window.language = {};
if (lang == "en") {
localStorage.setItem("lang","en");
set_lang();
check_curr_lang();
return;
}
$.getJSON("locale/"+lang+".json",function(store){
window.language = store.messages;
localStorage.setItem("lang",lang);
set_lang();
check_curr_lang();
}).fail(set_lang);
}
function check_curr_lang() {
var curr_lang = localStorage.getItem("lang");
$("#localization").find("a").each(function(a,b){
var item = $(b);
if (item.data("lang-code") == curr_lang) {
item.removeClass("ui-icon-carat-r").addClass("ui-icon-check");
} else {
item.removeClass("ui-icon-check").addClass("ui-icon-carat-r");
}
});
}
function dateToString(date) {
var lang = localStorage.getItem("lang");
if (lang == "de") {
date.setMinutes(date.getMinutes()+date.getTimezoneOffset());
return pad(date.getDate())+"."+pad(date.getMonth())+"."+date.getFullYear()+" "+pad(date.getHours())+":"+pad(date.getMinutes())+":"+pad(date.getSeconds());
}
return date.toUTCString().slice(0,-4);
}
function tzToString(prefix,tz,offset) {
var lang = localStorage.getItem("lang");
if (lang == "de") return "";
return prefix+tz+" "+offset;
}
|
Base: Initial change to storage wrapper
|
js/main.js
|
Base: Initial change to storage wrapper
|
<ide><path>s/main.js
<ide> $(document)
<ide> .ready(function() {
<ide> //Update the language on the page using the browser's locale
<del> update_lang(get_locale());
<add> update_lang();
<ide>
<ide> //Use the user's local time for preview
<ide> var now = new Date();
<ide> });
<ide> settings.find(".clear-config").off("click").on("click",function(){
<ide> areYouSure(_("Are you sure you want to delete all settings and return to the default settings?"), "", function() {
<del> localStorage.removeItem("sites");
<del> localStorage.removeItem("current_site");
<del> localStorage.removeItem("lang");
<del> localStorage.removeItem("provider");
<del> localStorage.removeItem("wapikey");
<del> localStorage.removeItem("runonce");
<del> update_lang(get_locale());
<del> changePage("#start");
<add> storage.remove(["sites","current_site","lang","provider","wapikey","runonce"],function(){
<add> update_lang();
<add> changePage("#start");
<add> });
<ide> });
<ide> return false;
<ide> });
<ide> }
<ide>
<ide> $("#os_name,#os_ip,#os_pw,#os_auth_user,#os_auth_pw").val("");
<del> localStorage.setItem("sites",JSON.stringify(sites));
<del> localStorage.setItem("current_site",name);
<del> update_site_list(Object.keys(sites));
<del> newload();
<add> storage.set({
<add> "sites": JSON.stringify(sites),
<add> "current_site": name
<add> },function(){
<add> update_site_list(Object.keys(sites));
<add> newload();
<add> });
<ide> } else {
<ide> showerror(_("Check IP/Port and try again."));
<ide> }
<ide> sites[nm] = sites[site];
<ide> delete sites[site];
<ide> site = nm;
<del> localStorage.setItem("current_site",site);
<add> storage.set({"current_site":site});
<ide> update_site_list(Object.keys(sites));
<ide> }
<ide>
<del> localStorage.setItem("sites",JSON.stringify(sites));
<add> storage.set({"sites":JSON.stringify(sites)});
<ide>
<ide> showerror(_("Site updated successfully"));
<ide>
<del> if (site === localStorage.getItem("current_site")) {
<del> if (pw !== "") window.curr_pw = pw;
<del> if (ip !== "") check_configured();
<del> }
<add> storage.get("current_site",function(data){
<add> if (site === data.current_site) {
<add> if (pw !== "") window.curr_pw = pw;
<add> if (ip !== "") check_configured();
<add> }
<add> });
<ide>
<ide> if (rename) show_sites();
<ide> }
<ide> // Update the panel list of sites
<ide> function update_site_list(names) {
<ide> var list = "",
<del> current = localStorage.getItem("current_site");
<del> $.each(names,function(a,b){
<del> list += "<option "+(b==current ? "selected ":"")+"value='"+b+"'>"+b+"</option>";
<del> });
<del>
<del> $("#site-selector").html(list);
<del> try {
<del> $("#site-selector").selectmenu("refresh");
<del> } catch (err) {
<del> }
<add> select = $("#site-selector");
<add>
<add> storage.get("current_site",function(data){
<add> $.each(names,function(a,b){
<add> list += "<option "+(b==data.current_site ? "selected ":"")+"value='"+b+"'>"+b+"</option>";
<add> });
<add>
<add> select.html(list);
<add> if (select.parent().parent().hasClass("ui-select")) select.selectmenu("refresh");
<add> });
<ide> }
<ide>
<ide> // Change the current site
<ide> function update_site(newsite) {
<ide> var sites = getsites();
<del> if (newsite in sites) {
<del> localStorage.setItem("current_site",newsite);
<del> check_configured();
<del> }
<add> if (newsite in sites) storage.set({"current_site":newsite},check_configured);
<ide> }
<ide>
<ide> // Get the list of sites from the local storage
<ide> }
<ide>
<ide> function update_weather() {
<del> var provider = localStorage.getItem("provider"),
<del> wapikey = localStorage.getItem("wapikey");
<del>
<del> if (window.controller.settings.loc === "") {
<del> hide_weather();
<del> return;
<del> }
<del>
<del> showLoading("#weather");
<del>
<del> if (provider == "wunderground" && wapikey) {
<del> update_wunderground_weather(wapikey);
<del> } else {
<del> update_yahoo_weather();
<del> }
<add> storage.get(["provider","wapikey"],function(data){
<add> if (window.controller.settings.loc === "") {
<add> hide_weather();
<add> return;
<add> }
<add>
<add> showLoading("#weather");
<add>
<add> if (data.provider == "wunderground" && data.wapikey) {
<add> update_wunderground_weather(data.wapikey);
<add> } else {
<add> update_yahoo_weather();
<add> }
<add> });
<ide> }
<ide>
<ide> function update_yahoo_weather() {
<ide> });
<ide> runonce.push(0);
<ide> }
<del> localStorage.setItem("runonce",JSON.stringify(runonce));
<add> storage.set({"runonce":JSON.stringify(runonce)});
<ide> send_to_os("/cr?pw=&t="+JSON.stringify(runonce)).done(function(){
<ide> $.mobile.document.one("pageshow",function(){
<ide> showerror(_("Run-once program has been scheduled"));
<ide>
<ide> // Export and Import functions
<ide> function export_config() {
<del> localStorage.setItem("backup", JSON.stringify(window.controller));
<del> showerror(_("Backup saved on this device"));
<add> storage.set({"backup":JSON.stringify(window.controller)},function(){
<add> showerror(_("Backup saved on this device"));
<add> });
<ide> }
<ide>
<ide> function import_config(data) {
<ide> keyIndex = {"tz":1,"ntp":2,"hp0":12,"hp1":13,"ar":14,"ext":15,"seq":16,"sdt":17,"mas":18,"mton":19,"mtof":20,"urs":21,"rso":22,"wl":23,"ipas":25,"devid":26};
<ide>
<ide> if (typeof data === "undefined") {
<del> data = localStorage.getItem("backup");
<del> if (data === null) {
<del> showerror(_("No backup available on this device"));
<del> return;
<del> }
<add> storage.get("backup",function(newdata){
<add> if (newdata.backup) {
<add> import_config(newdata.backup);
<add> } else {
<add> showerror(_("No backup available on this device"));
<add> return;
<add> }
<add> });
<add>
<add> return;
<ide> }
<ide>
<ide> data = JSON.parse(data);
<ide> });
<ide> $(".ui-toolbar-back-btn").text(_("Back"));
<ide> $.mobile.toolbar.prototype.options.backBtnText = _("Back");
<del>}
<del>
<del>function get_locale() {
<del> //Identify the current browser's locale
<del> var locale = "en",
<del> lang = localStorage.getItem("lang");
<del>
<del> locale = lang || navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage || locale;
<del>
<del> return locale.substring(0,2);
<add>
<add> check_curr_lang();
<ide> }
<ide>
<ide> function update_lang(lang) {
<ide> //Empty out the current language (English is provided as the key)
<ide> window.language = {};
<ide>
<add> if (typeof lang == "undefined") {
<add> storage.get("lang",function(data){
<add> //Identify the current browser's locale
<add> var locale = "en";
<add>
<add> locale = data.lang || navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage || locale;
<add>
<add> update_lang(locale.substring(0,2));
<add> });
<add> return;
<add> }
<add>
<add> storage.set({"lang":lang});
<add>
<ide> if (lang == "en") {
<del> localStorage.setItem("lang","en");
<ide> set_lang();
<del> check_curr_lang();
<ide> return;
<ide> }
<ide>
<ide> $.getJSON("locale/"+lang+".json",function(store){
<ide> window.language = store.messages;
<del> localStorage.setItem("lang",lang);
<ide> set_lang();
<del> check_curr_lang();
<ide> }).fail(set_lang);
<ide> }
<ide>
<ide> function check_curr_lang() {
<del> var curr_lang = localStorage.getItem("lang");
<del>
<del> $("#localization").find("a").each(function(a,b){
<del> var item = $(b);
<del> if (item.data("lang-code") == curr_lang) {
<del> item.removeClass("ui-icon-carat-r").addClass("ui-icon-check");
<del> } else {
<del> item.removeClass("ui-icon-check").addClass("ui-icon-carat-r");
<del> }
<add> storage.get("lang",function(data){
<add> $("#localization").find("a").each(function(a,b){
<add> var item = $(b);
<add> if (item.data("lang-code") == data.lang) {
<add> item.removeClass("ui-icon-carat-r").addClass("ui-icon-check");
<add> } else {
<add> item.removeClass("ui-icon-check").addClass("ui-icon-carat-r");
<add> }
<add> });
<ide> });
<ide> }
<ide>
|
|
Java
|
mit
|
error: pathspec 'src/test/java/com/emc/mongoose/metrics/util/MetricsCollectorTest.java' did not match any file(s) known to git
|
d9e584ff402c066b0f372416492769267a54f289
| 1 |
emc-mongoose/mongoose
|
package com.emc.mongoose.metrics.util;
import io.prometheus.client.Collector;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
@author veronika K. on 09.10.18 */
public class MetricsCollectorTest {
private final MetricsCollector metricsCollector = new MetricsCollector();
private final int METRICS_COUNT = 7; //sum, min, max, count, mean, loQ, hiQ
private final long ITERATION_COUNT = 10_000_000;
@Test
public void test() {
long sum = 0;
for(long i = 0; i < ITERATION_COUNT; ++ i) {
metricsCollector.update(i);
sum += i;
}
final List<Collector.MetricFamilySamples.Sample> samples = metricsCollector.collect().get(0).samples;
//
Assert.assertEquals(metricsCollector.collect().size(), 1);
Assert.assertEquals(samples.size(), METRICS_COUNT);
//count
Assert.assertEquals(new Double(samples.get(0).value).longValue(), ITERATION_COUNT);
//sum
Assert.assertEquals(new Double(samples.get(1).value).longValue(), sum);
//max
Assert.assertEquals(new Double(samples.get(2).value).longValue(), ITERATION_COUNT - 1);
//min
Assert.assertEquals(new Double(samples.get(3).value).longValue(), 0);
//mean
final double mean = ((double) sum) / ITERATION_COUNT;
Assert.assertEquals(new Double(samples.get(4).value).longValue(), mean, mean * 0.05);
//TODO: quantieles
}
}
|
src/test/java/com/emc/mongoose/metrics/util/MetricsCollectorTest.java
|
save (added MetricsCollector) [skip ci]
|
src/test/java/com/emc/mongoose/metrics/util/MetricsCollectorTest.java
|
save (added MetricsCollector) [skip ci]
|
<ide><path>rc/test/java/com/emc/mongoose/metrics/util/MetricsCollectorTest.java
<add>package com.emc.mongoose.metrics.util;
<add>
<add>import io.prometheus.client.Collector;
<add>import org.junit.Assert;
<add>import org.junit.Test;
<add>
<add>import java.util.List;
<add>
<add>/**
<add> @author veronika K. on 09.10.18 */
<add>public class MetricsCollectorTest {
<add>
<add> private final MetricsCollector metricsCollector = new MetricsCollector();
<add> private final int METRICS_COUNT = 7; //sum, min, max, count, mean, loQ, hiQ
<add> private final long ITERATION_COUNT = 10_000_000;
<add>
<add> @Test
<add> public void test() {
<add> long sum = 0;
<add> for(long i = 0; i < ITERATION_COUNT; ++ i) {
<add> metricsCollector.update(i);
<add> sum += i;
<add> }
<add> final List<Collector.MetricFamilySamples.Sample> samples = metricsCollector.collect().get(0).samples;
<add> //
<add> Assert.assertEquals(metricsCollector.collect().size(), 1);
<add> Assert.assertEquals(samples.size(), METRICS_COUNT);
<add> //count
<add> Assert.assertEquals(new Double(samples.get(0).value).longValue(), ITERATION_COUNT);
<add> //sum
<add> Assert.assertEquals(new Double(samples.get(1).value).longValue(), sum);
<add> //max
<add> Assert.assertEquals(new Double(samples.get(2).value).longValue(), ITERATION_COUNT - 1);
<add> //min
<add> Assert.assertEquals(new Double(samples.get(3).value).longValue(), 0);
<add> //mean
<add> final double mean = ((double) sum) / ITERATION_COUNT;
<add> Assert.assertEquals(new Double(samples.get(4).value).longValue(), mean, mean * 0.05);
<add> //TODO: quantieles
<add> }
<add>}
|
|
Java
|
apache-2.0
|
2c493f7465aa3ada82b7f100df5e4aa27de80582
| 0 |
mpi2/PhenotypeArchive,mpi2/PhenotypeArchive,mpi2/PhenotypeArchive
|
/**
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* Copyright © 2014 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.phenotype.solr.indexer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import joptsimple.HelpFormatter;
import joptsimple.OptionDescriptor;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.lang3.StringUtils;
import org.mousephenotype.www.testing.model.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import static uk.ac.ebi.phenotype.solr.indexer.AbstractIndexer.CONTEXT_ARG;
import uk.ac.ebi.phenotype.util.Utils;
/**
* This class encapsulates the code and data necessary to represent an index
* manager that manages the creation and deployment of all of the indexes
* required for phenotype archive; a job previously delegated to Jenkins that
* was susceptible to frequent failure.
*
* @author mrelac
*/
public class IndexerManager {
private static final Logger logger = LoggerFactory.getLogger(IndexerManager.class);
// core names.
// These are built only for a new data release.
public static final String OBSERVATION_CORE = "experiment_staging"; // For historic reasons, the core's actual name is 'experiment'.
public static final String GENOTYPE_PHENOTYPE_CORE = "genotype-phenotype_staging";
public static final String STATSTICAL_RESULT_CORE = "statistical-result_staging";
// These are built daily.
public static final String PREQC_CORE = "preqc_staging";
public static final String ALLELE_CORE = "allele_staging";
public static final String IMAGES_CORE = "images_staging";
public static final String IMPC_IMAGES_CORE = "impc_images_staging";
public static final String MP_CORE = "mp_staging";
public static final String MA_CORE = "ma_staging";
public static final String PIPELINE_CORE = "pipeline_staging";
public static final String GENE_CORE = "gene_staging";
public static final String DISEASE_CORE = "disease_staging";
public static final String AUTOSUGGEST_CORE = "autosuggest_staging";
// main return values.
public static final int STATUS_OK = 0;
public static final int STATUS_NO_DEPS = 1;
public static final int STATUS_NO_ARGUMENT = 2;
public static final int STATUS_UNRECOGNIZED_OPTION = 3;
public static final int STATUS_INVALID_CORE_NAME = 4;
public static final int STATUS_VALIDATION_ERROR = 5;
public static String getStatusCodeName(int statusCode) {
switch (statusCode) {
case STATUS_OK: return "STATUS_OK";
case STATUS_NO_DEPS: return "STATUS_NO_DEPS";
case STATUS_NO_ARGUMENT: return "STATUS_NO_ARGUMENT";
case STATUS_UNRECOGNIZED_OPTION: return "STATUS_UNRECOGNIZED_OPTION";
case STATUS_INVALID_CORE_NAME: return "STATUS_INVALID_CORE_NAME";
case STATUS_VALIDATION_ERROR: return "STATUS_VALIDATION_ERROR";
default: return "Unknown status code " + statusCode;
}
}
// These are the args that can be passed to the indexer manager.
private Boolean all;
private List<String> cores;
private Boolean daily;
private Boolean nodeps;
private Boolean deploy;
// These are the args passed to the individual indexers. They should be all the same and should be the same context argument passed to the indexerManager.
private String[] indexerArgs;
public static final String[] allCoresArray = new String[] { // In dependency order.
// In dependency order. These are built only for a new data release.
OBSERVATION_CORE
, GENOTYPE_PHENOTYPE_CORE
, STATSTICAL_RESULT_CORE
// These are built daily.
, PREQC_CORE
, ALLELE_CORE
, IMAGES_CORE
, IMPC_IMAGES_CORE
, MP_CORE
, MA_CORE
, PIPELINE_CORE
, GENE_CORE
, DISEASE_CORE
, AUTOSUGGEST_CORE
};
private final List<String> allCoresList = Arrays.asList(allCoresArray);
public static final String[] allDailyCoresArray = new String[] {
// In dependency order. These are built daily.
PREQC_CORE
, ALLELE_CORE
, IMAGES_CORE
, IMPC_IMAGES_CORE
, MP_CORE
, MA_CORE
, PIPELINE_CORE
, GENE_CORE
, DISEASE_CORE
, AUTOSUGGEST_CORE
};
public static final int RETRY_COUNT = 5; // If any core fails, retry building it up to this many times.
public static final int RETRY_SLEEP_IN_MS = 60000; // If any core fails, sleep this long before reattempting to build the core.
public static final String STAGING_SUFFIX = "_staging"; // This snippet is appended to core names meant to be staging core names.
private enum RunStatus { OK, FAIL };
@Resource(name = "globalConfiguration")
private Map<String, String> config;
@Autowired
ObservationIndexer observationIndexer;
@Autowired
GenotypePhenotypeIndexer genotypePhenotypeIndexer;
@Autowired
StatisticalResultIndexer statisticalResultIndexer;
@Autowired
PreqcIndexer preqcIndexer;
@Autowired
AlleleIndexer alleleIndexer;
@Autowired
SangerImagesIndexer imagesIndexer;
@Autowired
ImpcImagesIndexer impcImagesIndexer;
@Autowired
MPIndexer mpIndexer;
@Autowired
MAIndexer maIndexer;
@Autowired
PipelineIndexer pipelineIndexer;
@Autowired
GeneIndexer geneIndexer;
@Autowired
DiseaseIndexer diseaseIndexer;
@Autowired
AutosuggestIndexer autosuggestIndexer;
private String buildIndexesSolrUrl;
private IndexerItem[] indexerItems;
public String[] args;
public static final String ALL_ARG = "all";
public static final String CORES_ARG = "cores";
public static final String DAILY_ARG = "daily";
public static final String DEPLOY_ARG = "deploy";
public static final String NO_DEPS_ARG = "nodeps";
public class IndexerItem {
public final String name;
public final AbstractIndexer indexer;
public IndexerItem(String name, AbstractIndexer indexer) {
this.name = name;
this.indexer = indexer;
}
}
protected ApplicationContext applicationContext;
// GETTERS
public Boolean getAll() {
return all;
}
public List<String> getCores() {
return cores;
}
public Boolean getDaily() {
return daily;
}
public static Logger getLogger() {
return logger;
}
public Boolean getNodeps() {
return nodeps;
}
public Boolean getDeploy() {
return deploy;
}
// PUBLIC/PROTECTED METHODS
public void initialise(String[] args) throws IndexerException {
OptionSet options = parseCommandLine(args);
if (options != null) {
this.args = args;
applicationContext = loadApplicationContext((String)options.valuesOf(CONTEXT_ARG).get(0));
applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
initialiseHibernateSession(applicationContext);
loadIndexers();
} else {
throw new IndexerException("Failed to parse command-line options.");
}
buildIndexesSolrUrl = config.get("buildIndexesSolrUrl");
// Print the jvm memory configuration.
final int mb = 1024*1024;
Runtime runtime = Runtime.getRuntime();
DecimalFormat formatter = new DecimalFormat("#,###");
logger.info("Used memory : " + (formatter.format(runtime.totalMemory() - runtime.freeMemory() / mb)));
logger.info("Free memory : " + formatter.format(runtime.freeMemory()));
logger.info("Total memory: " + formatter.format(runtime.totalMemory()));
logger.info("Max memory : " + formatter.format(runtime.maxMemory()));
}
protected void initialiseHibernateSession(ApplicationContext applicationContext) {
// allow hibernate session to stay open the whole execution
PlatformTransactionManager transactionManager = (PlatformTransactionManager) applicationContext.getBean("transactionManager");
DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED);
transactionAttribute.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
transactionManager.getTransaction(transactionAttribute);
}
public void run() throws IndexerException {
ExecutionStatsList executionStatsList = new ExecutionStatsList();
logger.info("Starting IndexerManager. nodeps = " + nodeps + ". Building the following cores (in order):");
logger.info("\t" + StringUtils.join(cores));
for (IndexerItem indexerItem : indexerItems) {
long start = new Date().getTime();
indexerItem.indexer.initialise(indexerArgs);
// If the core build fails, retry up to RETRY_COUNT times before failing the IndexerManager build.
for (int i = 0; i <= RETRY_COUNT; i++) {
try {
buildStagingArea();
indexerItem.indexer.run();
indexerItem.indexer.validateBuild();
break;
} catch (IndexerException ie) {
if (i < RETRY_COUNT) {
logger.warn("IndexerException: core build attempt[" + i + "] failed. Retrying.");
logErrors(ie);
TestUtils.sleep(RETRY_SLEEP_IN_MS);
} else {
System.out.println(executionStatsList.add(new ExecutionStatsRow(indexerItem.name, RunStatus.FAIL, start, new Date().getTime())).toString());
throw ie;
}
} catch (Exception e) {
if (i < RETRY_COUNT) {
logger.warn("Exception: core build attempt[" + i + "] failed. Retrying.");
logErrors(new IndexerException(e));
TestUtils.sleep(RETRY_SLEEP_IN_MS);
} else {
System.out.println(executionStatsList.add(new ExecutionStatsRow(indexerItem.name, RunStatus.FAIL, start, new Date().getTime())).toString());
throw new IndexerException(e);
}
}
}
executionStatsList.add(new ExecutionStatsRow(indexerItem.name, RunStatus.OK, start, new Date().getTime()));
}
System.out.println(executionStatsList.toString());
}
protected ApplicationContext loadApplicationContext(String context) {
ApplicationContext appContext;
try {
// Try context as a file resource
getLogger().info("Trying to load context from file system...");
appContext = new FileSystemXmlApplicationContext("file:" + context);
getLogger().info("Context loaded from file system");
} catch (BeansException e) {
getLogger().warn("Unable to load the context file: {}", e.getMessage());
// Try context as a class path resource
appContext = new ClassPathXmlApplicationContext(context);
getLogger().warn("Using classpath app-config file: {}", context);
}
return appContext;
}
public void validateParameters(OptionSet options, List<String> coresRequested) throws IndexerException {
// Exactly one of: ALL_ARG, DAILY_ARG, or CORES_ARG must be specified.
if ( ! (options.has(ALL_ARG) || (options.has(DAILY_ARG) || options.has(CORES_ARG)))) {
throw new IndexerException(new MissingRequiredArgumentException("Expected either --all, --daily, or --cores=aaa"));
}
// if DAILY_ARG specified, no other args are allowed.
if (options.has(ALL_ARG)) {
if ((options.has(DAILY_ARG)) || (options.has(CORES_ARG)) || (options.has(NO_DEPS_ARG))) {
throw new IndexerException(new ValidationException("Expected exactly one of: --all, --daily, or --cores=aaa"));
}
}
// if DAILY_ARG specified, no other args are allowed.
if (options.has(DAILY_ARG)) {
if ((options.has(ALL_ARG)) || (options.has(CORES_ARG)) || (options.has(NO_DEPS_ARG))) {
throw new IndexerException(new ValidationException("Expected exactly one of: --all, --daily, or --cores=aaa"));
}
}
// if CORES_ARG specified, neither ALL_ARG nor DAILY_ARG is permitted.
if (options.has(CORES_ARG)) {
if ((options.has(ALL_ARG)) || (options.has(DAILY_ARG))) {
throw new IndexerException(new ValidationException("Expected exactly one of: --all, --daily, or --cores=aaa"));
}
}
// NO_DEPS_ARG may only be specified with CORES_ARG.
if (options.has(NO_DEPS_ARG)) {
if ((options.has(ALL_ARG)) || (options.has(DAILY_ARG))) {
throw new IndexerException(new ValidationException("--nodeps may only be specified with --cores"));
}
}
// Verify that each core name in coresRequested exists. Throw an exception if any does not.
for (String core : coresRequested) {
if ( ! allCoresList.contains(core)) {
throw new IndexerException(new InvalidCoreNameException("Invalid core name '" + core + "'"));
}
}
}
// PRIVATE METHODS
private void loadIndexers() {
List<IndexerItem> indexerItemList = new ArrayList();
for (String core : cores) {
switch (core) {
case OBSERVATION_CORE: indexerItemList.add(new IndexerItem(OBSERVATION_CORE, observationIndexer)); break;
case GENOTYPE_PHENOTYPE_CORE: indexerItemList.add(new IndexerItem(GENOTYPE_PHENOTYPE_CORE, genotypePhenotypeIndexer)); break;
case STATSTICAL_RESULT_CORE: indexerItemList.add(new IndexerItem(STATSTICAL_RESULT_CORE, statisticalResultIndexer)); break;
case PREQC_CORE: indexerItemList.add(new IndexerItem(PREQC_CORE, preqcIndexer)); break;
case ALLELE_CORE: indexerItemList.add(new IndexerItem(ALLELE_CORE, alleleIndexer)); break;
case IMAGES_CORE: indexerItemList.add(new IndexerItem(IMAGES_CORE, imagesIndexer)); break;
case IMPC_IMAGES_CORE: indexerItemList.add(new IndexerItem(IMPC_IMAGES_CORE, impcImagesIndexer)); break;
case MP_CORE: indexerItemList.add(new IndexerItem(MP_CORE, mpIndexer)); break;
case MA_CORE: indexerItemList.add(new IndexerItem(MA_CORE, maIndexer)); break;
case PIPELINE_CORE: indexerItemList.add(new IndexerItem(PIPELINE_CORE, pipelineIndexer)); break;
case GENE_CORE: indexerItemList.add(new IndexerItem(GENE_CORE, geneIndexer)); break;
case DISEASE_CORE: indexerItemList.add(new IndexerItem(DISEASE_CORE, diseaseIndexer)); break;
case AUTOSUGGEST_CORE: indexerItemList.add(new IndexerItem(AUTOSUGGEST_CORE, autosuggestIndexer)); break;
}
}
indexerItems = indexerItemList.toArray(new IndexerItem[0]);
}
// PRIVATE METHODS
/*
* Rules:
* 1. context is always required.
* 2. cores is optional.
* 2a. If cores is missing or empty:
* - build all cores starting at the preqc core (don't build OBSERVATION_CORE, GENOTYPE_PHENOTYPE_CORE, or STATSTICAL_RESULT_CORE).
* - specifying nodeps throws IllegalArgumentException.
* 2b. If 1 core:
* - core name must be valid.
* - if nodeps is specified:
* - build only the specified core. Don't build downstream cores.
* - else
* - build requested core and all downstream cores.
* 2c. If more than 1 core:
* - if nodeps is specified, it is ignored.
* - core names must be valid. No downstream cores are built.
*
* Core Build Truth Table (assume a valid '--context=' parameter is always supplied - not shown in table below to save space):
* |---------------------------------------------------------------------------|
* | command line | nodeps value | cores built |
* |---------------------------------------------------------------------------|
* | <empty> | false | preqc to autosuggest |
* | --cores | false | preqc to autosuggest |
* | --nodeps | NoDepsException | <none> |
* | --cores --nodeps | NoDepsException | <none> |
* | --cores=mp | false | mp to autosuggest |
* | --cores=mp --nodeps | true | mp |
* | --cores=mp,observation | true | mp,observation |
* | --cores-mp,observation --nodeps | true | mp,observation |
* |---------------------------------------------------------------------------|
* @param args command-line arguments
* @return<code>OptionSet</code> of parsed parameters
* @throws IndexerException
*/
/*
* Rules:
* 1. context is always required.
* 2. cores is always required.
* 2b. If 1 core:
* - core name must be valid.
* - if nodeps is specified:
* - build only the specified core. Don't build downstream cores.
* - else
* - build requested core and all downstream cores.
* 2c. If more than 1 core:
* - if nodeps is specified, it is ignored.
* - core names must be valid. No downstream cores are built.
* 3. If 'all' is specified, build all of the cores: experiment to autosuggest.
* Specifying --nodeps throws IllegalArgumentException.
* 4. If 'daily' is specified, build the daily cores: preqc to autosuggest.
* Specifying --nodeps throws IllegalArgumentException.
*
* Core Build Truth Table (assume a valid '--context=' parameter is always supplied - not shown in table below to save space):
* |-----------------------------------------------------------------------------------|
* | command line | Action | nodeps value |
* |-----------------------------------------------------------------------------------|
* | <empty> | Throw MissingRequiredArgumentException | N/A |
* | --cores | Throw MissingRequiredArgumentException | N/A |
* | --nodeps | Throw MissingRequiredArgumentException | N/A |
* | --cores --nodeps | Throw MissingRequiredArgumentException | N/A |
* | --cores= --nodeps | Throw MissingRequiredArgumentException | N/A |
* | --cores=junk | Throw InvalidCoreNameException | N/A |
* | --cores=mp | build mp to autosuggest cores | false |
* | --cores=mp --nodeps | build mp core only | true |
* | --cores=mp,ma | build mp and ma cores | true |
* | --cores-mp,ma --nodeps | build mp and ma cores | true |
* | --all | build experiment to autosuggest cores | false |
* | --all --cores=ma | Return STATUS_VALIDATION_ERROR | N/A |
* | --all --nodeps | Return STATUS_VALIDATION_ERROR | N/A |
* | --daily | build preqc to autosuggest cores. | false |
* | --daily --cores=ma | Return STATUS_VALIDATION_ERROR | N/A |
* | --daily --nodeps | Return STATUS_VALIDATION_ERROR | N/A |
* | --all --daily | Return STATUS_VALIDATION_ERROR | N/A |
* | --all --daily --nodeps | Return STATUS_VALIDATION_ERROR | N/A |
* |-----------------------------------------------------------------------------------|
* @param args command-line arguments
* @return<code>OptionSet</code> of parsed parameters
* @throws IndexerException
*/
private OptionSet parseCommandLine(String[] args) throws IndexerException {
OptionParser parser = new OptionParser();
OptionSet options = null;
// Spring context file parameter [required]
parser.accepts(CONTEXT_ARG)
.withRequiredArg()
.required()
.ofType(String.class)
.describedAs("Spring context file, such as 'index-app-config.xml'");
// cores [optional]
parser.accepts(CORES_ARG)
.withRequiredArg()
.ofType(String.class)
.describedAs("A list of cores, in build order.");
parser.accepts(ALL_ARG);
parser.accepts(DAILY_ARG);
parser.accepts(NO_DEPS_ARG);
parser.accepts(DEPLOY_ARG);
try {
// Parse the parameters.
options = parser.parse(args);
boolean coreMissingOrEmpty = false;
List<String> coresRequested = new ArrayList(); // This is a list of the unique core values specified in the 'cores=' argument.
// Create a list of cores requested based on the value the 'cores=' argument.
if (options.has(CORES_ARG)) {
String rawCoresArgument = (String)options.valueOf((CORES_ARG));
if ((rawCoresArgument == null) || (rawCoresArgument.trim().isEmpty())) {
// Cores list is empty.
coreMissingOrEmpty = true;
} else if ( ! rawCoresArgument.contains(",")) {
coresRequested.add(rawCoresArgument);
} else {
String[] coresArray = ((String)options.valueOf(CORES_ARG)).split(",");
coresRequested.addAll(Arrays.asList(coresArray));
}
} else {
// Cores list is missing.
coreMissingOrEmpty = true;
}
// The only case where nodeps is true is when:
// --cores is specified, AND
// (--nodeps is specified OR # cores requested > 1)
if ((options.has(NO_DEPS_ARG)) && (options.has(NO_DEPS_ARG) || coresRequested.size() > 1)) {
nodeps = true;
} else {
nodeps = false;
}
validateParameters(options, coresRequested);
// Build the cores list as follows:
// If --all specified, set firstCore to experiment.
// Else if --daily specified, set firstCore to preqc.
// Else if --cores specified
// If nodeps or coresRequested.size > 1
// set firstCore to null.
// set cores to coresRequested[0].
// Else
// set firstCore to coresRequested[0].
//
// If firstCore is not null
// search allCoresArray for the 0-relative firstCoreOffset of the value matching firstCore.
// add to cores every core name from firstCoreOffset to the last core in allCoresList.
String firstCore = null;
cores = new ArrayList();
if (options.has(ALL_ARG)) {
firstCore = OBSERVATION_CORE;
} else if (options.has(DAILY_ARG)) {
firstCore = PREQC_CORE;
} else if (options.has(CORES_ARG)) {
if ((nodeps) || coresRequested.size() > 1) {
cores.addAll(coresRequested);
} else {
firstCore = coresRequested.get(0);
}
}
if (firstCore != null) {
int firstCoreOffset = 0;
for (String core : allCoresArray) {
if (core.equals(firstCore)) {
break;
}
firstCoreOffset++;
}
for (int i = firstCoreOffset; i < allCoresArray.length; i++) {
cores.add(allCoresArray[i]);
}
}
} catch (IndexerException ie) {
if ((ie.getLocalizedMessage() != null) && ( ! ie.getLocalizedMessage().isEmpty())) {
System.out.println(ie.getLocalizedMessage() + "\n");
}
try { parser.printHelpOn(System.out); } catch (Exception e) {}
throw ie;
} catch (Exception uoe) {
Throwable t;
if (uoe.getLocalizedMessage().contains("is not a recognized option")) {
t = new UnrecognizedOptionException(uoe);
} else if (uoe.getLocalizedMessage().contains(" requires an argument")) {
t = new MissingRequiredArgumentException(uoe);
} else if (uoe.getLocalizedMessage().contains("Missing required option(s)")) {
t = new MissingRequiredArgumentException(uoe);
} else {
t = uoe;
}
try {
if ((uoe.getLocalizedMessage() != null) && ( ! uoe.getLocalizedMessage().isEmpty())) {
System.out.println(uoe.getLocalizedMessage() + "\n");
}
parser.formatHelpWith( new IndexManagerHelpFormatter() );
parser.printHelpOn(System.out);
} catch (Exception e) {}
throw new IndexerException(t);
}
indexerArgs = new String[] { "--context=" + (String)options.valueOf(CONTEXT_ARG) };
logger.info("indexer config file: '" + indexerArgs[0] + "'");
return options;
}
private void buildStagingArea() {
////// // Insure staging cores are deleted.
////// for (String core : cores) {
////// String stagingCoreFilename = buildIndexesSolrUrl + File.separator + core + STAGING_SUFFIX;
////// File file = new File(stagingCoreFilename);
//////
////// boolean b = file.canRead();
////// System.out.println();
//////
//////
//////
////// System.exit(999);
////// }
// Build and initialise staging core directories.
// Fetch schemas from git.
// Create the cores.
}
public static void main(String[] args) throws IndexerException {
int retVal = mainReturnsStatus(args);
if (retVal != STATUS_OK) {
throw new IndexerException("Build failed: " + getStatusCodeName(retVal));
}
}
public static int mainReturnsStatus(String[] args) {
try {
IndexerManager manager = new IndexerManager();
manager.initialise(args);
manager.run();
logger.info("IndexerManager process finished successfully. Exiting.");
} catch (IndexerException ie) {
logErrors(ie);
if (ie.getCause() instanceof NoDepsException) {
return STATUS_NO_DEPS;
} else if (ie.getCause() instanceof MissingRequiredArgumentException) {
return STATUS_NO_ARGUMENT;
} else if (ie.getCause() instanceof UnrecognizedOptionException) {
return STATUS_UNRECOGNIZED_OPTION;
} else if (ie.getCause() instanceof InvalidCoreNameException) {
return STATUS_INVALID_CORE_NAME;
} else if (ie.getCause() instanceof ValidationException) {
return STATUS_VALIDATION_ERROR;
} else if (ie.getCause() instanceof MissingRequiredArgumentException) {
return STATUS_NO_ARGUMENT;
}
return -1;
}
return STATUS_OK;
}
private static void logErrors(IndexerException ie) {
// Print out the exceptions.
if (ie.getLocalizedMessage() != null) {
logger.error(ie.getLocalizedMessage());
}
int i = 0;
Throwable t = ie.getCause();
while (t != null) {
StringBuilder errMsg = new StringBuilder("Level " + i + ": ");
if (t.getLocalizedMessage() != null) {
errMsg.append(t.getLocalizedMessage());
} else {
errMsg.append("<null>");
}
logger.error(errMsg.toString());
i++;
t = t.getCause();
}
}
/**
* Represents an execution status row. Used to display execution status in
* a readable format. Example:
* "preqc started xxx. Finshed (OK) yyy. Elapsed time: hh:mm:ss".
*/
private class ExecutionStatsRow {
private String coreName;
private RunStatus status;
private Long startTimeInMs;
private Long endTimeInMs;
public ExecutionStatsRow() {
this("<undefined>", RunStatus.FAIL, 0, 0);
}
public ExecutionStatsRow(String coreName, RunStatus status, long startTimeInMs, long endTimeInMs) {
this.coreName = coreName;
this.status = status;
this.startTimeInMs = startTimeInMs;
this.endTimeInMs = endTimeInMs;
}
@Override
public String toString() {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
long millis = endTimeInMs - startTimeInMs;
String elapsed = Utils.msToHms(millis);
formatter.format("%20s started %s. Finished (%s) %s. Elapsed time: %s",
coreName, dateFormatter.format(startTimeInMs), status.name(),
dateFormatter.format(endTimeInMs), elapsed);
return sb.toString();
}
}
private class ExecutionStatsList {
private final List<ExecutionStatsRow> rows = new ArrayList();
public ExecutionStatsList() {
}
public ExecutionStatsList add(ExecutionStatsRow row) {
rows.add(row);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if ((rows == null) || (rows.isEmpty())) {
sb.append("<empty>");
} else {
for (ExecutionStatsRow row : rows) {
sb.append(row.toString());
sb.append("\n");
}
sb.append("\n");
sb.append("Total build time: ");
String elapsed = Utils.msToHms(rows.get(rows.size() - 1).endTimeInMs - rows.get(0).startTimeInMs);
sb.append(elapsed);
}
return sb.toString();
}
}
public class IndexManagerHelpFormatter implements HelpFormatter {
private String errorMessage;
@Override
public String format( Map<String, ? extends OptionDescriptor> options ) {
String buffer =
"Usage: IndexerManager --context=aaa\n" +
" --all\n" +
" | --daily\n" +
" | --cores=aaa [--nodeps]\n" +
" | --cores=aaa,bbb[,ccc [, ...]]\n" +
" \n" +
"where aaa is the context file name (should be on the classpath)\n" +
"and aaa, bbb, and ccc are cores chosen from the list shown below." +
"\n" +
"if '--all' is specified, all cores from experiment to autosuggest are built.\n" +
"if '--daily' is specified, all cores from preqc to autosuggest are built.\n" +
"if ('--core=aaa' is specified, all cores from aaa to autosuggest are built.\n" +
"if ('--cores=aaa --nodeps' is specified, ony core 'aaa' is built.\n" +
"if ('--cores=aaa,bbb[,ccc [, ...]] is specified (i.e. 2 or more cores), only\n" +
" the specified cores are built, and in the order specified.\n" +
" NOTE: specifying --nodeps with multiple cores is superfluous and is ignored,\n" +
" as nodeps is the default for this case.\n" +
"\n" +
"Core list (in priority build order):\n" +
" experiment\n" +
" genotype-phenotype\n" +
" statistical-result\n" +
" preqc\n" +
" allele\n" +
" images\n" +
" impc_images\n" +
" mp\n" +
" ma\n" +
" pipeline\n" +
" gene\n" +
" disease\n" +
" autosuggest\n";
return buffer;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
}
|
src/main/java/uk/ac/ebi/phenotype/solr/indexer/IndexerManager.java
|
/**
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* Copyright © 2014 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.phenotype.solr.indexer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import joptsimple.HelpFormatter;
import joptsimple.OptionDescriptor;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.lang3.StringUtils;
import org.mousephenotype.www.testing.model.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import static uk.ac.ebi.phenotype.solr.indexer.AbstractIndexer.CONTEXT_ARG;
import uk.ac.ebi.phenotype.util.Utils;
/**
* This class encapsulates the code and data necessary to represent an index
* manager that manages the creation and deployment of all of the indexes
* required for phenotype archive; a job previously delegated to Jenkins that
* was susceptible to frequent failure.
*
* @author mrelac
*/
public class IndexerManager {
private static final Logger logger = LoggerFactory.getLogger(IndexerManager.class);
// core names.
// These are built only for a new data release.
public static final String OBSERVATION_CORE = "experiment"; // For historic reasons, the core's actual name is 'experiment'.
public static final String GENOTYPE_PHENOTYPE_CORE = "genotype-phenotype";
public static final String STATSTICAL_RESULT_CORE = "statistical-result";
// These are built daily.
public static final String PREQC_CORE = "preqc_staging";
public static final String ALLELE_CORE = "allele_staging";
public static final String IMAGES_CORE = "images_staging";
public static final String IMPC_IMAGES_CORE = "impc_images_staging";
public static final String MP_CORE = "mp_staging";
public static final String MA_CORE = "ma_staging";
public static final String PIPELINE_CORE = "pipeline_staging";
public static final String GENE_CORE = "gene_staging";
public static final String DISEASE_CORE = "disease_staging";
public static final String AUTOSUGGEST_CORE = "autosuggest_staging";
// main return values.
public static final int STATUS_OK = 0;
public static final int STATUS_NO_DEPS = 1;
public static final int STATUS_NO_ARGUMENT = 2;
public static final int STATUS_UNRECOGNIZED_OPTION = 3;
public static final int STATUS_INVALID_CORE_NAME = 4;
public static final int STATUS_VALIDATION_ERROR = 5;
public static String getStatusCodeName(int statusCode) {
switch (statusCode) {
case STATUS_OK: return "STATUS_OK";
case STATUS_NO_DEPS: return "STATUS_NO_DEPS";
case STATUS_NO_ARGUMENT: return "STATUS_NO_ARGUMENT";
case STATUS_UNRECOGNIZED_OPTION: return "STATUS_UNRECOGNIZED_OPTION";
case STATUS_INVALID_CORE_NAME: return "STATUS_INVALID_CORE_NAME";
case STATUS_VALIDATION_ERROR: return "STATUS_VALIDATION_ERROR";
default: return "Unknown status code " + statusCode;
}
}
// These are the args that can be passed to the indexer manager.
private Boolean all;
private List<String> cores;
private Boolean daily;
private Boolean nodeps;
private Boolean deploy;
// These are the args passed to the individual indexers. They should be all the same and should be the same context argument passed to the indexerManager.
private String[] indexerArgs;
public static final String[] allCoresArray = new String[] { // In dependency order.
// In dependency order. These are built only for a new data release.
OBSERVATION_CORE
, GENOTYPE_PHENOTYPE_CORE
, STATSTICAL_RESULT_CORE
// These are built daily.
, PREQC_CORE
, ALLELE_CORE
, IMAGES_CORE
, IMPC_IMAGES_CORE
, MP_CORE
, MA_CORE
, PIPELINE_CORE
, GENE_CORE
, DISEASE_CORE
, AUTOSUGGEST_CORE
};
private final List<String> allCoresList = Arrays.asList(allCoresArray);
public static final String[] allDailyCoresArray = new String[] {
// In dependency order. These are built daily.
PREQC_CORE
, ALLELE_CORE
, IMAGES_CORE
, IMPC_IMAGES_CORE
, MP_CORE
, MA_CORE
, PIPELINE_CORE
, GENE_CORE
, DISEASE_CORE
, AUTOSUGGEST_CORE
};
public static final int RETRY_COUNT = 5; // If any core fails, retry building it up to this many times.
public static final int RETRY_SLEEP_IN_MS = 60000; // If any core fails, sleep this long before reattempting to build the core.
public static final String STAGING_SUFFIX = "_staging"; // This snippet is appended to core names meant to be staging core names.
private enum RunStatus { OK, FAIL };
@Resource(name = "globalConfiguration")
private Map<String, String> config;
@Autowired
ObservationIndexer observationIndexer;
@Autowired
GenotypePhenotypeIndexer genotypePhenotypeIndexer;
@Autowired
StatisticalResultIndexer statisticalResultIndexer;
@Autowired
PreqcIndexer preqcIndexer;
@Autowired
AlleleIndexer alleleIndexer;
@Autowired
SangerImagesIndexer imagesIndexer;
@Autowired
ImpcImagesIndexer impcImagesIndexer;
@Autowired
MPIndexer mpIndexer;
@Autowired
MAIndexer maIndexer;
@Autowired
PipelineIndexer pipelineIndexer;
@Autowired
GeneIndexer geneIndexer;
@Autowired
DiseaseIndexer diseaseIndexer;
@Autowired
AutosuggestIndexer autosuggestIndexer;
private String buildIndexesSolrUrl;
private IndexerItem[] indexerItems;
public String[] args;
public static final String ALL_ARG = "all";
public static final String CORES_ARG = "cores";
public static final String DAILY_ARG = "daily";
public static final String DEPLOY_ARG = "deploy";
public static final String NO_DEPS_ARG = "nodeps";
public class IndexerItem {
public final String name;
public final AbstractIndexer indexer;
public IndexerItem(String name, AbstractIndexer indexer) {
this.name = name;
this.indexer = indexer;
}
}
protected ApplicationContext applicationContext;
// GETTERS
public Boolean getAll() {
return all;
}
public List<String> getCores() {
return cores;
}
public Boolean getDaily() {
return daily;
}
public static Logger getLogger() {
return logger;
}
public Boolean getNodeps() {
return nodeps;
}
public Boolean getDeploy() {
return deploy;
}
// PUBLIC/PROTECTED METHODS
public void initialise(String[] args) throws IndexerException {
OptionSet options = parseCommandLine(args);
if (options != null) {
this.args = args;
applicationContext = loadApplicationContext((String)options.valuesOf(CONTEXT_ARG).get(0));
applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
initialiseHibernateSession(applicationContext);
loadIndexers();
} else {
throw new IndexerException("Failed to parse command-line options.");
}
buildIndexesSolrUrl = config.get("buildIndexesSolrUrl");
// Print the jvm memory configuration.
final int mb = 1024*1024;
Runtime runtime = Runtime.getRuntime();
DecimalFormat formatter = new DecimalFormat("#,###");
logger.info("Used memory : " + (formatter.format(runtime.totalMemory() - runtime.freeMemory() / mb)));
logger.info("Free memory : " + formatter.format(runtime.freeMemory()));
logger.info("Total memory: " + formatter.format(runtime.totalMemory()));
logger.info("Max memory : " + formatter.format(runtime.maxMemory()));
}
protected void initialiseHibernateSession(ApplicationContext applicationContext) {
// allow hibernate session to stay open the whole execution
PlatformTransactionManager transactionManager = (PlatformTransactionManager) applicationContext.getBean("transactionManager");
DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED);
transactionAttribute.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
transactionManager.getTransaction(transactionAttribute);
}
public void run() throws IndexerException {
ExecutionStatsList executionStatsList = new ExecutionStatsList();
logger.info("Starting IndexerManager. nodeps = " + nodeps + ". Building the following cores (in order):");
logger.info("\t" + StringUtils.join(cores));
for (IndexerItem indexerItem : indexerItems) {
long start = new Date().getTime();
indexerItem.indexer.initialise(indexerArgs);
// If the core build fails, retry up to RETRY_COUNT times before failing the IndexerManager build.
for (int i = 0; i <= RETRY_COUNT; i++) {
try {
buildStagingArea();
indexerItem.indexer.run();
indexerItem.indexer.validateBuild();
break;
} catch (IndexerException ie) {
if (i < RETRY_COUNT) {
logger.warn("IndexerException: core build attempt[" + i + "] failed. Retrying.");
logErrors(ie);
TestUtils.sleep(RETRY_SLEEP_IN_MS);
} else {
System.out.println(executionStatsList.add(new ExecutionStatsRow(indexerItem.name, RunStatus.FAIL, start, new Date().getTime())).toString());
throw ie;
}
} catch (Exception e) {
if (i < RETRY_COUNT) {
logger.warn("Exception: core build attempt[" + i + "] failed. Retrying.");
logErrors(new IndexerException(e));
TestUtils.sleep(RETRY_SLEEP_IN_MS);
} else {
System.out.println(executionStatsList.add(new ExecutionStatsRow(indexerItem.name, RunStatus.FAIL, start, new Date().getTime())).toString());
throw new IndexerException(e);
}
}
}
executionStatsList.add(new ExecutionStatsRow(indexerItem.name, RunStatus.OK, start, new Date().getTime()));
}
System.out.println(executionStatsList.toString());
}
protected ApplicationContext loadApplicationContext(String context) {
ApplicationContext appContext;
try {
// Try context as a file resource
getLogger().info("Trying to load context from file system...");
appContext = new FileSystemXmlApplicationContext("file:" + context);
getLogger().info("Context loaded from file system");
} catch (BeansException e) {
getLogger().warn("Unable to load the context file: {}", e.getMessage());
// Try context as a class path resource
appContext = new ClassPathXmlApplicationContext(context);
getLogger().warn("Using classpath app-config file: {}", context);
}
return appContext;
}
public void validateParameters(OptionSet options, List<String> coresRequested) throws IndexerException {
// Exactly one of: ALL_ARG, DAILY_ARG, or CORES_ARG must be specified.
if ( ! (options.has(ALL_ARG) || (options.has(DAILY_ARG) || options.has(CORES_ARG)))) {
throw new IndexerException(new MissingRequiredArgumentException("Expected either --all, --daily, or --cores=aaa"));
}
// if DAILY_ARG specified, no other args are allowed.
if (options.has(ALL_ARG)) {
if ((options.has(DAILY_ARG)) || (options.has(CORES_ARG)) || (options.has(NO_DEPS_ARG))) {
throw new IndexerException(new ValidationException("Expected exactly one of: --all, --daily, or --cores=aaa"));
}
}
// if DAILY_ARG specified, no other args are allowed.
if (options.has(DAILY_ARG)) {
if ((options.has(ALL_ARG)) || (options.has(CORES_ARG)) || (options.has(NO_DEPS_ARG))) {
throw new IndexerException(new ValidationException("Expected exactly one of: --all, --daily, or --cores=aaa"));
}
}
// if CORES_ARG specified, neither ALL_ARG nor DAILY_ARG is permitted.
if (options.has(CORES_ARG)) {
if ((options.has(ALL_ARG)) || (options.has(DAILY_ARG))) {
throw new IndexerException(new ValidationException("Expected exactly one of: --all, --daily, or --cores=aaa"));
}
}
// NO_DEPS_ARG may only be specified with CORES_ARG.
if (options.has(NO_DEPS_ARG)) {
if ((options.has(ALL_ARG)) || (options.has(DAILY_ARG))) {
throw new IndexerException(new ValidationException("--nodeps may only be specified with --cores"));
}
}
// Verify that each core name in coresRequested exists. Throw an exception if any does not.
for (String core : coresRequested) {
if ( ! allCoresList.contains(core)) {
throw new IndexerException(new InvalidCoreNameException("Invalid core name '" + core + "'"));
}
}
}
// PRIVATE METHODS
private void loadIndexers() {
List<IndexerItem> indexerItemList = new ArrayList();
for (String core : cores) {
switch (core) {
case OBSERVATION_CORE: indexerItemList.add(new IndexerItem(OBSERVATION_CORE, observationIndexer)); break;
case GENOTYPE_PHENOTYPE_CORE: indexerItemList.add(new IndexerItem(GENOTYPE_PHENOTYPE_CORE, genotypePhenotypeIndexer)); break;
case STATSTICAL_RESULT_CORE: indexerItemList.add(new IndexerItem(STATSTICAL_RESULT_CORE, statisticalResultIndexer)); break;
case PREQC_CORE: indexerItemList.add(new IndexerItem(PREQC_CORE, preqcIndexer)); break;
case ALLELE_CORE: indexerItemList.add(new IndexerItem(ALLELE_CORE, alleleIndexer)); break;
case IMAGES_CORE: indexerItemList.add(new IndexerItem(IMAGES_CORE, imagesIndexer)); break;
case IMPC_IMAGES_CORE: indexerItemList.add(new IndexerItem(IMPC_IMAGES_CORE, impcImagesIndexer)); break;
case MP_CORE: indexerItemList.add(new IndexerItem(MP_CORE, mpIndexer)); break;
case MA_CORE: indexerItemList.add(new IndexerItem(MA_CORE, maIndexer)); break;
case PIPELINE_CORE: indexerItemList.add(new IndexerItem(PIPELINE_CORE, pipelineIndexer)); break;
case GENE_CORE: indexerItemList.add(new IndexerItem(GENE_CORE, geneIndexer)); break;
case DISEASE_CORE: indexerItemList.add(new IndexerItem(DISEASE_CORE, diseaseIndexer)); break;
case AUTOSUGGEST_CORE: indexerItemList.add(new IndexerItem(AUTOSUGGEST_CORE, autosuggestIndexer)); break;
}
}
indexerItems = indexerItemList.toArray(new IndexerItem[0]);
}
// PRIVATE METHODS
/*
* Rules:
* 1. context is always required.
* 2. cores is optional.
* 2a. If cores is missing or empty:
* - build all cores starting at the preqc core (don't build OBSERVATION_CORE, GENOTYPE_PHENOTYPE_CORE, or STATSTICAL_RESULT_CORE).
* - specifying nodeps throws IllegalArgumentException.
* 2b. If 1 core:
* - core name must be valid.
* - if nodeps is specified:
* - build only the specified core. Don't build downstream cores.
* - else
* - build requested core and all downstream cores.
* 2c. If more than 1 core:
* - if nodeps is specified, it is ignored.
* - core names must be valid. No downstream cores are built.
*
* Core Build Truth Table (assume a valid '--context=' parameter is always supplied - not shown in table below to save space):
* |---------------------------------------------------------------------------|
* | command line | nodeps value | cores built |
* |---------------------------------------------------------------------------|
* | <empty> | false | preqc to autosuggest |
* | --cores | false | preqc to autosuggest |
* | --nodeps | NoDepsException | <none> |
* | --cores --nodeps | NoDepsException | <none> |
* | --cores=mp | false | mp to autosuggest |
* | --cores=mp --nodeps | true | mp |
* | --cores=mp,observation | true | mp,observation |
* | --cores-mp,observation --nodeps | true | mp,observation |
* |---------------------------------------------------------------------------|
* @param args command-line arguments
* @return<code>OptionSet</code> of parsed parameters
* @throws IndexerException
*/
/*
* Rules:
* 1. context is always required.
* 2. cores is always required.
* 2b. If 1 core:
* - core name must be valid.
* - if nodeps is specified:
* - build only the specified core. Don't build downstream cores.
* - else
* - build requested core and all downstream cores.
* 2c. If more than 1 core:
* - if nodeps is specified, it is ignored.
* - core names must be valid. No downstream cores are built.
* 3. If 'all' is specified, build all of the cores: experiment to autosuggest.
* Specifying --nodeps throws IllegalArgumentException.
* 4. If 'daily' is specified, build the daily cores: preqc to autosuggest.
* Specifying --nodeps throws IllegalArgumentException.
*
* Core Build Truth Table (assume a valid '--context=' parameter is always supplied - not shown in table below to save space):
* |-----------------------------------------------------------------------------------|
* | command line | Action | nodeps value |
* |-----------------------------------------------------------------------------------|
* | <empty> | Throw MissingRequiredArgumentException | N/A |
* | --cores | Throw MissingRequiredArgumentException | N/A |
* | --nodeps | Throw MissingRequiredArgumentException | N/A |
* | --cores --nodeps | Throw MissingRequiredArgumentException | N/A |
* | --cores= --nodeps | Throw MissingRequiredArgumentException | N/A |
* | --cores=junk | Throw InvalidCoreNameException | N/A |
* | --cores=mp | build mp to autosuggest cores | false |
* | --cores=mp --nodeps | build mp core only | true |
* | --cores=mp,ma | build mp and ma cores | true |
* | --cores-mp,ma --nodeps | build mp and ma cores | true |
* | --all | build experiment to autosuggest cores | false |
* | --all --cores=ma | Return STATUS_VALIDATION_ERROR | N/A |
* | --all --nodeps | Return STATUS_VALIDATION_ERROR | N/A |
* | --daily | build preqc to autosuggest cores. | false |
* | --daily --cores=ma | Return STATUS_VALIDATION_ERROR | N/A |
* | --daily --nodeps | Return STATUS_VALIDATION_ERROR | N/A |
* | --all --daily | Return STATUS_VALIDATION_ERROR | N/A |
* | --all --daily --nodeps | Return STATUS_VALIDATION_ERROR | N/A |
* |-----------------------------------------------------------------------------------|
* @param args command-line arguments
* @return<code>OptionSet</code> of parsed parameters
* @throws IndexerException
*/
private OptionSet parseCommandLine(String[] args) throws IndexerException {
OptionParser parser = new OptionParser();
OptionSet options = null;
// Spring context file parameter [required]
parser.accepts(CONTEXT_ARG)
.withRequiredArg()
.required()
.ofType(String.class)
.describedAs("Spring context file, such as 'index-app-config.xml'");
// cores [optional]
parser.accepts(CORES_ARG)
.withRequiredArg()
.ofType(String.class)
.describedAs("A list of cores, in build order.");
parser.accepts(ALL_ARG);
parser.accepts(DAILY_ARG);
parser.accepts(NO_DEPS_ARG);
parser.accepts(DEPLOY_ARG);
try {
// Parse the parameters.
options = parser.parse(args);
boolean coreMissingOrEmpty = false;
List<String> coresRequested = new ArrayList(); // This is a list of the unique core values specified in the 'cores=' argument.
// Create a list of cores requested based on the value the 'cores=' argument.
if (options.has(CORES_ARG)) {
String rawCoresArgument = (String)options.valueOf((CORES_ARG));
if ((rawCoresArgument == null) || (rawCoresArgument.trim().isEmpty())) {
// Cores list is empty.
coreMissingOrEmpty = true;
} else if ( ! rawCoresArgument.contains(",")) {
coresRequested.add(rawCoresArgument);
} else {
String[] coresArray = ((String)options.valueOf(CORES_ARG)).split(",");
coresRequested.addAll(Arrays.asList(coresArray));
}
} else {
// Cores list is missing.
coreMissingOrEmpty = true;
}
// The only case where nodeps is true is when:
// --cores is specified, AND
// (--nodeps is specified OR # cores requested > 1)
if ((options.has(NO_DEPS_ARG)) && (options.has(NO_DEPS_ARG) || coresRequested.size() > 1)) {
nodeps = true;
} else {
nodeps = false;
}
validateParameters(options, coresRequested);
// Build the cores list as follows:
// If --all specified, set firstCore to experiment.
// Else if --daily specified, set firstCore to preqc.
// Else if --cores specified
// If nodeps or coresRequested.size > 1
// set firstCore to null.
// set cores to coresRequested[0].
// Else
// set firstCore to coresRequested[0].
//
// If firstCore is not null
// search allCoresArray for the 0-relative firstCoreOffset of the value matching firstCore.
// add to cores every core name from firstCoreOffset to the last core in allCoresList.
String firstCore = null;
cores = new ArrayList();
if (options.has(ALL_ARG)) {
firstCore = OBSERVATION_CORE;
} else if (options.has(DAILY_ARG)) {
firstCore = PREQC_CORE;
} else if (options.has(CORES_ARG)) {
if ((nodeps) || coresRequested.size() > 1) {
cores.addAll(coresRequested);
} else {
firstCore = coresRequested.get(0);
}
}
if (firstCore != null) {
int firstCoreOffset = 0;
for (String core : allCoresArray) {
if (core.equals(firstCore)) {
break;
}
firstCoreOffset++;
}
for (int i = firstCoreOffset; i < allCoresArray.length; i++) {
cores.add(allCoresArray[i]);
}
}
} catch (IndexerException ie) {
if ((ie.getLocalizedMessage() != null) && ( ! ie.getLocalizedMessage().isEmpty())) {
System.out.println(ie.getLocalizedMessage() + "\n");
}
try { parser.printHelpOn(System.out); } catch (Exception e) {}
throw ie;
} catch (Exception uoe) {
Throwable t;
if (uoe.getLocalizedMessage().contains("is not a recognized option")) {
t = new UnrecognizedOptionException(uoe);
} else if (uoe.getLocalizedMessage().contains(" requires an argument")) {
t = new MissingRequiredArgumentException(uoe);
} else if (uoe.getLocalizedMessage().contains("Missing required option(s)")) {
t = new MissingRequiredArgumentException(uoe);
} else {
t = uoe;
}
try {
if ((uoe.getLocalizedMessage() != null) && ( ! uoe.getLocalizedMessage().isEmpty())) {
System.out.println(uoe.getLocalizedMessage() + "\n");
}
parser.formatHelpWith( new IndexManagerHelpFormatter() );
parser.printHelpOn(System.out);
} catch (Exception e) {}
throw new IndexerException(t);
}
indexerArgs = new String[] { "--context=" + (String)options.valueOf(CONTEXT_ARG) };
logger.info("indexer config file: '" + indexerArgs[0] + "'");
return options;
}
private void buildStagingArea() {
////// // Insure staging cores are deleted.
////// for (String core : cores) {
////// String stagingCoreFilename = buildIndexesSolrUrl + File.separator + core + STAGING_SUFFIX;
////// File file = new File(stagingCoreFilename);
//////
////// boolean b = file.canRead();
////// System.out.println();
//////
//////
//////
////// System.exit(999);
////// }
// Build and initialise staging core directories.
// Fetch schemas from git.
// Create the cores.
}
public static void main(String[] args) throws IndexerException {
int retVal = mainReturnsStatus(args);
if (retVal != STATUS_OK) {
throw new IndexerException("Build failed: " + getStatusCodeName(retVal));
}
}
public static int mainReturnsStatus(String[] args) {
try {
IndexerManager manager = new IndexerManager();
manager.initialise(args);
manager.run();
logger.info("IndexerManager process finished successfully. Exiting.");
} catch (IndexerException ie) {
logErrors(ie);
if (ie.getCause() instanceof NoDepsException) {
return STATUS_NO_DEPS;
} else if (ie.getCause() instanceof MissingRequiredArgumentException) {
return STATUS_NO_ARGUMENT;
} else if (ie.getCause() instanceof UnrecognizedOptionException) {
return STATUS_UNRECOGNIZED_OPTION;
} else if (ie.getCause() instanceof InvalidCoreNameException) {
return STATUS_INVALID_CORE_NAME;
} else if (ie.getCause() instanceof ValidationException) {
return STATUS_VALIDATION_ERROR;
} else if (ie.getCause() instanceof MissingRequiredArgumentException) {
return STATUS_NO_ARGUMENT;
}
return -1;
}
return STATUS_OK;
}
private static void logErrors(IndexerException ie) {
// Print out the exceptions.
if (ie.getLocalizedMessage() != null) {
logger.error(ie.getLocalizedMessage());
}
int i = 0;
Throwable t = ie.getCause();
while (t != null) {
StringBuilder errMsg = new StringBuilder("Level " + i + ": ");
if (t.getLocalizedMessage() != null) {
errMsg.append(t.getLocalizedMessage());
} else {
errMsg.append("<null>");
}
logger.error(errMsg.toString());
i++;
t = t.getCause();
}
}
/**
* Represents an execution status row. Used to display execution status in
* a readable format. Example:
* "preqc started xxx. Finshed (OK) yyy. Elapsed time: hh:mm:ss".
*/
private class ExecutionStatsRow {
private String coreName;
private RunStatus status;
private Long startTimeInMs;
private Long endTimeInMs;
public ExecutionStatsRow() {
this("<undefined>", RunStatus.FAIL, 0, 0);
}
public ExecutionStatsRow(String coreName, RunStatus status, long startTimeInMs, long endTimeInMs) {
this.coreName = coreName;
this.status = status;
this.startTimeInMs = startTimeInMs;
this.endTimeInMs = endTimeInMs;
}
@Override
public String toString() {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
long millis = endTimeInMs - startTimeInMs;
String elapsed = Utils.msToHms(millis);
formatter.format("%20s started %s. Finished (%s) %s. Elapsed time: %s",
coreName, dateFormatter.format(startTimeInMs), status.name(),
dateFormatter.format(endTimeInMs), elapsed);
return sb.toString();
}
}
private class ExecutionStatsList {
private final List<ExecutionStatsRow> rows = new ArrayList();
public ExecutionStatsList() {
}
public ExecutionStatsList add(ExecutionStatsRow row) {
rows.add(row);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if ((rows == null) || (rows.isEmpty())) {
sb.append("<empty>");
} else {
for (ExecutionStatsRow row : rows) {
sb.append(row.toString());
sb.append("\n");
}
sb.append("\n");
sb.append("Total build time: ");
String elapsed = Utils.msToHms(rows.get(rows.size() - 1).endTimeInMs - rows.get(0).startTimeInMs);
sb.append(elapsed);
}
return sb.toString();
}
}
public class IndexManagerHelpFormatter implements HelpFormatter {
private String errorMessage;
@Override
public String format( Map<String, ? extends OptionDescriptor> options ) {
String buffer =
"Usage: IndexerManager --context=aaa\n" +
" --all\n" +
" | --daily\n" +
" | --cores=aaa [--nodeps]\n" +
" | --cores=aaa,bbb[,ccc [, ...]]\n" +
" \n" +
"where aaa is the context file name (should be on the classpath)\n" +
"and aaa, bbb, and ccc are cores chosen from the list shown below." +
"\n" +
"if '--all' is specified, all cores from experiment to autosuggest are built.\n" +
"if '--daily' is specified, all cores from preqc to autosuggest are built.\n" +
"if ('--core=aaa' is specified, all cores from aaa to autosuggest are built.\n" +
"if ('--cores=aaa --nodeps' is specified, ony core 'aaa' is built.\n" +
"if ('--cores=aaa,bbb[,ccc [, ...]] is specified (i.e. 2 or more cores), only\n" +
" the specified cores are built, and in the order specified.\n" +
" NOTE: specifying --nodeps with multiple cores is superfluous and is ignored,\n" +
" as nodeps is the default for this case.\n" +
"\n" +
"Core list (in priority build order):\n" +
" experiment\n" +
" genotype-phenotype\n" +
" statistical-result\n" +
" preqc\n" +
" allele\n" +
" images\n" +
" impc_images\n" +
" mp\n" +
" ma\n" +
" pipeline\n" +
" gene\n" +
" disease\n" +
" autosuggest\n";
return buffer;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
}
|
Forgot to add _staging to experiment, g-p and statistical-result core names.
|
src/main/java/uk/ac/ebi/phenotype/solr/indexer/IndexerManager.java
|
Forgot to add _staging to experiment, g-p and statistical-result core names.
|
<ide><path>rc/main/java/uk/ac/ebi/phenotype/solr/indexer/IndexerManager.java
<ide>
<ide> // core names.
<ide> // These are built only for a new data release.
<del> public static final String OBSERVATION_CORE = "experiment"; // For historic reasons, the core's actual name is 'experiment'.
<del> public static final String GENOTYPE_PHENOTYPE_CORE = "genotype-phenotype";
<del> public static final String STATSTICAL_RESULT_CORE = "statistical-result";
<add> public static final String OBSERVATION_CORE = "experiment_staging"; // For historic reasons, the core's actual name is 'experiment'.
<add> public static final String GENOTYPE_PHENOTYPE_CORE = "genotype-phenotype_staging";
<add> public static final String STATSTICAL_RESULT_CORE = "statistical-result_staging";
<ide>
<ide> // These are built daily.
<ide> public static final String PREQC_CORE = "preqc_staging";
|
|
Java
|
apache-2.0
|
15c227d8042a09d6a95d67d4c217fa650945c757
| 0 |
ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,da1z/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,da1z/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,ibinti/intellij-community
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.ui.FontInfo;
import org.jetbrains.annotations.Nullable;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
/**
* @author Sergey.Malenkov
*/
public final class FontComboBox extends ComboBox {
private static final FontInfoRenderer RENDERER = new FontInfoRenderer();
private Model myModel;
public FontComboBox() {
this(false);
}
public FontComboBox(boolean withAllStyles) {
this(withAllStyles, true, false);
}
public FontComboBox(boolean withAllStyles, boolean filterNonLatin, boolean noFontItem) {
super(new Model(withAllStyles, filterNonLatin, noFontItem));
Dimension size = getPreferredSize();
size.width = size.height * 8;
setPreferredSize(size);
setSwingPopup(true);
setRenderer(RENDERER);
}
public boolean isMonospacedOnly() {
return myModel.myMonospacedOnly;
}
public void setMonospacedOnly(boolean monospaced) {
if (myModel.myMonospacedOnly != monospaced) {
myModel.myMonospacedOnly = monospaced;
myModel.updateSelectedItem();
}
}
public String getFontName() {
Object item = myModel.getSelectedItem();
return item == null ? null : item.toString();
}
public void setFontName(@Nullable String item) {
myModel.setSelectedItem(item);
}
public boolean isNoFontSelected() {
return myModel.isNoFontSelected();
}
@Override
public void setModel(ComboBoxModel model) {
if (model instanceof Model) {
myModel = (Model)model;
super.setModel(model);
}
else {
throw new UnsupportedOperationException();
}
}
private static final class Model extends AbstractListModel implements ComboBoxModel {
private final NoFontItem myNoFontItem;
private volatile List<FontInfo> myAllFonts = Collections.emptyList();
private volatile List<FontInfo> myMonoFonts = Collections.emptyList();
private boolean myMonospacedOnly;
private Object mySelectedItem;
private Model(boolean withAllStyles, boolean filterNonLatin, boolean noFontItem) {
myNoFontItem = noFontItem ? new NoFontItem() : null;
Application application = ApplicationManager.getApplication();
if (application == null || application.isUnitTestMode()) {
setFonts(FontInfo.getAll(withAllStyles), filterNonLatin);
}
else {
application.executeOnPooledThread(() -> {
List<FontInfo> all = FontInfo.getAll(withAllStyles);
application.invokeLater(() -> {
setFonts(all, filterNonLatin);
updateSelectedItem();
}, application.getAnyModalityState());
});
}
}
private void setFonts(List<FontInfo> all, boolean filterNonLatin) {
List<FontInfo> allFonts = new ArrayList<>(all.size());
List<FontInfo> monoFonts = new ArrayList<>();
for (FontInfo info : all) {
if (!filterNonLatin || info.getFont().canDisplayUpTo(info.toString()) == -1) {
allFonts.add(info);
if (info.isMonospaced()) {
monoFonts.add(info);
}
}
}
myAllFonts = allFonts;
myMonoFonts = monoFonts;
}
private void updateSelectedItem() {
Object item = getSelectedItem();
setSelectedItem(null);
setSelectedItem(item);
}
@Override
public Object getSelectedItem() {
return mySelectedItem;
}
@Override
public void setSelectedItem(@Nullable Object item) {
if (item == null && myNoFontItem != null) {
item = myNoFontItem;
}
else {
if (item instanceof FontInfo) {
FontInfo info = getInfo(item);
if (info == null) {
List<FontInfo> list = myMonospacedOnly ? myMonoFonts : myAllFonts;
item = list.isEmpty() ? null : list.get(0);
}
}
if (item instanceof String) {
FontInfo info = getInfo(item);
if (info != null) item = info;
}
}
if (!Comparing.equal(mySelectedItem, item) || item == myNoFontItem) {
mySelectedItem = item;
fireContentsChanged(this, -1, -1);
}
}
public boolean isNoFontSelected() {
return getSelectedItem() == myNoFontItem;
}
@Override
public int getSize() {
List<FontInfo> list = myMonospacedOnly ? myMonoFonts : myAllFonts;
int size = list.size();
if (mySelectedItem instanceof String) size ++;
if (myNoFontItem != null) size++;
return size;
}
@Override
public Object getElementAt(int index) {
int i = index;
if (myNoFontItem != null) {
if (index == 0) return myNoFontItem;
i --;
}
List<FontInfo> list = myMonospacedOnly ? myMonoFonts : myAllFonts;
return 0 <= i && i < list.size() ? list.get(i) : mySelectedItem;
}
private FontInfo getInfo(Object item) {
for (FontInfo info : myMonospacedOnly ? myMonoFonts : myAllFonts) {
if (item instanceof String ? info.toString().equalsIgnoreCase((String)item) : info.equals(item)) {
return info;
}
}
return null;
}
private final static class NoFontItem {
@Override
public String toString() {
return ApplicationBundle.message("settings.editor.font.none");
}
}
}
}
|
platform/platform-impl/src/com/intellij/ui/FontComboBox.java
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.util.ui.FontInfo;
import org.jetbrains.annotations.Nullable;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
/**
* @author Sergey.Malenkov
*/
public final class FontComboBox extends ComboBox {
private static final FontInfoRenderer RENDERER = new FontInfoRenderer();
private Model myModel;
public FontComboBox() {
this(false);
}
public FontComboBox(boolean withAllStyles) {
this(withAllStyles, true, false);
}
public FontComboBox(boolean withAllStyles, boolean filterNonLatin, boolean noFontItem) {
super(new Model(withAllStyles, filterNonLatin, noFontItem));
Dimension size = getPreferredSize();
size.width = size.height * 8;
setPreferredSize(size);
setSwingPopup(true);
setRenderer(RENDERER);
}
public boolean isMonospacedOnly() {
return myModel.myMonospacedOnly;
}
public void setMonospacedOnly(boolean monospaced) {
if (myModel.myMonospacedOnly != monospaced) {
myModel.myMonospacedOnly = monospaced;
myModel.updateSelectedItem();
}
}
public String getFontName() {
Object item = myModel.getSelectedItem();
return item == null ? null : item.toString();
}
public void setFontName(@Nullable String item) {
myModel.setSelectedItem(item);
}
public boolean isNoFontSelected() {
return myModel.isNoFontSelected();
}
@Override
public void setModel(ComboBoxModel model) {
if (model instanceof Model) {
myModel = (Model)model;
super.setModel(model);
}
else {
throw new UnsupportedOperationException();
}
}
private static final class Model extends AbstractListModel implements ComboBoxModel {
private final NoFontItem myNoFontItem;
private volatile List<FontInfo> myAllFonts = Collections.emptyList();
private volatile List<FontInfo> myMonoFonts = Collections.emptyList();
private boolean myMonospacedOnly;
private Object mySelectedItem;
private Model(boolean withAllStyles, boolean filterNonLatin, boolean noFontItem) {
myNoFontItem = noFontItem ? new NoFontItem() : null;
Application application = ApplicationManager.getApplication();
if (application == null || application.isUnitTestMode()) {
setFonts(FontInfo.getAll(withAllStyles), filterNonLatin);
}
else {
application.executeOnPooledThread(() -> {
List<FontInfo> all = FontInfo.getAll(withAllStyles);
application.invokeLater(() -> {
setFonts(all, filterNonLatin);
updateSelectedItem();
}, application.getAnyModalityState());
});
}
}
private void setFonts(List<FontInfo> all, boolean filterNonLatin) {
List<FontInfo> allFonts = new ArrayList<>(all.size());
List<FontInfo> monoFonts = new ArrayList<>();
for (FontInfo info : all) {
if (!filterNonLatin || info.getFont().canDisplayUpTo(info.toString()) == -1) {
allFonts.add(info);
if (info.isMonospaced()) {
monoFonts.add(info);
}
}
}
myAllFonts = allFonts;
myMonoFonts = monoFonts;
}
private void updateSelectedItem() {
Object item = getSelectedItem();
setSelectedItem(null);
setSelectedItem(item);
}
@Override
public Object getSelectedItem() {
return mySelectedItem;
}
@Override
public void setSelectedItem(@Nullable Object item) {
if (item == null && myNoFontItem != null) {
item = myNoFontItem;
}
else {
if (item instanceof FontInfo) {
FontInfo info = getInfo(item);
if (info == null) {
List<FontInfo> list = myMonospacedOnly ? myMonoFonts : myAllFonts;
item = list.isEmpty() ? null : list.get(0);
}
}
if (item instanceof String) {
FontInfo info = getInfo(item);
if (info != null) item = info;
}
}
if (!(mySelectedItem == null ? item == null : mySelectedItem.equals(item))) {
mySelectedItem = item;
fireContentsChanged(this, -1, -1);
}
}
public boolean isNoFontSelected() {
return getSelectedItem() == myNoFontItem;
}
@Override
public int getSize() {
List<FontInfo> list = myMonospacedOnly ? myMonoFonts : myAllFonts;
int size = list.size();
if (mySelectedItem instanceof String) size ++;
if (myNoFontItem != null) size++;
return size;
}
@Override
public Object getElementAt(int index) {
int i = index;
if (myNoFontItem != null) {
if (index == 0) return myNoFontItem;
i --;
}
List<FontInfo> list = myMonospacedOnly ? myMonoFonts : myAllFonts;
return 0 <= i && i < list.size() ? list.get(i) : mySelectedItem;
}
private FontInfo getInfo(Object item) {
for (FontInfo info : myMonospacedOnly ? myMonoFonts : myAllFonts) {
if (item instanceof String ? info.toString().equalsIgnoreCase((String)item) : info.equals(item)) {
return info;
}
}
return null;
}
private final static class NoFontItem {
@Override
public String toString() {
return ApplicationBundle.message("settings.editor.font.none");
}
}
}
}
|
FIXED IDEA-174367 Font settings: Can't set non-monospace fallback font
|
platform/platform-impl/src/com/intellij/ui/FontComboBox.java
|
FIXED IDEA-174367 Font settings: Can't set non-monospace fallback font
|
<ide><path>latform/platform-impl/src/com/intellij/ui/FontComboBox.java
<ide> import com.intellij.openapi.application.ApplicationBundle;
<ide> import com.intellij.openapi.application.ApplicationManager;
<ide> import com.intellij.openapi.ui.ComboBox;
<add>import com.intellij.openapi.util.Comparing;
<ide> import com.intellij.util.ui.FontInfo;
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<ide> if (info != null) item = info;
<ide> }
<ide> }
<del> if (!(mySelectedItem == null ? item == null : mySelectedItem.equals(item))) {
<add> if (!Comparing.equal(mySelectedItem, item) || item == myNoFontItem) {
<ide> mySelectedItem = item;
<ide> fireContentsChanged(this, -1, -1);
<ide> }
|
|
Java
|
apache-2.0
|
8a506e66a66c004a7a253e3dd28845517da8a967
| 0 |
aureagle/cassandra,heiko-braun/cassandra,juiceblender/cassandra,emolsson/cassandra,thobbs/cassandra,project-zerus/cassandra,pofallon/cassandra,yanbit/cassandra,codefollower/Cassandra-Research,boneill42/cassandra,weideng1/cassandra,mt0803/cassandra,adejanovski/cassandra,hengxin/cassandra,tommystendahl/cassandra,jkni/cassandra,qinjin/mdtc-cassandra,Instagram/cassandra,project-zerus/cassandra,yanbit/cassandra,aboudreault/cassandra,regispl/cassandra,guanxi55nba/key-value-store,guanxi55nba/db-improvement,Stratio/cassandra,boneill42/cassandra,mshuler/cassandra,modempachev4/kassandra,nvoron23/cassandra,juiceblender/cassandra,tjake/cassandra,yhnishi/cassandra,sluk3r/cassandra,driftx/cassandra,adelapena/cassandra,dongjiaqiang/cassandra,shawnkumar/cstargraph,michaelsembwever/cassandra,aureagle/cassandra,instaclustr/cassandra,weideng1/cassandra,shawnkumar/cstargraph,adelapena/cassandra,chbatey/cassandra-1,likaiwalkman/cassandra,ifesdjeen/cassandra,Jaumo/cassandra,blambov/cassandra,qinjin/mdtc-cassandra,bdeggleston/cassandra,phact/cassandra,boneill42/cassandra,macintoshio/cassandra,bcoverston/cassandra,codefollower/Cassandra-Research,caidongyun/cassandra,mike-tr-adamson/cassandra,driftx/cassandra,sharvanath/cassandra,Instagram/cassandra,Bj0rnen/cassandra,tommystendahl/cassandra,sriki77/cassandra,pkdevbox/cassandra,fengshao0907/Cassandra-Research,spodkowinski/cassandra,blambov/cassandra,a-buck/cassandra,miguel0afd/cassandra-cqlMod,ibmsoe/cassandra,AtwooTM/cassandra,shawnkumar/cstargraph,yonglehou/cassandra,kangkot/stratio-cassandra,Jaumo/cassandra,sedulam/CASSANDRA-12201,sivikt/cassandra,EnigmaCurry/cassandra,wreda/cassandra,caidongyun/cassandra,josh-mckenzie/cassandra,nlalevee/cassandra,nutbunnies/cassandra,asias/cassandra,yonglehou/cassandra,nakomis/cassandra,Imran-C/cassandra,WorksApplications/cassandra,jrwest/cassandra,asias/cassandra,spodkowinski/cassandra,bmel/cassandra,pkdevbox/cassandra,iburmistrov/Cassandra,kangkot/stratio-cassandra,Instagram/cassandra,aweisberg/cassandra,jeffjirsa/cassandra,sharvanath/cassandra,aarushi12002/cassandra,matthewtt/cassandra_read,ptnapoleon/cassandra,bmel/cassandra,yukim/cassandra,nlalevee/cassandra,bpupadhyaya/cassandra,pthomaid/cassandra,kgreav/cassandra,carlyeks/cassandra,MasahikoSawada/cassandra,knifewine/cassandra,pcmanus/cassandra,matthewtt/cassandra_read,blerer/cassandra,szhou1234/cassandra,belliottsmith/cassandra,dongjiaqiang/cassandra,chaordic/cassandra,carlyeks/cassandra,jsanda/cassandra,rogerchina/cassandra,vaibhi9/cassandra,christian-esken/cassandra,dongjiaqiang/cassandra,DikangGu/cassandra,tommystendahl/cassandra,iamaleksey/cassandra,sivikt/cassandra,emolsson/cassandra,sriki77/cassandra,rackerlabs/cloudmetrics-cassandra,ptuckey/cassandra,strapdata/cassandra,sriki77/cassandra,pofallon/cassandra,jeffjirsa/cassandra,LatencyUtils/cassandra-stress2,jasonwee/cassandra,hhorii/cassandra,yangzhe1991/cassandra,aweisberg/cassandra,jrwest/cassandra,adejanovski/cassandra,ollie314/cassandra,nitsanw/cassandra,dkua/cassandra,mshuler/cassandra,sharvanath/cassandra,aarushi12002/cassandra,regispl/cassandra,yukim/cassandra,josh-mckenzie/cassandra,kangkot/stratio-cassandra,GabrielNicolasAvellaneda/cassandra,ben-manes/cassandra,beobal/cassandra,LatencyUtils/cassandra-stress2,clohfink/cassandra,likaiwalkman/cassandra,joesiewert/cassandra,ptuckey/cassandra,sayanh/ViewMaintenanceCassandra,driftx/cassandra,lalithsuresh/cassandra-c3,likaiwalkman/cassandra,LatencyUtils/cassandra-stress2,Jaumo/cassandra,belliottsmith/cassandra,asias/cassandra,clohfink/cassandra,sayanh/ViewMaintenanceCassandra,sayanh/ViewMaintenanceSupport,cooldoger/cassandra,pallavi510/cassandra,xiongzheng/Cassandra-Research,bcoverston/cassandra,newrelic-forks/cassandra,guanxi55nba/key-value-store,apache/cassandra,phact/cassandra,fengshao0907/Cassandra-Research,apache/cassandra,yhnishi/cassandra,pauloricardomg/cassandra,chaordic/cassandra,Jollyplum/cassandra,DICL/cassandra,fengshao0907/cassandra-1,bcoverston/cassandra,sedulam/CASSANDRA-12201,gdusbabek/cassandra,krummas/cassandra,nutbunnies/cassandra,szhou1234/cassandra,heiko-braun/cassandra,mheffner/cassandra-1,pkdevbox/cassandra,wreda/cassandra,pauloricardomg/cassandra,fengshao0907/cassandra-1,scaledata/cassandra,macintoshio/cassandra,chaordic/cassandra,exoscale/cassandra,vaibhi9/cassandra,mshuler/cassandra,jasobrown/cassandra,aweisberg/cassandra,mambocab/cassandra,yangzhe1991/cassandra,DikangGu/cassandra,pcn/cassandra-1,mheffner/cassandra-1,jeromatron/cassandra,juiceblender/cassandra,Stratio/stratio-cassandra,DikangGu/cassandra,nitsanw/cassandra,mkjellman/cassandra,joesiewert/cassandra,adejanovski/cassandra,ptnapoleon/cassandra,michaelsembwever/cassandra,yonglehou/cassandra,MasahikoSawada/cassandra,RyanMagnusson/cassandra,vramaswamy456/cassandra,kangkot/stratio-cassandra,jasonwee/cassandra,JeremiahDJordan/cassandra,beobal/cassandra,rdio/cassandra,iamaleksey/cassandra,AtwooTM/cassandra,kgreav/cassandra,cooldoger/cassandra,miguel0afd/cassandra-cqlMod,blerer/cassandra,scaledata/cassandra,kangkot/stratio-cassandra,guanxi55nba/db-improvement,guanxi55nba/key-value-store,jasonwee/cassandra,DICL/cassandra,snazy/cassandra,mashuai/Cassandra-Research,thelastpickle/cassandra,jasobrown/cassandra,hhorii/cassandra,wreda/cassandra,joesiewert/cassandra,nlalevee/cassandra,thelastpickle/cassandra,GabrielNicolasAvellaneda/cassandra,jasonstack/cassandra,pallavi510/cassandra,scylladb/scylla-tools-java,gdusbabek/cassandra,krummas/cassandra,phact/cassandra,mike-tr-adamson/cassandra,aarushi12002/cassandra,modempachev4/kassandra,Stratio/stratio-cassandra,scylladb/scylla-tools-java,aweisberg/cassandra,taigetco/cassandra_read,cooldoger/cassandra,nitsanw/cassandra,emolsson/cassandra,strapdata/cassandra,belliottsmith/cassandra,carlyeks/cassandra,aureagle/cassandra,helena/cassandra,jsanda/cassandra,exoscale/cassandra,stef1927/cassandra,darach/cassandra,instaclustr/cassandra,krummas/cassandra,tongjixianing/projects,jkni/cassandra,mambocab/cassandra,caidongyun/cassandra,rmarchei/cassandra,bpupadhyaya/cassandra,adelapena/cassandra,jbellis/cassandra,ptuckey/cassandra,MasahikoSawada/cassandra,kgreav/cassandra,Bj0rnen/cassandra,rdio/cassandra,ibmsoe/cassandra,rogerchina/cassandra,Stratio/cassandra,ejankan/cassandra,blerer/cassandra,clohfink/cassandra,Jollyplum/cassandra,cooldoger/cassandra,ptnapoleon/cassandra,mshuler/cassandra,tongjixianing/projects,weipinghe/cassandra,WorksApplications/cassandra,michaelmior/cassandra,tjake/cassandra,chbatey/cassandra-1,Instagram/cassandra,szhou1234/cassandra,snazy/cassandra,swps/cassandra,ollie314/cassandra,EnigmaCurry/cassandra,driftx/cassandra,pcn/cassandra-1,jasobrown/cassandra,krummas/cassandra,mkjellman/cassandra,lalithsuresh/cassandra-c3,Stratio/cassandra,guard163/cassandra,miguel0afd/cassandra-cqlMod,qinjin/mdtc-cassandra,macintoshio/cassandra,Stratio/stratio-cassandra,jasonstack/cassandra,jeromatron/cassandra,spodkowinski/cassandra,aboudreault/cassandra,knifewine/cassandra,michaelsembwever/cassandra,iburmistrov/Cassandra,apache/cassandra,bcoverston/cassandra,nvoron23/cassandra,blerer/cassandra,EnigmaCurry/cassandra,Jollyplum/cassandra,strapdata/cassandra,rackerlabs/cloudmetrics-cassandra,iamaleksey/cassandra,jeromatron/cassandra,blambov/cassandra,jeffjirsa/cassandra,mike-tr-adamson/cassandra,JeremiahDJordan/cassandra,weideng1/cassandra,scylladb/scylla-tools-java,bdeggleston/cassandra,adelapena/cassandra,blambov/cassandra,pauloricardomg/cassandra,iamaleksey/cassandra,dkua/cassandra,thobbs/cassandra,vramaswamy456/cassandra,yanbit/cassandra,mt0803/cassandra,Stratio/stratio-cassandra,a-buck/cassandra,a-buck/cassandra,ifesdjeen/cassandra,whitepages/cassandra,mashuai/Cassandra-Research,bmel/cassandra,belliottsmith/cassandra,thelastpickle/cassandra,yangzhe1991/cassandra,WorksApplications/cassandra,spodkowinski/cassandra,rmarchei/cassandra,Stratio/stratio-cassandra,rackerlabs/cloudmetrics-cassandra,whitepages/cassandra,jasobrown/cassandra,knifewine/cassandra,tjake/cassandra,fengshao0907/cassandra-1,pcmanus/cassandra,clohfink/cassandra,mt0803/cassandra,beobal/cassandra,pallavi510/cassandra,nutbunnies/cassandra,jrwest/cassandra,stef1927/cassandra,ifesdjeen/cassandra,jkni/cassandra,mheffner/cassandra-1,jsanda/cassandra,stef1927/cassandra,swps/cassandra,beobal/cassandra,bdeggleston/cassandra,guard163/cassandra,project-zerus/cassandra,ejankan/cassandra,DICL/cassandra,ollie314/cassandra,heiko-braun/cassandra,helena/cassandra,mkjellman/cassandra,michaelmior/cassandra,sedulam/CASSANDRA-12201,xiongzheng/Cassandra-Research,nakomis/cassandra,vaibhi9/cassandra,weipinghe/cassandra,swps/cassandra,christian-esken/cassandra,JeremiahDJordan/cassandra,guard163/cassandra,tongjixianing/projects,Imran-C/cassandra,mkjellman/cassandra,newrelic-forks/cassandra,michaelmior/cassandra,rmarchei/cassandra,tommystendahl/cassandra,exoscale/cassandra,ejankan/cassandra,thobbs/cassandra,snazy/cassandra,nakomis/cassandra,darach/cassandra,rogerchina/cassandra,RyanMagnusson/cassandra,hhorii/cassandra,iburmistrov/Cassandra,jeffjirsa/cassandra,rdio/cassandra,GabrielNicolasAvellaneda/cassandra,josh-mckenzie/cassandra,codefollower/Cassandra-Research,sivikt/cassandra,Bj0rnen/cassandra,instaclustr/cassandra,sayanh/ViewMaintenanceSupport,ibmsoe/cassandra,bdeggleston/cassandra,matthewtt/cassandra_read,pcmanus/cassandra,sluk3r/cassandra,ben-manes/cassandra,stef1927/cassandra,thelastpickle/cassandra,lalithsuresh/cassandra-c3,darach/cassandra,christian-esken/cassandra,vramaswamy456/cassandra,jbellis/cassandra,jbellis/cassandra,weipinghe/cassandra,strapdata/cassandra,newrelic-forks/cassandra,scaledata/cassandra,helena/cassandra,dkua/cassandra,taigetco/cassandra_read,ifesdjeen/cassandra,szhou1234/cassandra,scylladb/scylla-tools-java,hengxin/cassandra,kgreav/cassandra,jrwest/cassandra,regispl/cassandra,gdusbabek/cassandra,ben-manes/cassandra,whitepages/cassandra,Imran-C/cassandra,instaclustr/cassandra,josh-mckenzie/cassandra,bpupadhyaya/cassandra,sluk3r/cassandra,mike-tr-adamson/cassandra,pauloricardomg/cassandra,tjake/cassandra,WorksApplications/cassandra,aboudreault/cassandra,yukim/cassandra,fengshao0907/Cassandra-Research,juiceblender/cassandra,xiongzheng/Cassandra-Research,modempachev4/kassandra,pcn/cassandra-1,hengxin/cassandra,chbatey/cassandra-1,pthomaid/cassandra,sayanh/ViewMaintenanceCassandra,pofallon/cassandra,yhnishi/cassandra,RyanMagnusson/cassandra,apache/cassandra,guanxi55nba/db-improvement,taigetco/cassandra_read,yukim/cassandra,jasonstack/cassandra,michaelsembwever/cassandra,pthomaid/cassandra,AtwooTM/cassandra,mashuai/Cassandra-Research,nvoron23/cassandra,snazy/cassandra,mambocab/cassandra
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.tracing;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import org.slf4j.helpers.MessageFormatter;
import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.ArrayBackedSortedColumns;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.service.StorageProxy;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.cassandra.utils.WrappedRunnable;
/**
* ThreadLocal state for a tracing session. The presence of an instance of this class as a ThreadLocal denotes that an
* operation is being traced.
*/
public class TraceState
{
public final UUID sessionId;
public final InetAddress coordinator;
public final Stopwatch watch;
public final ByteBuffer sessionIdBytes;
public TraceState(InetAddress coordinator, UUID sessionId)
{
assert coordinator != null;
assert sessionId != null;
this.coordinator = coordinator;
this.sessionId = sessionId;
sessionIdBytes = ByteBufferUtil.bytes(sessionId);
watch = new Stopwatch();
watch.start();
}
public int elapsed()
{
long elapsed = watch.elapsedTime(TimeUnit.MICROSECONDS);
return elapsed < Integer.MAX_VALUE ? (int) elapsed : Integer.MAX_VALUE;
}
public void trace(String format, Object arg)
{
trace(MessageFormatter.format(format, arg).getMessage());
}
public void trace(String format, Object arg1, Object arg2)
{
trace(MessageFormatter.format(format, arg1, arg2).getMessage());
}
public void trace(String format, Object[] args)
{
trace(MessageFormatter.arrayFormat(format, args).getMessage());
}
public void trace(String message)
{
TraceState.trace(sessionIdBytes, message, elapsed());
}
public static void trace(final ByteBuffer sessionIdBytes, final String message, final int elapsed)
{
final ByteBuffer eventId = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes());
StageManager.getStage(Stage.TRACING).execute(new WrappedRunnable()
{
public void runMayThrow()
{
CFMetaData cfMeta = CFMetaData.TraceEventsCf;
ColumnFamily cf = ArrayBackedSortedColumns.factory.create(cfMeta);
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("activity")), message);
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("source")), FBUtilities.getBroadcastAddress());
if (elapsed >= 0)
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("source_elapsed")), elapsed);
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("activity")), message);
Tracing.mutateWithCatch(new RowMutation(Tracing.TRACE_KS, sessionIdBytes, cf));
}
});
}
}
|
src/java/org/apache/cassandra/tracing/TraceState.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.tracing;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import org.slf4j.helpers.MessageFormatter;
import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.ArrayBackedSortedColumns;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.service.StorageProxy;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.cassandra.utils.WrappedRunnable;
/**
* ThreadLocal state for a tracing session. The presence of an instance of this class as a ThreadLocal denotes that an
* operation is being traced.
*/
public class TraceState
{
public final UUID sessionId;
public final InetAddress coordinator;
public final Stopwatch watch;
public final ByteBuffer sessionIdBytes;
public TraceState(InetAddress coordinator, UUID sessionId)
{
assert coordinator != null;
assert sessionId != null;
this.coordinator = coordinator;
this.sessionId = sessionId;
sessionIdBytes = ByteBufferUtil.bytes(sessionId);
watch = new Stopwatch();
watch.start();
}
public int elapsed()
{
long elapsed = watch.elapsedTime(TimeUnit.MICROSECONDS);
return elapsed < Integer.MAX_VALUE ? (int) elapsed : Integer.MAX_VALUE;
}
public void trace(String format, Object arg)
{
trace(MessageFormatter.format(format, arg).getMessage());
}
public void trace(String format, Object arg1, Object arg2)
{
trace(MessageFormatter.format(format, arg1, arg2).getMessage());
}
public void trace(String format, Object[] args)
{
trace(MessageFormatter.arrayFormat(format, args).getMessage());
}
public void trace(String message)
{
TraceState.trace(sessionIdBytes, message, elapsed());
}
public static void trace(final ByteBuffer sessionIdBytes, final String message, final int elapsed)
{
final ByteBuffer eventId = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes());
final String threadName = Thread.currentThread().getName();
StageManager.getStage(Stage.TRACING).execute(new WrappedRunnable()
{
public void runMayThrow()
{
CFMetaData cfMeta = CFMetaData.TraceEventsCf;
ColumnFamily cf = ArrayBackedSortedColumns.factory.create(cfMeta);
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("activity")), message);
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("source")), FBUtilities.getBroadcastAddress());
if (elapsed >= 0)
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("source_elapsed")), elapsed);
Tracing.addColumn(cf, Tracing.buildName(cfMeta, eventId, ByteBufferUtil.bytes("activity")), message);
Tracing.mutateWithCatch(new RowMutation(Tracing.TRACE_KS, sessionIdBytes, cf));
}
});
}
}
|
remove unused 'threadName' var
|
src/java/org/apache/cassandra/tracing/TraceState.java
|
remove unused 'threadName' var
|
<ide><path>rc/java/org/apache/cassandra/tracing/TraceState.java
<ide> public static void trace(final ByteBuffer sessionIdBytes, final String message, final int elapsed)
<ide> {
<ide> final ByteBuffer eventId = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes());
<del> final String threadName = Thread.currentThread().getName();
<ide>
<ide> StageManager.getStage(Stage.TRACING).execute(new WrappedRunnable()
<ide> {
|
|
Java
|
apache-2.0
|
913778b37a076e963b84df483f5c77e72f62c6c6
| 0 |
uschindler/elasticsearch,gfyoung/elasticsearch,gfyoung/elasticsearch,robin13/elasticsearch,coding0011/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,uschindler/elasticsearch,HonzaKral/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,HonzaKral/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,coding0011/elasticsearch,coding0011/elasticsearch,GlenRSmith/elasticsearch,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,gingerwizard/elasticsearch
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.range;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class InternalRange<B extends InternalRange.Bucket, R extends InternalRange<B, R>> extends InternalMultiBucketAggregation<R, B>
implements Range {
static final Factory FACTORY = new Factory();
public static class Bucket extends InternalMultiBucketAggregation.InternalBucket implements Range.Bucket {
protected final transient boolean keyed;
protected final transient DocValueFormat format;
protected final double from;
protected final double to;
private final long docCount;
private final InternalAggregations aggregations;
private final String key;
public Bucket(String key, double from, double to, long docCount, InternalAggregations aggregations, boolean keyed,
DocValueFormat format) {
this.keyed = keyed;
this.format = format;
this.key = key != null ? key : generateKey(from, to, format);
this.from = from;
this.to = to;
this.docCount = docCount;
this.aggregations = aggregations;
}
@Override
public String getKey() {
return getKeyAsString();
}
@Override
public String getKeyAsString() {
return key;
}
@Override
public Object getFrom() {
return from;
}
@Override
public Object getTo() {
return to;
}
public boolean getKeyed() {
return keyed;
}
public DocValueFormat getFormat() {
return format;
}
@Override
public String getFromAsString() {
if (Double.isInfinite(from)) {
return null;
} else {
return format.format(from).toString();
}
}
@Override
public String getToAsString() {
if (Double.isInfinite(to)) {
return null;
} else {
return format.format(to).toString();
}
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
protected Factory<? extends Bucket, ?> getFactory() {
return FACTORY;
}
Bucket reduce(List<Bucket> ranges, ReduceContext context) {
long docCount = 0;
List<InternalAggregations> aggregationsList = new ArrayList<>(ranges.size());
for (Bucket range : ranges) {
docCount += range.docCount;
aggregationsList.add(range.aggregations);
}
final InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context);
return getFactory().createBucket(key, from, to, docCount, aggs, keyed, format);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (keyed) {
builder.startObject(key);
} else {
builder.startObject();
builder.field(CommonFields.KEY.getPreferredName(), key);
}
if (!Double.isInfinite(from)) {
builder.field(CommonFields.FROM.getPreferredName(), from);
if (format != DocValueFormat.RAW) {
builder.field(CommonFields.FROM_AS_STRING.getPreferredName(), format.format(from));
}
}
if (!Double.isInfinite(to)) {
builder.field(CommonFields.TO.getPreferredName(), to);
if (format != DocValueFormat.RAW) {
builder.field(CommonFields.TO_AS_STRING.getPreferredName(), format.format(to));
}
}
builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount);
aggregations.toXContentInternal(builder, params);
builder.endObject();
return builder;
}
private static String generateKey(double from, double to, DocValueFormat format) {
StringBuilder builder = new StringBuilder()
.append(Double.isInfinite(from) ? "*" : format.format(from))
.append("-")
.append(Double.isInfinite(to) ? "*" : format.format(to));
return builder.toString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getVersion().onOrAfter(Version.V_6_4_0)) {
out.writeString(key);
} else {
out.writeOptionalString(key);
}
out.writeDouble(from);
out.writeDouble(to);
out.writeVLong(docCount);
aggregations.writeTo(out);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Bucket that = (Bucket) other;
return Objects.equals(from, that.from)
&& Objects.equals(to, that.to)
&& Objects.equals(docCount, that.docCount)
&& Objects.equals(aggregations, that.aggregations)
&& Objects.equals(key, that.key);
}
@Override
public int hashCode() {
return Objects.hash(getClass(), from, to, docCount, aggregations, key);
}
}
public static class Factory<B extends Bucket, R extends InternalRange<B, R>> {
public ValuesSourceType getValueSourceType() {
return ValuesSourceType.NUMERIC;
}
public ValueType getValueType() {
return ValueType.NUMERIC;
}
@SuppressWarnings("unchecked")
public R create(String name, List<B> ranges, DocValueFormat format, boolean keyed, List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) {
return (R) new InternalRange<B, R>(name, ranges, format, keyed, pipelineAggregators, metaData);
}
@SuppressWarnings("unchecked")
public B createBucket(String key, double from, double to, long docCount, InternalAggregations aggregations, boolean keyed,
DocValueFormat format) {
return (B) new Bucket(key, from, to, docCount, aggregations, keyed, format);
}
@SuppressWarnings("unchecked")
public R create(List<B> ranges, R prototype) {
return (R) new InternalRange<B, R>(prototype.name, ranges, prototype.format, prototype.keyed, prototype.pipelineAggregators(),
prototype.metaData);
}
@SuppressWarnings("unchecked")
public B createBucket(InternalAggregations aggregations, B prototype) {
return (B) new Bucket(prototype.getKey(), prototype.from, prototype.to, prototype.getDocCount(), aggregations, prototype.keyed,
prototype.format);
}
}
private final List<B> ranges;
protected final DocValueFormat format;
protected final boolean keyed;
public InternalRange(String name, List<B> ranges, DocValueFormat format, boolean keyed,
List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) {
super(name, pipelineAggregators, metaData);
this.ranges = ranges;
this.format = format;
this.keyed = keyed;
}
/**
* Read from a stream.
*/
public InternalRange(StreamInput in) throws IOException {
super(in);
format = in.readNamedWriteable(DocValueFormat.class);
keyed = in.readBoolean();
int size = in.readVInt();
List<B> ranges = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String key = in.getVersion().onOrAfter(Version.V_6_4_0)
? in.readString()
: in.readOptionalString();
ranges.add(getFactory().createBucket(key, in.readDouble(), in.readDouble(), in.readVLong(),
InternalAggregations.readAggregations(in), keyed, format));
}
this.ranges = ranges;
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(format);
out.writeBoolean(keyed);
out.writeVInt(ranges.size());
for (B bucket : ranges) {
bucket.writeTo(out);
}
}
@Override
public String getWriteableName() {
return RangeAggregationBuilder.NAME;
}
@Override
public List<B> getBuckets() {
return ranges;
}
public Factory<B, R> getFactory() {
return FACTORY;
}
@SuppressWarnings("unchecked")
@Override
public R create(List<B> buckets) {
return getFactory().create(buckets, (R) this);
}
@Override
public B createBucket(InternalAggregations aggregations, B prototype) {
return getFactory().createBucket(aggregations, prototype);
}
@SuppressWarnings("unchecked")
@Override
public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
reduceContext.consumeBucketsAndMaybeBreak(ranges.size());
List<Bucket>[] rangeList = new List[ranges.size()];
for (int i = 0; i < rangeList.length; ++i) {
rangeList[i] = new ArrayList<>();
}
for (InternalAggregation aggregation : aggregations) {
InternalRange<B, R> ranges = (InternalRange<B, R>) aggregation;
int i = 0;
for (Bucket range : ranges.ranges) {
rangeList[i++].add(range);
}
}
final List<B> ranges = new ArrayList<>();
for (int i = 0; i < this.ranges.size(); ++i) {
ranges.add((B) rangeList[i].get(0).reduce(rangeList[i], reduceContext));
}
return getFactory().create(name, ranges, format, keyed, pipelineAggregators(), getMetaData());
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
if (keyed) {
builder.startObject(CommonFields.BUCKETS.getPreferredName());
} else {
builder.startArray(CommonFields.BUCKETS.getPreferredName());
}
for (B range : ranges) {
range.toXContent(builder, params);
}
if (keyed) {
builder.endObject();
} else {
builder.endArray();
}
return builder;
}
@Override
protected int doHashCode() {
return Objects.hash(ranges, format, keyed);
}
@Override
protected boolean doEquals(Object obj) {
InternalRange<?,?> that = (InternalRange<?,?>) obj;
return Objects.equals(ranges, that.ranges)
&& Objects.equals(format, that.format)
&& Objects.equals(keyed, that.keyed);
}
}
|
server/src/main/java/org/elasticsearch/search/aggregations/bucket/range/InternalRange.java
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.range;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class InternalRange<B extends InternalRange.Bucket, R extends InternalRange<B, R>> extends InternalMultiBucketAggregation<R, B>
implements Range {
static final Factory FACTORY = new Factory();
public static class Bucket extends InternalMultiBucketAggregation.InternalBucket implements Range.Bucket {
protected final transient boolean keyed;
protected final transient DocValueFormat format;
protected final double from;
protected final double to;
private final long docCount;
private final InternalAggregations aggregations;
private final String key;
public Bucket(String key, double from, double to, long docCount, InternalAggregations aggregations, boolean keyed,
DocValueFormat format) {
this.keyed = keyed;
this.format = format;
this.key = key != null ? key : generateKey(from, to, format);
this.from = from;
this.to = to;
this.docCount = docCount;
this.aggregations = aggregations;
}
@Override
public String getKey() {
return getKeyAsString();
}
@Override
public String getKeyAsString() {
return key;
}
@Override
public Object getFrom() {
return from;
}
@Override
public Object getTo() {
return to;
}
public boolean getKeyed() {
return keyed;
}
public DocValueFormat getFormat() {
return format;
}
@Override
public String getFromAsString() {
if (Double.isInfinite(from)) {
return null;
} else {
return format.format(from).toString();
}
}
@Override
public String getToAsString() {
if (Double.isInfinite(to)) {
return null;
} else {
return format.format(to).toString();
}
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
protected Factory<? extends Bucket, ?> getFactory() {
return FACTORY;
}
Bucket reduce(List<Bucket> ranges, ReduceContext context) {
long docCount = 0;
List<InternalAggregations> aggregationsList = new ArrayList<>(ranges.size());
for (Bucket range : ranges) {
docCount += range.docCount;
aggregationsList.add(range.aggregations);
}
final InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context);
return getFactory().createBucket(key, from, to, docCount, aggs, keyed, format);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (keyed) {
builder.startObject(key);
} else {
builder.startObject();
builder.field(CommonFields.KEY.getPreferredName(), key);
}
if (!Double.isInfinite(from)) {
builder.field(CommonFields.FROM.getPreferredName(), from);
if (format != DocValueFormat.RAW) {
builder.field(CommonFields.FROM_AS_STRING.getPreferredName(), format.format(from));
}
}
if (!Double.isInfinite(to)) {
builder.field(CommonFields.TO.getPreferredName(), to);
if (format != DocValueFormat.RAW) {
builder.field(CommonFields.TO_AS_STRING.getPreferredName(), format.format(to));
}
}
builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount);
aggregations.toXContentInternal(builder, params);
builder.endObject();
return builder;
}
private static String generateKey(double from, double to, DocValueFormat format) {
StringBuilder builder = new StringBuilder()
.append(Double.isInfinite(from) ? "*" : format.format(from))
.append("-")
.append(Double.isInfinite(to) ? "*" : format.format(to));
return builder.toString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getVersion().onOrAfter(Version.V_7_0_0_alpha1)) {
out.writeString(key);
} else {
out.writeOptionalString(key);
}
out.writeDouble(from);
out.writeDouble(to);
out.writeVLong(docCount);
aggregations.writeTo(out);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Bucket that = (Bucket) other;
return Objects.equals(from, that.from)
&& Objects.equals(to, that.to)
&& Objects.equals(docCount, that.docCount)
&& Objects.equals(aggregations, that.aggregations)
&& Objects.equals(key, that.key);
}
@Override
public int hashCode() {
return Objects.hash(getClass(), from, to, docCount, aggregations, key);
}
}
public static class Factory<B extends Bucket, R extends InternalRange<B, R>> {
public ValuesSourceType getValueSourceType() {
return ValuesSourceType.NUMERIC;
}
public ValueType getValueType() {
return ValueType.NUMERIC;
}
@SuppressWarnings("unchecked")
public R create(String name, List<B> ranges, DocValueFormat format, boolean keyed, List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) {
return (R) new InternalRange<B, R>(name, ranges, format, keyed, pipelineAggregators, metaData);
}
@SuppressWarnings("unchecked")
public B createBucket(String key, double from, double to, long docCount, InternalAggregations aggregations, boolean keyed,
DocValueFormat format) {
return (B) new Bucket(key, from, to, docCount, aggregations, keyed, format);
}
@SuppressWarnings("unchecked")
public R create(List<B> ranges, R prototype) {
return (R) new InternalRange<B, R>(prototype.name, ranges, prototype.format, prototype.keyed, prototype.pipelineAggregators(),
prototype.metaData);
}
@SuppressWarnings("unchecked")
public B createBucket(InternalAggregations aggregations, B prototype) {
return (B) new Bucket(prototype.getKey(), prototype.from, prototype.to, prototype.getDocCount(), aggregations, prototype.keyed,
prototype.format);
}
}
private final List<B> ranges;
protected final DocValueFormat format;
protected final boolean keyed;
public InternalRange(String name, List<B> ranges, DocValueFormat format, boolean keyed,
List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) {
super(name, pipelineAggregators, metaData);
this.ranges = ranges;
this.format = format;
this.keyed = keyed;
}
/**
* Read from a stream.
*/
public InternalRange(StreamInput in) throws IOException {
super(in);
format = in.readNamedWriteable(DocValueFormat.class);
keyed = in.readBoolean();
int size = in.readVInt();
List<B> ranges = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String key = in.getVersion().onOrAfter(Version.V_7_0_0_alpha1)
? in.readString()
: in.readOptionalString();
ranges.add(getFactory().createBucket(key, in.readDouble(), in.readDouble(), in.readVLong(),
InternalAggregations.readAggregations(in), keyed, format));
}
this.ranges = ranges;
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(format);
out.writeBoolean(keyed);
out.writeVInt(ranges.size());
for (B bucket : ranges) {
bucket.writeTo(out);
}
}
@Override
public String getWriteableName() {
return RangeAggregationBuilder.NAME;
}
@Override
public List<B> getBuckets() {
return ranges;
}
public Factory<B, R> getFactory() {
return FACTORY;
}
@SuppressWarnings("unchecked")
@Override
public R create(List<B> buckets) {
return getFactory().create(buckets, (R) this);
}
@Override
public B createBucket(InternalAggregations aggregations, B prototype) {
return getFactory().createBucket(aggregations, prototype);
}
@SuppressWarnings("unchecked")
@Override
public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
reduceContext.consumeBucketsAndMaybeBreak(ranges.size());
List<Bucket>[] rangeList = new List[ranges.size()];
for (int i = 0; i < rangeList.length; ++i) {
rangeList[i] = new ArrayList<>();
}
for (InternalAggregation aggregation : aggregations) {
InternalRange<B, R> ranges = (InternalRange<B, R>) aggregation;
int i = 0;
for (Bucket range : ranges.ranges) {
rangeList[i++].add(range);
}
}
final List<B> ranges = new ArrayList<>();
for (int i = 0; i < this.ranges.size(); ++i) {
ranges.add((B) rangeList[i].get(0).reduce(rangeList[i], reduceContext));
}
return getFactory().create(name, ranges, format, keyed, pipelineAggregators(), getMetaData());
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
if (keyed) {
builder.startObject(CommonFields.BUCKETS.getPreferredName());
} else {
builder.startArray(CommonFields.BUCKETS.getPreferredName());
}
for (B range : ranges) {
range.toXContent(builder, params);
}
if (keyed) {
builder.endObject();
} else {
builder.endArray();
}
return builder;
}
@Override
protected int doHashCode() {
return Objects.hash(ranges, format, keyed);
}
@Override
protected boolean doEquals(Object obj) {
InternalRange<?,?> that = (InternalRange<?,?>) obj;
return Objects.equals(ranges, that.ranges)
&& Objects.equals(format, that.format)
&& Objects.equals(keyed, that.keyed);
}
}
|
Update the version checks around range bucket keys, now that the change was backported.
|
server/src/main/java/org/elasticsearch/search/aggregations/bucket/range/InternalRange.java
|
Update the version checks around range bucket keys, now that the change was backported.
|
<ide><path>erver/src/main/java/org/elasticsearch/search/aggregations/bucket/range/InternalRange.java
<ide>
<ide> @Override
<ide> public void writeTo(StreamOutput out) throws IOException {
<del> if (out.getVersion().onOrAfter(Version.V_7_0_0_alpha1)) {
<add> if (out.getVersion().onOrAfter(Version.V_6_4_0)) {
<ide> out.writeString(key);
<ide> } else {
<ide> out.writeOptionalString(key);
<ide> int size = in.readVInt();
<ide> List<B> ranges = new ArrayList<>(size);
<ide> for (int i = 0; i < size; i++) {
<del> String key = in.getVersion().onOrAfter(Version.V_7_0_0_alpha1)
<add> String key = in.getVersion().onOrAfter(Version.V_6_4_0)
<ide> ? in.readString()
<ide> : in.readOptionalString();
<ide> ranges.add(getFactory().createBucket(key, in.readDouble(), in.readDouble(), in.readVLong(),
|
|
Java
|
agpl-3.0
|
330b151af6953d902130f9140efa63c9e964ab60
| 0 |
picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons
|
package picoded.jSql.db;
import java.lang.String;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.lang.RuntimeException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.StringWriter;
import java.util.logging.*;
import java.io.PrintWriter;
import java.util.concurrent.ExecutionException;
import picoded.jSql.JSqlType;
import picoded.jSql.JSqlResult;
import picoded.jSql.JSqlException;
import picoded.jSql.*;
import picoded.jSql.db.BaseInterface;
/// Pure SQL Server 2012 implentation of JSql
/// Support only for SQL Server 2012 and above version for the pagination query, the OFFSET / FETCH keywords
/// are used which are faster and better in performance in comparison of old ROW_NUMBER()
public class JSql_Mssql extends JSql implements BaseInterface {
/// Internal self used logger
private static Logger logger = Logger.getLogger(JSql_Mssql.class.getName());
/// Runs JSql with the JDBC sqlite engine
public JSql_Mssql(String dbUrl, String dbName, String dbUser, String dbPass) {
sqlType = JSqlType.mssql;
String connectionUrl = "jdbc:jtds:sqlserver://" + dbUrl;
if (dbName != null && dbName.length() > 0) {
connectionUrl = connectionUrl + ";DatabaseName=" + dbName + ";uselobs=false;"; //disable clobs
}
try {
Class.forName("net.sourceforge.jtds.jdbcx.JtdsDataSource"); //connection pooling
sqlConn = java.sql.DriverManager.getConnection(connectionUrl, dbUser, dbPass);
} catch (Exception e) {
throw new RuntimeException("Failed to load mssql connection: ", e);
}
}
// Internal parser that converts some of the common sql statements to mssql
public static String genericSqlParser(String inString) {
String fixedQuotes = inString.trim().replaceAll("(\\s){1}", " ").replaceAll("'", "\"").replaceAll("`", "\"");
String upperCaseStr = fixedQuotes.toUpperCase();
String qString = fixedQuotes;
String qStringPrefix = "";
String qStringSuffix = "";
final String ifExists = "IF EXISTS";
final String ifNotExists = "IF NOT EXISTS";
final String create = "CREATE";
final String drop = "DROP";
final String table = "TABLE";
final String select = "SELECT";
final String update = "UPDATE";
final String insertInto = "INSERT INTO";
final String deleteFrom = "DELETE FROM";
final String[] indexTypeArr = { "UNIQUE", "FULLTEXT", "SPATIAL" };
final String index = "INDEX";
String indexType;
String tmpStr;
int tmpIndx;
Pattern createIndexType = Pattern.compile("((UNIQUE|FULLTEXT|SPATIAL) ){0,1}INDEX.*");
int prefixOffset = 0;
if (upperCaseStr.startsWith(drop)) { //DROP
prefixOffset = drop.length() + 1;
if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE
prefixOffset += table.length() + 1;
if (upperCaseStr.startsWith(ifExists, prefixOffset)) { //IF EXISTS
prefixOffset += ifExists.length() + 1;
qStringPrefix = "BEGIN TRY IF OBJECT_ID('" + fixedQuotes.substring(prefixOffset).toUpperCase()
+ "', 'U')" + " IS NOT NULL DROP TABLE " + fixedQuotes.substring(prefixOffset)
+ " END TRY BEGIN CATCH END CATCH";
} else {
qStringPrefix = "DROP TABLE ";
}
qString = qStringPrefix;
} else if (upperCaseStr.startsWith(index, prefixOffset)) { //INDEX
}
} else if (upperCaseStr.startsWith(create)) { //CREATE
prefixOffset = create.length() + 1;
if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE
prefixOffset += table.length() + 1;
if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) { //IF NOT EXISTS
prefixOffset += ifNotExists.length() + 1;
//get the table name from incoming query
String tableName = getTableName(fixedQuotes.substring(prefixOffset));
qStringPrefix = "BEGIN TRY IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'" + tableName
+ "')" + " AND OBJECTPROPERTY(id, N'" + tableName + "')" + " = 1) CREATE TABLE ";
qStringSuffix = " END TRY BEGIN CATCH END CATCH";
} else {
qStringPrefix = "CREATE TABLE ";
}
qString = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset));
//qString = _simpleMysqlToOracle_collumnSubstitude(qString);
} else {
logger.finer("Trying to matched INDEX : " + upperCaseStr.substring(prefixOffset));
if (createIndexType.matcher(upperCaseStr.substring(prefixOffset)).matches()) { //UNIQUE|FULLTEXT|SPATIAL|_ INDEX
logger.finer("Matched INDEX : " + inString);
//Find the index type
indexType = null;
for (int a = 0; a < indexTypeArr.length; ++a) {
if (upperCaseStr.startsWith(indexTypeArr[a], prefixOffset)) {
prefixOffset += indexTypeArr[a].length() + 1;
indexType = indexTypeArr[a];
break;
}
}
//only bother if it matches (shd be right?)
if (upperCaseStr.startsWith(index, prefixOffset)) {
prefixOffset += index.length() + 1;
//If not exists wrapper
if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) {
prefixOffset += ifNotExists.length() + 1;
qStringPrefix = "";
qStringSuffix = "";
}
tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset));
tmpIndx = tmpStr.indexOf(" ON ");
if (tmpIndx > 0) {
qString = "BEGIN TRY CREATE " + ((indexType != null) ? indexType + " " : "") + "INDEX "
+ tmpStr.substring(0, tmpIndx) + " ON "
+ _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx + 4))
+ " END TRY BEGIN CATCH END CATCH";
}
}
}
}
} else if (upperCaseStr.startsWith(insertInto)) { //INSERT INTO
prefixOffset = insertInto.length() + 1;
tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset));
qString = "INSERT INTO " + tmpStr;
} else if (upperCaseStr.startsWith(select)) { //SELECT
prefixOffset = select.length() + 1;
tmpStr = qString.substring(prefixOffset);
tmpIndx = qString.toUpperCase().indexOf(" FROM ");
if (tmpIndx > 0) {
qString = "SELECT " + tmpStr.substring(0, tmpIndx - 7).replaceAll("\"", "'").replaceAll("`", "'")
+ " FROM " + _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx - 1));
} else {
qString = _fixTableNameInMssqlSubQuery(fixedQuotes);
}
prefixOffset = 0;
//Fix the "AS" quotation
while ((tmpIndx = qString.indexOf(" AS ", prefixOffset)) > 0) {
prefixOffset = qString.indexOf(" ", tmpIndx + 4);
if (prefixOffset > 0) {
qString = qString.substring(0, tmpIndx)
+ qString.substring(tmpIndx, prefixOffset).replaceAll("`", "\"").replaceAll("'", "\"")
+ qString.substring(prefixOffset);
} else {
break;
}
}
// Fix the pagination query as per the SQL Server 2012 syntax by using the OFFSET/FETCH
String prefixQuery = null;
int offsetIndex = qString.indexOf("OFFSET");
String offsetQuery = "";
if (offsetIndex != -1) {
prefixQuery = qString.substring(0, offsetIndex);
offsetQuery = qString.substring(offsetIndex);
offsetQuery += " ROWS ";
}
int limitIndex = qString.indexOf("LIMIT");
String limitQuery = "";
if (limitIndex != -1) {
prefixQuery = qString.substring(0, limitIndex);
if (offsetIndex != -1) {
limitQuery = qString.substring(limitIndex, offsetIndex);
} else {
limitQuery = qString.substring(limitIndex);
}
limitQuery = limitQuery.replace("LIMIT", "FETCH NEXT");
limitQuery += " ROWS ONLY ";
}
if (prefixQuery != null) {
qString = prefixQuery + offsetQuery + limitQuery;
}
} else if (upperCaseStr.startsWith(deleteFrom)) {
prefixOffset = deleteFrom.length() + 1;
tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset));
qString = deleteFrom + " " + tmpStr;
} else if (upperCaseStr.startsWith(update)) { //UPDATE
prefixOffset = update.length() + 1;
tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset));
qString = update + " " + tmpStr;
}
//Drop table query modication
if (qString.contains("DROP")) {
qString = qStringPrefix;
} else {
qString = qStringPrefix + qString + qStringSuffix;
}
//Convert MY-Sql NUMBER data type to NUMERIC data type for Ms-sql
if (qString.contains("CREATE TABLE") && qString.contains("NUMBER")) {
qString = qString.replaceAll("NUMBER", "NUMERIC");
}
//remove ON DELETE FOR CLIENTSTATUSHISTORY---> this block needs to be refined for future.
if (qString.contains("ON DELETE")) { //qString.contains("CLIENTSTATUSHISTORY") &&
qString = qString.replaceAll("ON DELETE SET NULL", "");
}
//logger.finer("Converting MySQL query to MsSql query");
logger.finer("MySql -> " + inString);
logger.finer("MsSql -> " + qString);
//logger.warning("MySql -> "+inString);
//logger.warning("OracleSql -> "+qString);
//System.out.println("[Query]: "+qString);
return qString; //no change of data
}
//Method to return table name from incoming query string
private static String getTableName(String qString) {
qString = qString.trim();
int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt;
String tableStr = qString.substring(0, indxPt).toUpperCase();
return tableStr; //retrun the table name
}
private static String _fixTableNameInMssqlSubQuery(String qString) {
qString = qString.trim();
int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt;
String tableStr = qString.substring(0, indxPt).toUpperCase();
qString = tableStr + qString.substring(indxPt);
while (qString.endsWith(";")) { //Remove uneeded trailing ";" semi collons
qString = qString.substring(0, qString.length() - 1);
}
return qString;
}
/// Executes the argumented query, and returns the result object *without*
/// fetching the result data from the database. (not fetching may not apply to all implementations)
///
/// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results
public JSqlResult executeQuery(String qString, Object... values) throws JSqlException {
return executeQuery_raw(genericSqlParser(qString), values);
}
/// Executes the argumented query, and immediately fetches the result from
/// the database into the result set.
///
/// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results
public JSqlResult query(String qString, Object... values) throws JSqlException {
return query_raw(genericSqlParser(qString), values);
}
/// Executes and dispose the sqliteResult object.
///
/// Returns false if no result is given by the execution call, else true on success
public boolean execute(String qString, Object... values) throws JSqlException {
return execute_raw(genericSqlParser(qString), values);
}
///
/// Helps generate an SQL UPSERT request. This function was created to acommedate the various
/// syntax differances of UPSERT across the various SQL vendors.
///
/// Note that care should be taken to prevent SQL injection via the given statment strings.
///
/// The syntax below, is an example of such an UPSERT statement for Oracle.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.SQL}
/// MERGE
/// INTO Employee AS destTable
/// USING (SELECT
/// 1 AS id, // Unique value
/// 'C3PO' AS name, // Insert value
/// COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer') AS role, // Values with default
/// (SELECT note FROM Employee WHERE id = 1) AS note // Misc values to preserve
/// ) AS sourceTable
/// ON (destTable.id = sourceTable.id)
/// WHEN MATCHED THEN
/// INSERT (
/// id, // Unique Columns to check for upsert
/// name, // Insert Columns to update
/// role, // Default Columns, that has default fallback value
/// note, // Misc Columns, which existing values are preserved (if exists)
/// ) VALUES (
/// 1, // Unique value
/// 'C3PO', // Insert value
/// COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer'), // Values with default
/// (SELECT note FROM Employee WHERE id = 1) // Misc values to preserve
/// )
/// WHEN NOT MATCHED THEN
/// UPDATE
/// SET name = 'C3PO', // Insert value
/// role = COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer'), // Values with default
/// note = (SELECT note FROM Employee WHERE id = 1) // Misc values to preserve
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
public JSqlQuerySet upsertQuerySet( //
String tableName, // Table name to upsert on
//
String[] uniqueColumns, // The unique column names
Object[] uniqueValues, // The row unique identifier values
//
String[] insertColumns, // Columns names to update
Object[] insertValues, // Values to update
//
String[] defaultColumns, // Columns names to apply default value, if not exists
Object[] defaultValues, // Values to insert, that is not updated. Note that this is ignored if pre-existing values exists
//
// Various column names where its existing value needs to be maintained (if any),
// this is important as some SQL implementation will fallback to default table values, if not properly handled
String[] miscColumns //
) throws JSqlException {
if (tableName.length() > 30) {
logger.warning(JSqlException.oracleNameSpaceWarning + tableName);
}
/// Checks that unique collumn and values length to be aligned
if (uniqueColumns == null || uniqueValues == null || uniqueColumns.length != uniqueValues.length) {
throw new JSqlException("Upsert query requires unique column and values to be equal length");
}
/// Preparing inner default select, this will be used repeatingly for COALESCE, DEFAULT and MISC values
ArrayList<Object> innerSelectArgs = new ArrayList<Object>();
StringBuilder innerSelectSB = new StringBuilder(" FROM ");
innerSelectSB.append("`" + tableName + "`");
innerSelectSB.append(" WHERE ");
for (int a = 0; a < uniqueColumns.length; ++a) {
if (a > 0) {
innerSelectSB.append(" AND ");
}
innerSelectSB.append(uniqueColumns[a] + " = ?");
innerSelectArgs.add(uniqueValues[a]);
}
innerSelectSB.append(")");
String innerSelectPrefix = "(SELECT ";
String innerSelectSuffix = innerSelectSB.toString();
String equalSign = "=";
String targetTableAlias = "target";
String sourceTableAlias = "source";
String statementTerminator = ";";
/// Building the query for INSERT OR REPLACE
StringBuilder queryBuilder = new StringBuilder("MERGE INTO `" + tableName + "` AS " + targetTableAlias);
ArrayList<Object> queryArgs = new ArrayList<Object>();
ArrayList<Object> insertQueryArgs = new ArrayList<Object>();
ArrayList<Object> updateQueryArgs = new ArrayList<Object>();
ArrayList<Object> selectQueryArgs = new ArrayList<Object>();
/// Building the query for both sides of '(...columns...) VALUE (...vars...)' clauses in upsert
/// Note that the final trailing ", " seperator will be removed prior to final query conversion
StringBuilder selectColumnNames = new StringBuilder();
StringBuilder updateColumnNames = new StringBuilder();
StringBuilder insertColumnNames = new StringBuilder();
StringBuilder insertColumnValues = new StringBuilder();
StringBuilder condition = new StringBuilder();
String columnSeperator = ", ";
/// Setting up unique values
for (int a = 0; a < uniqueColumns.length; ++a) {
// dual select
selectColumnNames.append("?");
selectColumnNames.append(" AS ");
selectColumnNames.append(uniqueColumns[a]);
selectColumnNames.append(columnSeperator);
selectQueryArgs.add(uniqueValues[a]);
// insert column list
insertColumnNames.append(uniqueColumns[a]);
insertColumnNames.append(columnSeperator);
// insert column value list
insertColumnValues.append("?");
insertColumnValues.append(columnSeperator);
//
insertQueryArgs.add(uniqueValues[a]);
}
/// Inserting updated values
if (insertColumns != null) {
for (int a = 0; a < insertColumns.length; ++a) {
// update column
updateColumnNames.append(insertColumns[a]);
updateColumnNames.append(equalSign);
updateColumnNames.append("?");
updateColumnNames.append(columnSeperator);
updateQueryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null);
// select dual
selectColumnNames.append("?");
selectColumnNames.append(" AS ");
selectColumnNames.append(insertColumns[a]);
selectColumnNames.append(columnSeperator);
selectQueryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null);
// insert column
insertColumnNames.append(insertColumns[a]);
insertColumnNames.append(columnSeperator);
insertColumnValues.append("?");
insertColumnValues.append(columnSeperator);
insertQueryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null);
}
}
/// Handling default values
if (defaultColumns != null) {
for (int a = 0; a < defaultColumns.length; ++a) {
// insert column
insertColumnNames.append(defaultColumns[a]);
insertColumnNames.append(columnSeperator);
insertColumnValues.append("COALESCE(");
insertColumnValues.append(innerSelectPrefix);
insertColumnValues.append(defaultColumns[a]);
insertColumnValues.append(innerSelectSuffix);
insertQueryArgs.addAll(innerSelectArgs);
insertColumnValues.append(", ?)");
insertColumnValues.append(columnSeperator);
insertQueryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null);
// update column
updateColumnNames.append(defaultColumns[a]);
updateColumnNames.append(equalSign);
updateColumnNames.append("COALESCE(");
updateColumnNames.append(innerSelectPrefix);
updateColumnNames.append(defaultColumns[a]);
updateColumnNames.append(innerSelectSuffix);
updateQueryArgs.addAll(innerSelectArgs);
updateColumnNames.append(", ?)");
updateColumnNames.append(columnSeperator);
updateQueryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null);
// select dual
// COALESCE((SELECT col3 from t where a=?), ?) as col3
selectColumnNames.append("COALESCE(");
selectColumnNames.append(innerSelectPrefix);
selectColumnNames.append(defaultColumns[a]);
selectColumnNames.append(innerSelectSuffix);
selectColumnNames.append(", ?)");
selectQueryArgs.addAll(innerSelectArgs);
selectColumnNames.append(" AS " + defaultColumns[a] + columnSeperator);
selectQueryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null);
}
}
/// Handling Misc values
if (miscColumns != null) {
for (int a = 0; a < miscColumns.length; ++a) {
// insert column
insertColumnNames.append(miscColumns[a]);
insertColumnNames.append(columnSeperator);
insertColumnValues.append(innerSelectPrefix);
insertColumnValues.append(miscColumns[a]);
insertColumnValues.append(innerSelectSuffix);
insertQueryArgs.addAll(innerSelectArgs);
insertColumnValues.append(columnSeperator);
// updtae column
updateColumnNames.append(miscColumns[a]);
updateColumnNames.append(equalSign);
updateColumnNames.append(innerSelectPrefix);
updateColumnNames.append(miscColumns[a]);
updateColumnNames.append(innerSelectSuffix);
updateColumnNames.append(columnSeperator);
updateQueryArgs.addAll(innerSelectArgs);
// select dual
selectColumnNames.append(innerSelectPrefix);
selectColumnNames.append(miscColumns[a]);
selectColumnNames.append(innerSelectSuffix);
selectColumnNames.append(" AS ");
selectColumnNames.append(miscColumns[a]);
selectColumnNames.append(columnSeperator);
selectQueryArgs.addAll(innerSelectArgs);
}
}
/// Setting up the condition
for (int a = 0; a < uniqueColumns.length; ++a) {
if (a > 0) {
condition.append(" and ");
}
condition.append(targetTableAlias);
condition.append(".");
condition.append(uniqueColumns[a]);
condition.append(equalSign);
condition.append(sourceTableAlias);
condition.append(".");
condition.append(uniqueColumns[a]);
}
/// Building the final query
queryBuilder.append(" USING (SELECT ");
queryBuilder.append(selectColumnNames.substring(0, selectColumnNames.length() - columnSeperator.length()));
queryBuilder.append(")");
queryBuilder.append(" AS ");
queryBuilder.append(sourceTableAlias);
queryBuilder.append(" ON ( ");
queryBuilder.append(condition.toString());
queryBuilder.append(" ) ");
queryBuilder.append(" WHEN MATCHED ");
queryBuilder.append(" THEN UPDATE SET ");
queryBuilder.append(updateColumnNames.substring(0, updateColumnNames.length() - columnSeperator.length()));
queryBuilder.append(" WHEN NOT MATCHED ");
queryBuilder.append(" THEN INSERT (");
queryBuilder.append(insertColumnNames.substring(0, insertColumnNames.length() - columnSeperator.length()));
queryBuilder.append(") VALUES (");
queryBuilder.append(insertColumnValues.substring(0, insertColumnValues.length() - columnSeperator.length()));
queryBuilder.append(")");
queryBuilder.append(statementTerminator);
queryArgs.addAll(selectQueryArgs);
queryArgs.addAll(updateQueryArgs);
queryArgs.addAll(insertQueryArgs);
//System.out.println("JSql -> upsertQuerySet -> query : " + queryBuilder.toString());
//System.out.println("JSql -> upsertQuerySet -> queryArgs : " + queryArgs);
return new JSqlQuerySet(queryBuilder.toString(), queryArgs.toArray(), this);
}
// Helper varient, without default or misc fields
public JSqlQuerySet upsertQuerySet( //
String tableName, // Table name to upsert on
//
String[] uniqueColumns, // The unique column names
Object[] uniqueValues, // The row unique identifier values
//
String[] insertColumns, // Columns names to update
Object[] insertValues // Values to update
) throws JSqlException {
return upsertQuerySet(tableName, uniqueColumns, uniqueValues, insertColumns, insertValues, null, null, null);
}
}
|
src/picoded/jSql/db/JSql_Mssql.java
|
package picoded.jSql.db;
import java.lang.String;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.lang.RuntimeException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.StringWriter;
import java.util.logging.*;
import java.io.PrintWriter;
import java.util.concurrent.ExecutionException;
import picoded.jSql.JSqlType;
import picoded.jSql.JSqlResult;
import picoded.jSql.JSqlException;
import picoded.jSql.*;
import picoded.jSql.db.BaseInterface;
/// Pure SQL Server 2012 implentation of JSql
/// Support only for SQL Server 2012 and above version for the pagination query, the OFFSET / FETCH keywords
/// are used which are faster and better in performance in comparison of old ROW_NUMBER()
public class JSql_Mssql extends JSql implements BaseInterface {
/// Internal self used logger
private static Logger logger = Logger.getLogger(JSql_Mssql.class.getName());
/// Runs JSql with the JDBC sqlite engine
public JSql_Mssql(String dbUrl, String dbName, String dbUser, String dbPass) {
sqlType = JSqlType.mssql;
String connectionUrl = "jdbc:jtds:sqlserver://" + dbUrl;
if (dbName != null && dbName.length() > 0) {
connectionUrl = connectionUrl + ";DatabaseName=" + dbName + ";uselobs=false;"; //disable clobs
}
try {
Class.forName("net.sourceforge.jtds.jdbcx.JtdsDataSource"); //connection pooling
sqlConn = java.sql.DriverManager.getConnection(connectionUrl, dbUser, dbPass);
} catch (Exception e) {
throw new RuntimeException("Failed to load mssql connection: ", e);
}
}
// Internal parser that converts some of the common sql statements to mssql
public static String genericSqlParser(String inString) {
String fixedQuotes = inString.trim().replaceAll("(\\s){1}", " ").replaceAll("'", "\"").replaceAll("`", "\"");
String upperCaseStr = fixedQuotes.toUpperCase();
String qString = fixedQuotes;
String qStringPrefix = "";
String qStringSuffix = "";
final String ifExists = "IF EXISTS";
final String ifNotExists = "IF NOT EXISTS";
final String create = "CREATE";
final String drop = "DROP";
final String table = "TABLE";
final String select = "SELECT";
final String update = "UPDATE";
final String insertInto = "INSERT INTO";
final String deleteFrom = "DELETE FROM";
final String[] indexTypeArr = { "UNIQUE", "FULLTEXT", "SPATIAL" };
final String index = "INDEX";
String indexType;
String tmpStr;
int tmpIndx;
Pattern createIndexType = Pattern.compile("((UNIQUE|FULLTEXT|SPATIAL) ){0,1}INDEX.*");
int prefixOffset = 0;
if (upperCaseStr.startsWith(drop)) { //DROP
prefixOffset = drop.length() + 1;
if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE
prefixOffset += table.length() + 1;
if (upperCaseStr.startsWith(ifExists, prefixOffset)) { //IF EXISTS
prefixOffset += ifExists.length() + 1;
qStringPrefix = "BEGIN TRY IF OBJECT_ID('" + fixedQuotes.substring(prefixOffset).toUpperCase()
+ "', 'U')" + " IS NOT NULL DROP TABLE " + fixedQuotes.substring(prefixOffset)
+ " END TRY BEGIN CATCH END CATCH";
} else {
qStringPrefix = "DROP TABLE ";
}
qString = qStringPrefix;
} else if (upperCaseStr.startsWith(index, prefixOffset)) { //INDEX
}
} else if (upperCaseStr.startsWith(create)) { //CREATE
prefixOffset = create.length() + 1;
if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE
prefixOffset += table.length() + 1;
if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) { //IF NOT EXISTS
prefixOffset += ifNotExists.length() + 1;
//get the table name from incoming query
String tableName = getTableName(fixedQuotes.substring(prefixOffset));
qStringPrefix = "BEGIN TRY IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'" + tableName
+ "')" + " AND OBJECTPROPERTY(id, N'" + tableName + "')" + " = 1) CREATE TABLE ";
qStringSuffix = " END TRY BEGIN CATCH END CATCH";
} else {
qStringPrefix = "CREATE TABLE ";
}
qString = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset));
//qString = _simpleMysqlToOracle_collumnSubstitude(qString);
} else {
logger.finer("Trying to matched INDEX : " + upperCaseStr.substring(prefixOffset));
if (createIndexType.matcher(upperCaseStr.substring(prefixOffset)).matches()) { //UNIQUE|FULLTEXT|SPATIAL|_ INDEX
logger.finer("Matched INDEX : " + inString);
//Find the index type
indexType = null;
for (int a = 0; a < indexTypeArr.length; ++a) {
if (upperCaseStr.startsWith(indexTypeArr[a], prefixOffset)) {
prefixOffset += indexTypeArr[a].length() + 1;
indexType = indexTypeArr[a];
break;
}
}
//only bother if it matches (shd be right?)
if (upperCaseStr.startsWith(index, prefixOffset)) {
prefixOffset += index.length() + 1;
//If not exists wrapper
if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) {
prefixOffset += ifNotExists.length() + 1;
qStringPrefix = "";
qStringSuffix = "";
}
tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset));
tmpIndx = tmpStr.indexOf(" ON ");
if (tmpIndx > 0) {
qString = "BEGIN TRY CREATE " + ((indexType != null) ? indexType + " " : "") + "INDEX "
+ tmpStr.substring(0, tmpIndx) + " ON "
+ _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx + 4))
+ " END TRY BEGIN CATCH END CATCH";
}
}
}
}
} else if (upperCaseStr.startsWith(insertInto)) { //INSERT INTO
prefixOffset = insertInto.length() + 1;
tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset));
qString = "INSERT INTO " + tmpStr;
} else if (upperCaseStr.startsWith(select)) { //SELECT
prefixOffset = select.length() + 1;
tmpStr = qString.substring(prefixOffset);
tmpIndx = qString.toUpperCase().indexOf(" FROM ");
if (tmpIndx > 0) {
qString = "SELECT " + tmpStr.substring(0, tmpIndx - 7).replaceAll("\"", "'").replaceAll("`", "'")
+ " FROM " + _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx - 1));
} else {
qString = _fixTableNameInMssqlSubQuery(fixedQuotes);
}
prefixOffset = 0;
//Fix the "AS" quotation
while ((tmpIndx = qString.indexOf(" AS ", prefixOffset)) > 0) {
prefixOffset = qString.indexOf(" ", tmpIndx + 4);
if (prefixOffset > 0) {
qString = qString.substring(0, tmpIndx)
+ qString.substring(tmpIndx, prefixOffset).replaceAll("`", "\"").replaceAll("'", "\"")
+ qString.substring(prefixOffset);
} else {
break;
}
}
// Fix the pagination query as per the SQL Server 2012 syntax by using the OFFSET/FETCH
String prefixQuery = null;
int offsetIndex = qString.indexOf("OFFSET");
String offsetQuery = "";
if (offsetIndex != -1) {
prefixQuery = qString.substring(0, offsetIndex);
offsetQuery = qString.substring(offsetIndex);
offsetQuery += " ROWS ";
}
int limitIndex = qString.indexOf("LIMIT");
String limitQuery = "";
if (limitIndex != -1) {
prefixQuery = qString.substring(0, limitIndex);
if (offsetIndex != -1) {
limitQuery = qString.substring(limitIndex, offsetIndex);
} else {
limitQuery = qString.substring(limitIndex);
}
limitQuery = limitQuery.replace("LIMIT", "FETCH NEXT");
limitQuery += " ROWS ONLY ";
}
if (prefixQuery != null) {
qString = prefixQuery + offsetQuery + limitQuery;
}
} else if (upperCaseStr.startsWith(deleteFrom)) {
prefixOffset = deleteFrom.length() + 1;
tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset));
qString = deleteFrom + " " + tmpStr;
} else if (upperCaseStr.startsWith(update)) { //UPDATE
prefixOffset = update.length() + 1;
tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset));
qString = update + " " + tmpStr;
}
//Drop table query modication
if (qString.contains("DROP")) {
qString = qStringPrefix;
} else {
qString = qStringPrefix + qString + qStringSuffix;
}
//Convert MY-Sql NUMBER data type to NUMERIC data type for Ms-sql
if (qString.contains("CREATE TABLE") && qString.contains("NUMBER")) {
qString = qString.replaceAll("NUMBER", "NUMERIC");
}
//remove ON DELETE FOR CLIENTSTATUSHISTORY---> this block needs to be refined for future.
if (qString.contains("ON DELETE")) { //qString.contains("CLIENTSTATUSHISTORY") &&
qString = qString.replaceAll("ON DELETE SET NULL", "");
}
//logger.finer("Converting MySQL query to MsSql query");
logger.finer("MySql -> " + inString);
logger.finer("MsSql -> " + qString);
//logger.warning("MySql -> "+inString);
//logger.warning("OracleSql -> "+qString);
//System.out.println("[Query]: "+qString);
return qString; //no change of data
}
//Method to return table name from incoming query string
private static String getTableName(String qString) {
qString = qString.trim();
int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt;
String tableStr = qString.substring(0, indxPt).toUpperCase();
return tableStr; //retrun the table name
}
private static String _fixTableNameInMssqlSubQuery(String qString) {
qString = qString.trim();
int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt;
String tableStr = qString.substring(0, indxPt).toUpperCase();
qString = tableStr + qString.substring(indxPt);
while (qString.endsWith(";")) { //Remove uneeded trailing ";" semi collons
qString = qString.substring(0, qString.length() - 1);
}
return qString;
}
/// Executes the argumented query, and returns the result object *without*
/// fetching the result data from the database. (not fetching may not apply to all implementations)
///
/// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results
public JSqlResult executeQuery(String qString, Object... values) throws JSqlException {
return executeQuery_raw(genericSqlParser(qString), values);
}
/// Executes the argumented query, and immediately fetches the result from
/// the database into the result set.
///
/// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results
public JSqlResult query(String qString, Object... values) throws JSqlException {
return query_raw(genericSqlParser(qString), values);
}
/// Executes and dispose the sqliteResult object.
///
/// Returns false if no result is given by the execution call, else true on success
public boolean execute(String qString, Object... values) throws JSqlException {
return execute_raw(genericSqlParser(qString), values);
}
///
/// Helps generate an SQL UPSERT request. This function was created to acommedate the various
/// syntax differances of UPSERT across the various SQL vendors.
///
/// Note that care should be taken to prevent SQL injection via the given statment strings.
///
/// The syntax below, is an example of such an UPSERT statement for Oracle.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.SQL}
/// MERGE
/// INTO destTable d
/// USING (
/// SELECT *
/// FROM sourceTable
/// ) s
/// ON (s.id = d.id)
/// WHEN MATCHED THEN
/// INSERT (id, destCol1, destCol2)
/// VALUES (id, sourceCol1, sourceCol2)
/// WHEN NOT MATCHED THEN
/// UPDATE
/// SET destCol1 = sourceCol1,
/// destCol2 = sourceCol2
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
public JSqlQuerySet upsertQuerySet( //
String tableName, // Table name to upsert on
//
String[] uniqueColumns, // The unique column names
Object[] uniqueValues, // The row unique identifier values
//
String[] insertColumns, // Columns names to update
Object[] insertValues, // Values to update
//
String[] defaultColumns, // Columns names to apply default value, if not exists
Object[] defaultValues, // Values to insert, that is not updated. Note that this is ignored if pre-existing values exists
//
// Various column names where its existing value needs to be maintained (if any),
// this is important as some SQL implementation will fallback to default table values, if not properly handled
String[] miscColumns //
) throws JSqlException {
if (tableName.length() > 30) {
logger.warning(JSqlException.oracleNameSpaceWarning + tableName);
}
/// Checks that unique collumn and values length to be aligned
if (uniqueColumns == null || uniqueValues == null || uniqueColumns.length != uniqueValues.length) {
throw new JSqlException("Upsert query requires unique column and values to be equal length");
}
/// Preparing inner default select, this will be used repeatingly for COALESCE, DEFAULT and MISC values
ArrayList<Object> innerSelectArgs = new ArrayList<Object>();
StringBuilder innerSelectSB = new StringBuilder(" FROM ");
innerSelectSB.append("`" + tableName + "`");
innerSelectSB.append(" WHERE ");
for (int a = 0; a < uniqueColumns.length; ++a) {
if (a > 0) {
innerSelectSB.append(" AND ");
}
innerSelectSB.append(uniqueColumns[a] + " = ?");
innerSelectArgs.add(uniqueValues[a]);
}
innerSelectSB.append(")");
String innerSelectPrefix = "(SELECT ";
String innerSelectSuffix = innerSelectSB.toString();
String equalSign = "=";
String targetTableAlias = "target";
String sourceTableAlias = "source";
String statementTerminator = ";";
/// Building the query for INSERT OR REPLACE
StringBuilder queryBuilder = new StringBuilder("MERGE INTO `" + tableName + "` AS " + targetTableAlias);
ArrayList<Object> queryArgs = new ArrayList<Object>();
ArrayList<Object> insertQueryArgs = new ArrayList<Object>();
ArrayList<Object> updateQueryArgs = new ArrayList<Object>();
ArrayList<Object> selectQueryArgs = new ArrayList<Object>();
/// Building the query for both sides of '(...columns...) VALUE (...vars...)' clauses in upsert
/// Note that the final trailing ", " seperator will be removed prior to final query conversion
StringBuilder selectColumnNames = new StringBuilder();
StringBuilder updateColumnNames = new StringBuilder();
StringBuilder insertColumnNames = new StringBuilder();
StringBuilder insertColumnValues = new StringBuilder();
StringBuilder condition = new StringBuilder();
String columnSeperator = ", ";
/// Setting up unique values
for (int a = 0; a < uniqueColumns.length; ++a) {
// dual select
selectColumnNames.append("?");
selectColumnNames.append(" AS ");
selectColumnNames.append(uniqueColumns[a]);
selectColumnNames.append(columnSeperator);
selectQueryArgs.add(uniqueValues[a]);
// insert column list
insertColumnNames.append(uniqueColumns[a]);
insertColumnNames.append(columnSeperator);
// insert column value list
insertColumnValues.append("?");
insertColumnValues.append(columnSeperator);
//
insertQueryArgs.add(uniqueValues[a]);
}
/// Inserting updated values
if (insertColumns != null) {
for (int a = 0; a < insertColumns.length; ++a) {
// update column
updateColumnNames.append(insertColumns[a]);
updateColumnNames.append(equalSign);
updateColumnNames.append("?");
updateColumnNames.append(columnSeperator);
updateQueryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null);
// select dual
selectColumnNames.append("?");
selectColumnNames.append(" AS ");
selectColumnNames.append(insertColumns[a]);
selectColumnNames.append(columnSeperator);
selectQueryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null);
// insert column
insertColumnNames.append(insertColumns[a]);
insertColumnNames.append(columnSeperator);
insertColumnValues.append("?");
insertColumnValues.append(columnSeperator);
insertQueryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null);
}
}
/// Handling default values
if (defaultColumns != null) {
for (int a = 0; a < defaultColumns.length; ++a) {
// insert column
insertColumnNames.append(defaultColumns[a]);
insertColumnNames.append(columnSeperator);
insertColumnValues.append("COALESCE(");
insertColumnValues.append(innerSelectPrefix);
insertColumnValues.append(defaultColumns[a]);
insertColumnValues.append(innerSelectSuffix);
insertQueryArgs.addAll(innerSelectArgs);
insertColumnValues.append(", ?)");
insertColumnValues.append(columnSeperator);
insertQueryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null);
// update column
updateColumnNames.append(defaultColumns[a]);
updateColumnNames.append(equalSign);
updateColumnNames.append("COALESCE(");
updateColumnNames.append(innerSelectPrefix);
updateColumnNames.append(defaultColumns[a]);
updateColumnNames.append(innerSelectSuffix);
updateQueryArgs.addAll(innerSelectArgs);
updateColumnNames.append(", ?)");
updateColumnNames.append(columnSeperator);
updateQueryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null);
// select dual
// COALESCE((SELECT col3 from t where a=?), ?) as col3
selectColumnNames.append("COALESCE(");
selectColumnNames.append(innerSelectPrefix);
selectColumnNames.append(defaultColumns[a]);
selectColumnNames.append(innerSelectSuffix);
selectColumnNames.append(", ?)");
selectQueryArgs.addAll(innerSelectArgs);
selectColumnNames.append(" AS " + defaultColumns[a] + columnSeperator);
selectQueryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null);
}
}
/// Handling Misc values
if (miscColumns != null) {
for (int a = 0; a < miscColumns.length; ++a) {
// insert column
insertColumnNames.append(miscColumns[a]);
insertColumnNames.append(columnSeperator);
insertColumnValues.append(innerSelectPrefix);
insertColumnValues.append(miscColumns[a]);
insertColumnValues.append(innerSelectSuffix);
insertQueryArgs.addAll(innerSelectArgs);
insertColumnValues.append(columnSeperator);
// updtae column
updateColumnNames.append(miscColumns[a]);
updateColumnNames.append(equalSign);
updateColumnNames.append(innerSelectPrefix);
updateColumnNames.append(miscColumns[a]);
updateColumnNames.append(innerSelectSuffix);
updateColumnNames.append(columnSeperator);
updateQueryArgs.addAll(innerSelectArgs);
// select dual
selectColumnNames.append(innerSelectPrefix);
selectColumnNames.append(miscColumns[a]);
selectColumnNames.append(innerSelectSuffix);
selectColumnNames.append(" AS ");
selectColumnNames.append(miscColumns[a]);
selectColumnNames.append(columnSeperator);
selectQueryArgs.addAll(innerSelectArgs);
}
}
/// Setting up the condition
for (int a = 0; a < uniqueColumns.length; ++a) {
if (a > 0) {
condition.append(" and ");
}
condition.append(targetTableAlias);
condition.append(".");
condition.append(uniqueColumns[a]);
condition.append(equalSign);
condition.append(sourceTableAlias);
condition.append(".");
condition.append(uniqueColumns[a]);
}
/// Building the final query
queryBuilder.append(" USING (SELECT ");
queryBuilder.append(selectColumnNames.substring(0, selectColumnNames.length() - columnSeperator.length()));
queryBuilder.append(")");
queryBuilder.append(" AS ");
queryBuilder.append(sourceTableAlias);
queryBuilder.append(" ON ( ");
queryBuilder.append(condition.toString());
queryBuilder.append(" ) ");
queryBuilder.append(" WHEN MATCHED ");
queryBuilder.append(" THEN UPDATE SET ");
queryBuilder.append(updateColumnNames.substring(0, updateColumnNames.length() - columnSeperator.length()));
queryBuilder.append(" WHEN NOT MATCHED ");
queryBuilder.append(" THEN INSERT (");
queryBuilder.append(insertColumnNames.substring(0, insertColumnNames.length() - columnSeperator.length()));
queryBuilder.append(") VALUES (");
queryBuilder.append(insertColumnValues.substring(0, insertColumnValues.length() - columnSeperator.length()));
queryBuilder.append(")");
queryBuilder.append(statementTerminator);
queryArgs.addAll(selectQueryArgs);
queryArgs.addAll(updateQueryArgs);
queryArgs.addAll(insertQueryArgs);
//System.out.println("JSql -> upsertQuerySet -> query : " + queryBuilder.toString());
//System.out.println("JSql -> upsertQuerySet -> queryArgs : " + queryArgs);
return new JSqlQuerySet(queryBuilder.toString(), queryArgs.toArray(), this);
}
// Helper varient, without default or misc fields
public JSqlQuerySet upsertQuerySet( //
String tableName, // Table name to upsert on
//
String[] uniqueColumns, // The unique column names
Object[] uniqueValues, // The row unique identifier values
//
String[] insertColumns, // Columns names to update
Object[] insertValues // Values to update
) throws JSqlException {
return upsertQuerySet(tableName, uniqueColumns, uniqueValues, insertColumns, insertValues, null, null, null);
}
}
|
source beautification
|
src/picoded/jSql/db/JSql_Mssql.java
|
source beautification
|
<ide><path>rc/picoded/jSql/db/JSql_Mssql.java
<ide> ///
<ide> /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.SQL}
<ide> /// MERGE
<del> /// INTO destTable d
<del> /// USING (
<del> /// SELECT *
<del> /// FROM sourceTable
<del> /// ) s
<del> /// ON (s.id = d.id)
<add> /// INTO Employee AS destTable
<add> /// USING (SELECT
<add> /// 1 AS id, // Unique value
<add> /// 'C3PO' AS name, // Insert value
<add> /// COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer') AS role, // Values with default
<add> /// (SELECT note FROM Employee WHERE id = 1) AS note // Misc values to preserve
<add> /// ) AS sourceTable
<add> /// ON (destTable.id = sourceTable.id)
<ide> /// WHEN MATCHED THEN
<del> /// INSERT (id, destCol1, destCol2)
<del> /// VALUES (id, sourceCol1, sourceCol2)
<add> /// INSERT (
<add> /// id, // Unique Columns to check for upsert
<add> /// name, // Insert Columns to update
<add> /// role, // Default Columns, that has default fallback value
<add> /// note, // Misc Columns, which existing values are preserved (if exists)
<add> /// ) VALUES (
<add> /// 1, // Unique value
<add> /// 'C3PO', // Insert value
<add> /// COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer'), // Values with default
<add> /// (SELECT note FROM Employee WHERE id = 1) // Misc values to preserve
<add> /// )
<ide> /// WHEN NOT MATCHED THEN
<ide> /// UPDATE
<del> /// SET destCol1 = sourceCol1,
<del> /// destCol2 = sourceCol2
<add> /// SET name = 'C3PO', // Insert value
<add> /// role = COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer'), // Values with default
<add> /// note = (SELECT note FROM Employee WHERE id = 1) // Misc values to preserve
<ide> /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<ide> ///
<ide> public JSqlQuerySet upsertQuerySet( //
|
|
Java
|
apache-2.0
|
4389080392477538fc9e50f9712a69e8e8c5bd46
| 0 |
cfieber/clouddriver,ajordens/clouddriver,duftler/clouddriver,cfieber/clouddriver,duftler/clouddriver,ajordens/clouddriver,cfieber/clouddriver,duftler/clouddriver,spinnaker/clouddriver,ajordens/clouddriver,spinnaker/clouddriver,spinnaker/clouddriver,ajordens/clouddriver,duftler/clouddriver
|
/*
* Copyright 2017 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.frigga.Names;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import com.netflix.spinnaker.moniker.Moniker;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Slf4j
public class KubernetesManifestAnnotater {
private static final String SPINNAKER_ANNOTATION = "spinnaker.io";
private static final String RELATIONSHIP_ANNOTATION_PREFIX = "relationships." + SPINNAKER_ANNOTATION;
private static final String ARTIFACT_ANNOTATION_PREFIX = "artifact." + SPINNAKER_ANNOTATION;
private static final String MONIKER_ANNOTATION_PREFIX = "moniker." + SPINNAKER_ANNOTATION;
private static final String LOAD_BALANCERS = RELATIONSHIP_ANNOTATION_PREFIX + "/loadBalancers";
private static final String SECURITY_GROUPS = RELATIONSHIP_ANNOTATION_PREFIX + "/securityGroups";
private static final String CLUSTER = MONIKER_ANNOTATION_PREFIX + "/cluster";
private static final String APPLICATION = MONIKER_ANNOTATION_PREFIX + "/application";
private static final String STACK = MONIKER_ANNOTATION_PREFIX + "/stack";
private static final String DETAIL = MONIKER_ANNOTATION_PREFIX + "/detail";
private static final String TYPE = ARTIFACT_ANNOTATION_PREFIX + "/type";
private static final String NAME = ARTIFACT_ANNOTATION_PREFIX + "/name";
private static final String LOCATION = ARTIFACT_ANNOTATION_PREFIX + "/location";
private static final String VERSION = ARTIFACT_ANNOTATION_PREFIX + "/version";
private static final String KUBERNETES_ANNOTATION = "kubernetes.io";
private static final String DEPLOYMENT_ANNOTATION_PREFIX = "deployment." + KUBERNETES_ANNOTATION;
private static final String DEPLOYMENT_REVISION = DEPLOYMENT_ANNOTATION_PREFIX + "/revision";
private static ObjectMapper objectMapper = new ObjectMapper();
private static void storeAnnotation(Map<String, String> annotations, String key, Object value) {
if (value == null) {
return;
}
try {
annotations.put(key, objectMapper.writeValueAsString(value));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Illegal annotation value for '" + key + "': " + e);
}
}
private static <T> T getAnnotation(Map<String, String> annotations, String key, TypeReference<T> typeReference) {
return getAnnotation(annotations, key, typeReference, null);
}
private static <T> T getAnnotation(Map<String, String> annotations, String key, TypeReference<T> typeReference, T defaultValue) {
String value = annotations.get(key);
if (value == null) {
return defaultValue;
}
try {
return objectMapper.readValue(value, typeReference);
} catch (IOException e) {
throw new IllegalArgumentException("Illegally annotated resource for '" + key + "': " + e);
}
}
public static void annotateManifest(KubernetesManifest manifest, KubernetesManifestSpinnakerRelationships relationships) {
Map<String, String> annotations = manifest.getAnnotations();
storeAnnotations(annotations, relationships);
manifest.getSpecTemplateAnnotations().flatMap(a -> {
storeAnnotations(a, relationships);
return Optional.empty();
});
}
public static void annotateManifest(KubernetesManifest manifest, Moniker moniker) {
Map<String, String> annotations = manifest.getAnnotations();
storeAnnotations(annotations, moniker);
manifest.getSpecTemplateAnnotations().flatMap(a -> {
storeAnnotations(a, moniker);
return Optional.empty();
});
}
public static void annotateManifest(KubernetesManifest manifest, Artifact artifact) {
Map<String, String> annotations = manifest.getAnnotations();
storeAnnotations(annotations, artifact);
manifest.getSpecTemplateAnnotations().flatMap(a -> {
storeAnnotations(a, artifact);
return Optional.empty();
});
}
private static void storeAnnotations(Map<String, String> annotations, Moniker moniker) {
if (moniker == null) {
throw new IllegalArgumentException("Every resource deployed via spinnaker must be assigned a moniker");
}
storeAnnotation(annotations, CLUSTER, moniker.getCluster());
storeAnnotation(annotations, APPLICATION, moniker.getApp());
storeAnnotation(annotations, STACK, moniker.getStack());
storeAnnotation(annotations, DETAIL, moniker.getDetail());
}
private static void storeAnnotations(Map<String, String> annotations, KubernetesManifestSpinnakerRelationships relationships) {
if (relationships == null) {
return;
}
storeAnnotation(annotations, LOAD_BALANCERS, relationships.getLoadBalancers());
storeAnnotation(annotations, SECURITY_GROUPS, relationships.getSecurityGroups());
}
private static void storeAnnotations(Map<String, String> annotations, Artifact artifact) {
if (artifact == null) {
return;
}
storeAnnotation(annotations, TYPE, artifact.getType());
storeAnnotation(annotations, NAME, artifact.getName());
storeAnnotation(annotations, LOCATION, artifact.getLocation());
storeAnnotation(annotations, VERSION, artifact.getVersion());
}
public static KubernetesManifestSpinnakerRelationships getManifestRelationships(KubernetesManifest manifest) {
Map<String, String> annotations = manifest.getAnnotations();
return new KubernetesManifestSpinnakerRelationships()
.setLoadBalancers(getAnnotation(annotations, LOAD_BALANCERS, new TypeReference<List<String>>() {}))
.setSecurityGroups(getAnnotation(annotations, SECURITY_GROUPS, new TypeReference<List<String>>() {}));
}
public static Artifact getArtifact(KubernetesManifest manifest) {
Map<String, String> annotations = manifest.getAnnotations();
return Artifact.builder()
.type(getAnnotation(annotations, TYPE, new TypeReference<String>() {}))
.name(getAnnotation(annotations, NAME, new TypeReference<String>() {}))
.location(getAnnotation(annotations, LOCATION, new TypeReference<String>() {}))
.version(getAnnotation(annotations, VERSION, new TypeReference<String>() {}))
.build();
}
public static Moniker getMoniker(KubernetesManifest manifest) {
Names parsed = Names.parseName(manifest.getName());
Map<String, String> annotations = manifest.getAnnotations();
return Moniker.builder()
.cluster(getAnnotation(annotations, CLUSTER, new TypeReference<String>() {}, parsed.getCluster()))
.app(getAnnotation(annotations, APPLICATION, new TypeReference<String>() {}, parsed.getApp()))
.stack(getAnnotation(annotations, STACK, new TypeReference<String>() {}, parsed.getStack()))
.detail(getAnnotation(annotations, DETAIL, new TypeReference<String>() {}, parsed.getDetail()))
.sequence(getAnnotation(annotations, DEPLOYMENT_REVISION, new TypeReference<Integer>() {}, parsed.getSequence()))
.build();
}
}
|
clouddriver-kubernetes/src/main/groovy/com/netflix/spinnaker/clouddriver/kubernetes/v2/description/manifest/KubernetesManifestAnnotater.java
|
/*
* Copyright 2017 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import com.netflix.spinnaker.moniker.Moniker;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Slf4j
public class KubernetesManifestAnnotater {
private static final String SPINNAKER_ANNOTATION = "spinnaker.io";
private static final String RELATIONSHIP_ANNOTATION_PREFIX = "relationships." + SPINNAKER_ANNOTATION;
private static final String ARTIFACT_ANNOTATION_PREFIX = "artifact." + SPINNAKER_ANNOTATION;
private static final String MONIKER_ANNOTATION_PREFIX = "moniker." + SPINNAKER_ANNOTATION;
private static final String LOAD_BALANCERS = RELATIONSHIP_ANNOTATION_PREFIX + "/loadBalancers";
private static final String SECURITY_GROUPS = RELATIONSHIP_ANNOTATION_PREFIX + "/securityGroups";
private static final String CLUSTER = MONIKER_ANNOTATION_PREFIX + "/cluster";
private static final String APPLICATION = MONIKER_ANNOTATION_PREFIX + "/application";
private static final String STACK = MONIKER_ANNOTATION_PREFIX + "/stack";
private static final String DETAIL = MONIKER_ANNOTATION_PREFIX + "/detail";
private static final String TYPE = ARTIFACT_ANNOTATION_PREFIX + "/type";
private static final String NAME = ARTIFACT_ANNOTATION_PREFIX + "/name";
private static final String LOCATION = ARTIFACT_ANNOTATION_PREFIX + "/location";
private static final String VERSION = ARTIFACT_ANNOTATION_PREFIX + "/version";
private static final String KUBERNETES_ANNOTATION = "kubernetes.io";
private static final String DEPLOYMENT_ANNOTATION_PREFIX = "deployment." + KUBERNETES_ANNOTATION;
private static final String DEPLOYMENT_REVISION = DEPLOYMENT_ANNOTATION_PREFIX + "/revision";
private static ObjectMapper objectMapper = new ObjectMapper();
private static void storeAnnotation(Map<String, String> annotations, String key, Object value) {
if (value == null) {
return;
}
try {
annotations.put(key, objectMapper.writeValueAsString(value));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Illegal annotation value for '" + key + "': " + e);
}
}
private static <T> T getAnnotation(Map<String, String> annotations, String key, TypeReference<T> typeReference) {
String value = annotations.get(key);
if (value == null) {
return null;
}
try {
return objectMapper.readValue(value, typeReference);
} catch (IOException e) {
throw new IllegalArgumentException("Illegally annotated resource for '" + key + "': " + e);
}
}
public static void annotateManifest(KubernetesManifest manifest, KubernetesManifestSpinnakerRelationships relationships) {
Map<String, String> annotations = manifest.getAnnotations();
storeAnnotations(annotations, relationships);
manifest.getSpecTemplateAnnotations().flatMap(a -> {
storeAnnotations(a, relationships);
return Optional.empty();
});
}
public static void annotateManifest(KubernetesManifest manifest, Moniker moniker) {
Map<String, String> annotations = manifest.getAnnotations();
storeAnnotations(annotations, moniker);
manifest.getSpecTemplateAnnotations().flatMap(a -> {
storeAnnotations(a, moniker);
return Optional.empty();
});
}
public static void annotateManifest(KubernetesManifest manifest, Artifact artifact) {
Map<String, String> annotations = manifest.getAnnotations();
storeAnnotations(annotations, artifact);
manifest.getSpecTemplateAnnotations().flatMap(a -> {
storeAnnotations(a, artifact);
return Optional.empty();
});
}
private static void storeAnnotations(Map<String, String> annotations, Moniker moniker) {
if (moniker == null) {
throw new IllegalArgumentException("Every resource deployed via spinnaker must be assigned a moniker");
}
storeAnnotation(annotations, CLUSTER, moniker.getCluster());
storeAnnotation(annotations, APPLICATION, moniker.getApp());
storeAnnotation(annotations, STACK, moniker.getStack());
storeAnnotation(annotations, DETAIL, moniker.getDetail());
}
private static void storeAnnotations(Map<String, String> annotations, KubernetesManifestSpinnakerRelationships relationships) {
if (relationships == null) {
return;
}
storeAnnotation(annotations, LOAD_BALANCERS, relationships.getLoadBalancers());
storeAnnotation(annotations, SECURITY_GROUPS, relationships.getSecurityGroups());
}
private static void storeAnnotations(Map<String, String> annotations, Artifact artifact) {
if (artifact == null) {
return;
}
storeAnnotation(annotations, TYPE, artifact.getType());
storeAnnotation(annotations, NAME, artifact.getName());
storeAnnotation(annotations, LOCATION, artifact.getLocation());
storeAnnotation(annotations, VERSION, artifact.getVersion());
}
public static KubernetesManifestSpinnakerRelationships getManifestRelationships(KubernetesManifest manifest) {
Map<String, String> annotations = manifest.getAnnotations();
return new KubernetesManifestSpinnakerRelationships()
.setLoadBalancers(getAnnotation(annotations, LOAD_BALANCERS, new TypeReference<List<String>>() {}))
.setSecurityGroups(getAnnotation(annotations, SECURITY_GROUPS, new TypeReference<List<String>>() {}));
}
public static Artifact getArtifact(KubernetesManifest manifest) {
Map<String, String> annotations = manifest.getAnnotations();
return Artifact.builder()
.type(getAnnotation(annotations, TYPE, new TypeReference<String>() {}))
.name(getAnnotation(annotations, NAME, new TypeReference<String>() {}))
.location(getAnnotation(annotations, LOCATION, new TypeReference<String>() {}))
.version(getAnnotation(annotations, VERSION, new TypeReference<String>() {}))
.build();
}
public static Moniker getMoniker(KubernetesManifest manifest) {
Map<String, String> annotations = manifest.getAnnotations();
return Moniker.builder()
.cluster(getAnnotation(annotations, CLUSTER, new TypeReference<String>() {}))
.app(getAnnotation(annotations, APPLICATION, new TypeReference<String>() {}))
.stack(getAnnotation(annotations, STACK, new TypeReference<String>() {}))
.detail(getAnnotation(annotations, DETAIL, new TypeReference<String>() {}))
.sequence(getAnnotation(annotations, DEPLOYMENT_REVISION, new TypeReference<Integer>() {}))
.build();
}
}
|
feat(provider/kubernetes): default to frigga (#2156)
|
clouddriver-kubernetes/src/main/groovy/com/netflix/spinnaker/clouddriver/kubernetes/v2/description/manifest/KubernetesManifestAnnotater.java
|
feat(provider/kubernetes): default to frigga (#2156)
|
<ide><path>louddriver-kubernetes/src/main/groovy/com/netflix/spinnaker/clouddriver/kubernetes/v2/description/manifest/KubernetesManifestAnnotater.java
<ide> import com.fasterxml.jackson.core.JsonProcessingException;
<ide> import com.fasterxml.jackson.core.type.TypeReference;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<add>import com.netflix.frigga.Names;
<ide> import com.netflix.spinnaker.kork.artifacts.model.Artifact;
<ide> import com.netflix.spinnaker.moniker.Moniker;
<ide> import lombok.extern.slf4j.Slf4j;
<ide> }
<ide>
<ide> private static <T> T getAnnotation(Map<String, String> annotations, String key, TypeReference<T> typeReference) {
<add> return getAnnotation(annotations, key, typeReference, null);
<add> }
<add>
<add> private static <T> T getAnnotation(Map<String, String> annotations, String key, TypeReference<T> typeReference, T defaultValue) {
<ide> String value = annotations.get(key);
<ide> if (value == null) {
<del> return null;
<add> return defaultValue;
<ide> }
<ide>
<ide> try {
<ide> }
<ide>
<ide> public static Moniker getMoniker(KubernetesManifest manifest) {
<add> Names parsed = Names.parseName(manifest.getName());
<ide> Map<String, String> annotations = manifest.getAnnotations();
<ide>
<ide> return Moniker.builder()
<del> .cluster(getAnnotation(annotations, CLUSTER, new TypeReference<String>() {}))
<del> .app(getAnnotation(annotations, APPLICATION, new TypeReference<String>() {}))
<del> .stack(getAnnotation(annotations, STACK, new TypeReference<String>() {}))
<del> .detail(getAnnotation(annotations, DETAIL, new TypeReference<String>() {}))
<del> .sequence(getAnnotation(annotations, DEPLOYMENT_REVISION, new TypeReference<Integer>() {}))
<add> .cluster(getAnnotation(annotations, CLUSTER, new TypeReference<String>() {}, parsed.getCluster()))
<add> .app(getAnnotation(annotations, APPLICATION, new TypeReference<String>() {}, parsed.getApp()))
<add> .stack(getAnnotation(annotations, STACK, new TypeReference<String>() {}, parsed.getStack()))
<add> .detail(getAnnotation(annotations, DETAIL, new TypeReference<String>() {}, parsed.getDetail()))
<add> .sequence(getAnnotation(annotations, DEPLOYMENT_REVISION, new TypeReference<Integer>() {}, parsed.getSequence()))
<ide> .build();
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
10478c8e8ffff4cec8b27dd37e3ebe2dd37ed4f9
| 0 |
tremes/deltaspike,rafabene/deltaspike,apache/deltaspike,chkal/deltaspike,rafabene/deltaspike,jharting/deltaspike,tremes/deltaspike,subaochen/deltaspike,apache/deltaspike,idontgotit/deltaspike,subaochen/deltaspike,chkal/deltaspike,subaochen/deltaspike,os890/DeltaSpikePlayground,tremes/deltaspike,os890/deltaspike-vote,os890/DS_Discuss,danielsoro/deltaspike,os890/DeltaSpikePlayground,LightGuard/incubator-deltaspike,os890/DS_Discuss,Danny02/deltaspike,mlachat/deltaspike,idontgotit/deltaspike,rdicroce/deltaspike,os890/deltaspike-vote,rdicroce/deltaspike,idontgotit/deltaspike,apache/deltaspike,tremes/deltaspike,jharting/deltaspike,danielsoro/deltaspike,idontgotit/deltaspike,Danny02/deltaspike,struberg/deltaspike,os890/deltaspike-vote,os890/DS_Discuss,Danny02/deltaspike,subaochen/deltaspike,rafabene/deltaspike,struberg/deltaspike,rdicroce/deltaspike,os890/DS_Discuss,os890/DeltaSpikePlayground,mlachat/deltaspike,LightGuard/incubator-deltaspike,chkal/deltaspike,apache/deltaspike,mlachat/deltaspike,danielsoro/deltaspike,danielsoro/deltaspike,chkal/deltaspike,LightGuard/incubator-deltaspike,Danny02/deltaspike,struberg/deltaspike,jharting/deltaspike,mlachat/deltaspike,rdicroce/deltaspike,struberg/deltaspike,os890/deltaspike-vote
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.deltaspike.jsf.impl.exception;
import java.lang.annotation.Annotation;
import java.util.Iterator;
import javax.enterprise.inject.spi.BeanManager;
import javax.faces.FacesException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import org.apache.deltaspike.core.api.exception.control.event.ExceptionToCatchEvent;
import org.apache.deltaspike.core.api.provider.BeanManagerProvider;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.apache.deltaspike.core.spi.activation.Deactivatable;
import org.apache.deltaspike.core.util.ClassDeactivationUtils;
import org.apache.deltaspike.core.util.metadata.AnnotationInstanceProvider;
import org.apache.deltaspike.jsf.api.config.JsfModuleConfig;
public class DeltaSpikeExceptionHandler extends ExceptionHandlerWrapper implements Deactivatable
{
private final ExceptionHandler wrapped;
private volatile Boolean initialized;
private Annotation exceptionQualifier;
private boolean isActivated = true;
public DeltaSpikeExceptionHandler(ExceptionHandler wrapped)
{
this.isActivated = ClassDeactivationUtils.isActivated(getClass());
this.wrapped = wrapped;
}
@Override
public ExceptionHandler getWrapped()
{
return wrapped;
}
@Override
public void handle() throws FacesException
{
if (isActivated)
{
init();
FacesContext context = FacesContext.getCurrentInstance();
if (context.getResponseComplete())
{
return;
}
Iterable<ExceptionQueuedEvent> exceptionQueuedEvents = getUnhandledExceptionQueuedEvents();
if (exceptionQueuedEvents != null && exceptionQueuedEvents.iterator() != null)
{
Iterator<ExceptionQueuedEvent> iterator = exceptionQueuedEvents.iterator();
BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
while (iterator.hasNext())
{
Throwable throwable = iterator.next().getContext().getException();
Throwable rootCause = getRootCause(throwable);
ExceptionToCatchEvent event = new ExceptionToCatchEvent(rootCause, exceptionQualifier);
beanManager.fireEvent(event);
if (event.isHandled())
{
iterator.remove();
}
// a handle method might redirect and set responseComplete
if (context.getResponseComplete())
{
break;
}
}
}
}
super.handle();
}
private synchronized void init()
{
if (this.initialized == null)
{
this.exceptionQualifier = AnnotationInstanceProvider.of(
BeanProvider.getContextualReference(JsfModuleConfig.class).getExceptionQualifier());
this.initialized = true;
}
}
}
|
deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/exception/DeltaSpikeExceptionHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.deltaspike.jsf.impl.exception;
import java.lang.annotation.Annotation;
import java.util.Iterator;
import javax.enterprise.inject.spi.BeanManager;
import javax.faces.FacesException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import org.apache.deltaspike.core.api.exception.control.event.ExceptionToCatchEvent;
import org.apache.deltaspike.core.api.provider.BeanManagerProvider;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.apache.deltaspike.core.spi.activation.Deactivatable;
import org.apache.deltaspike.core.util.ClassDeactivationUtils;
import org.apache.deltaspike.core.util.metadata.AnnotationInstanceProvider;
import org.apache.deltaspike.jsf.api.config.JsfModuleConfig;
public class DeltaSpikeExceptionHandler extends ExceptionHandlerWrapper implements Deactivatable
{
private final ExceptionHandler wrapped;
private final Annotation exceptionQualifier;
private boolean isActivated = true;
public DeltaSpikeExceptionHandler(ExceptionHandler wrapped)
{
this.isActivated = ClassDeactivationUtils.isActivated(getClass());
this.wrapped = wrapped;
this.exceptionQualifier = AnnotationInstanceProvider.of(
BeanProvider.getContextualReference(JsfModuleConfig.class).getExceptionQualifier());
}
@Override
public ExceptionHandler getWrapped()
{
return wrapped;
}
@Override
public void handle() throws FacesException
{
if (isActivated)
{
FacesContext context = FacesContext.getCurrentInstance();
if (context.getResponseComplete())
{
return;
}
Iterable<ExceptionQueuedEvent> exceptionQueuedEvents = getUnhandledExceptionQueuedEvents();
if (exceptionQueuedEvents != null && exceptionQueuedEvents.iterator() != null)
{
Iterator<ExceptionQueuedEvent> iterator = exceptionQueuedEvents.iterator();
BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
while (iterator.hasNext())
{
Throwable throwable = iterator.next().getContext().getException();
Throwable rootCause = getRootCause(throwable);
ExceptionToCatchEvent event = new ExceptionToCatchEvent(rootCause, exceptionQualifier);
beanManager.fireEvent(event);
if (event.isHandled())
{
iterator.remove();
}
// a handle method might redirect and set responseComplete
if (context.getResponseComplete())
{
break;
}
}
}
}
super.handle();
}
}
|
DELTASPIKE-529 fixed initialization in non-EE environment
|
deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/exception/DeltaSpikeExceptionHandler.java
|
DELTASPIKE-529 fixed initialization in non-EE environment
|
<ide><path>eltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/exception/DeltaSpikeExceptionHandler.java
<ide> public class DeltaSpikeExceptionHandler extends ExceptionHandlerWrapper implements Deactivatable
<ide> {
<ide> private final ExceptionHandler wrapped;
<del> private final Annotation exceptionQualifier;
<ide>
<add> private volatile Boolean initialized;
<add>
<add> private Annotation exceptionQualifier;
<ide> private boolean isActivated = true;
<ide>
<ide> public DeltaSpikeExceptionHandler(ExceptionHandler wrapped)
<ide> {
<ide> this.isActivated = ClassDeactivationUtils.isActivated(getClass());
<ide> this.wrapped = wrapped;
<del> this.exceptionQualifier = AnnotationInstanceProvider.of(
<del> BeanProvider.getContextualReference(JsfModuleConfig.class).getExceptionQualifier());
<ide> }
<ide>
<ide> @Override
<ide> {
<ide> if (isActivated)
<ide> {
<add> init();
<add>
<ide> FacesContext context = FacesContext.getCurrentInstance();
<ide>
<ide> if (context.getResponseComplete())
<ide>
<ide> super.handle();
<ide> }
<add>
<add> private synchronized void init()
<add> {
<add> if (this.initialized == null)
<add> {
<add> this.exceptionQualifier = AnnotationInstanceProvider.of(
<add> BeanProvider.getContextualReference(JsfModuleConfig.class).getExceptionQualifier());
<add>
<add> this.initialized = true;
<add> }
<add> }
<ide> }
|
|
Java
|
apache-2.0
|
9bbbd8c89b256fe9095e0a9839c4d290d6d563e6
| 0 |
scalio/storypath,scalio/storypath,n8fr8/storypath,StoryMaker/storypath,StoryMaker/storypath,n8fr8/storypath,scalio/storypath,StoryMaker/storypath,n8fr8/storypath
|
package scal.io.liger;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.android.vending.expansion.zipfile.ZipResourceFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import scal.io.liger.model.ExpansionIndexItem;
import scal.io.liger.model.InstanceIndexItem;
import scal.io.liger.model.QueueItem;
import scal.io.liger.model.StoryPath;
import scal.io.liger.model.StoryPathLibrary;
/**
* Created by mnbogner on 11/24/14.
*/
public class QueueManager {
//public static long NO_MANAGER = -123;
public static Long DUPLICATE_QUERY = Long.valueOf(0);
private static String downloadQueueName = "download_queue.json";
public static long queueTimeout = Long.MAX_VALUE; // user-configurable? setting to max value, will revisit later
// caching to avoid file collision issues (cache should ensure correct data is read/written)
public static HashMap<Long, QueueItem> cachedQueue = new HashMap<Long, QueueItem>();
public static ArrayList<String> cachedQueries = new ArrayList<String>();
// need some sort of solution to prevent multiple simultaneous checks from all looking and all finding nothing
public static synchronized Long checkQueue(Context context, File queueFile) {
return checkQueue(context, queueFile.getName());
}
public static synchronized Long checkQueue(Context context, String queueFile) {
loadQueue(context); // fills cached queue
if (cachedQueries.contains(queueFile)) {
Log.d("QUEUE", "QUEUE ITEM IS " + queueFile + " BUT SOMEONE IS ALREADY LOOKING FOR THAT");
return DUPLICATE_QUERY;
} else {
Log.d("QUEUE", "ADDING CACHED QUERY FOR " + queueFile);
cachedQueries.add(queueFile);
}
for (Long queueId : cachedQueue.keySet()) {
Log.d("QUEUE", "QUEUE ITEM IS " + cachedQueue.get(queueId).getQueueFile() + " LOOKING FOR " + queueFile);
if (queueFile.equals(cachedQueue.get(queueId).getQueueFile())) {
Log.d("QUEUE", "QUEUE ITEM FOR " + queueFile + " FOUND WITH ID " + queueId + " REMOVING CACHED QUERY ");
cachedQueries.remove(queueFile);
return queueId;
}
}
Log.d("QUEUE", "QUEUE ITEM FOR " + queueFile + " NOT FOUND");
return null;
}
public static synchronized void checkQueueFinished(Context context, File queueFile) {
checkQueueFinished(context, queueFile.getName());
}
public static synchronized void checkQueueFinished(Context context, String queueFile) {
Log.d("QUEUE", "LOOKING FOR CACHED QUERY FOR " + queueFile);
// done checking queue for item, remove temp item
if (cachedQueries.contains(queueFile)) {
Log.d("QUEUE", "REMOVING CACHED QUERY FOR " + queueFile);
cachedQueries.remove(queueFile);
}
}
public static synchronized HashMap<Long, QueueItem> loadQueue(Context context) {
if (cachedQueue.size() > 0) {
return cachedQueue;
}
String queueJson = null;
String jsonFilePath = ZipHelper.getFileFolderName(context);
//Log.d("QUEUE", "READING JSON FILE " + jsonFilePath + downloadQueueName + " FROM SD CARD");
File jsonFile = new File(jsonFilePath + downloadQueueName);
if (!jsonFile.exists()) {
Log.e("QUEUE", jsonFilePath + downloadQueueName + " WAS NOT FOUND");
return cachedQueue;
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(jsonFile);
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonStream = null;
queueJson = new String(buffer);
} catch (IOException ioe) {
Log.e("QUEUE", "READING JSON FILE " + jsonFilePath + downloadQueueName + " FROM SD CARD FAILED");
return cachedQueue;
}
} else {
Log.e("QUEUE", "SD CARD WAS NOT FOUND");
return cachedQueue;
}
if ((queueJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
// trying to account for issues with old queue files
try {
cachedQueue = gson.fromJson(queueJson, new TypeToken<HashMap<Long, QueueItem>>() {
}.getType());
} catch (Exception ise) {
// this will hopefully catch existing Long/String queue files
Log.d("QUEUE", "JSON QUEUE FILE APPEARS CORRUPT, PURGING FILE, RETURNING EMPTY QUEUE");
if (jsonFile.exists()) {
jsonFile.delete();
}
cachedQueue = new HashMap<Long, QueueItem>();
}
}
return cachedQueue;
}
// unused
/*
public static long checkQueue(String fileName, HashMap<Long, QueueItem> queueMap) {
for (Long queueNumber : queueMap.keySet()) {
if (queueMap.get(queueNumber).getQueueFile().contains(fileName)) {
return queueNumber.longValue();
}
}
return -1;
}
*/
public static synchronized void addToQueue(Context context, Long queueId, String queueFile) {
if (cachedQueue.size() == 0) {
cachedQueue = loadQueue(context);
}
QueueItem queueItem = new QueueItem(queueFile, new Date());
cachedQueue.put(queueId, queueItem);
// we have an actual entry for the item now, remove temp item
if (cachedQueries.contains(queueFile)) {
Log.d("QUEUE", "REMOVING CACHED QUERY FOR " + queueFile);
cachedQueries.remove(queueFile);
}
Log.d("QUEUE", "PUT " + queueId + " IN QUEUE, NEW QUEUE " + cachedQueue.keySet().toString());
saveQueue(context, cachedQueue, downloadQueueName);
return;
}
public static synchronized boolean removeFromQueue(Context context, Long queueId) {
if (cachedQueue.size() == 0) {
cachedQueue = loadQueue(context);
}
if (cachedQueue.keySet().contains(queueId)) {
QueueItem removedItem = cachedQueue.remove(queueId);
// check for cached queries
checkQueueFinished(context, removedItem.getQueueFile());
Log.d("QUEUE", "REMOVED " + queueId + " FROM QUEUE, NEW QUEUE " + cachedQueue.keySet().toString());
saveQueue(context, cachedQueue, downloadQueueName);
return true;
} else{
return false;
}
}
// unused
/*
public static synchronized boolean purgeFromQueue(Context context, Long queueId) {
HashMap<Long, QueueItem> queueMap = loadQueue(context);
if (queueMap.keySet().contains(queueId)) {
String fileToPurge = queueMap.get(queueId).getQueueFile();
fileToPurge = fileToPurge.substring(fileToPurge.lastIndexOf(File.separator) + 1, fileToPurge.lastIndexOf("."));
Log.d("QUEUE", "REMOVING " + queueId + " AND PURGING ALL OTHER QUEUE ITEMS FOR " + fileToPurge);
queueMap.remove(queueId);
for (Long queueNumber : queueMap.keySet()) {
if (queueMap.get(queueNumber).getQueueFile().contains(fileToPurge)) {
queueMap.remove(queueNumber);
Log.d("QUEUE", "REMOVED " + queueNumber + " FROM QUEUE, NEW QUEUE " + queueMap.keySet().toString());
}
}
saveQueue(context, queueMap, downloadQueueName);
return true;
} else{
return false;
}
}
*/
private static synchronized void saveQueue(Context context, HashMap<Long, QueueItem> queueMap, String jsonFileName) {
String queueJson = "";
String jsonFilePath = ZipHelper.getFileFolderName(context);
//Log.d("QUEUE", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD");
File jsonFile = new File(jsonFilePath + jsonFileName + ".tmp"); // write to temp and rename
if (jsonFile.exists()) {
jsonFile.delete();
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
jsonFile.createNewFile();
FileOutputStream jsonStream = new FileOutputStream(jsonFile);
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
queueJson = gson.toJson(queueMap);
byte[] buffer = queueJson.getBytes();
jsonStream.write(buffer);
jsonStream.flush();
jsonStream.close();
jsonStream = null;
Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + jsonFileName + ".tmp " + jsonFilePath + jsonFileName);
} catch (IOException ioe) {
Log.e("QUEUE", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD FAILED");
return;
}
} else {
Log.e("QUEUE", "SD CARD WAS NOT FOUND");
return;
}
}
}
|
lib/src/main/java/scal/io/liger/QueueManager.java
|
package scal.io.liger;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.android.vending.expansion.zipfile.ZipResourceFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import scal.io.liger.model.ExpansionIndexItem;
import scal.io.liger.model.InstanceIndexItem;
import scal.io.liger.model.QueueItem;
import scal.io.liger.model.StoryPath;
import scal.io.liger.model.StoryPathLibrary;
/**
* Created by mnbogner on 11/24/14.
*/
public class QueueManager {
//public static long NO_MANAGER = -123;
public static Long DUPLICATE_QUERY = Long.valueOf(0);
private static String downloadQueueName = "download_queue.json";
public static long queueTimeout = Long.MAX_VALUE; // user-configurable? setting to max value, will revisit later
// caching to avoid file collision issues (cache should ensure correct data is read/written)
public static HashMap<Long, QueueItem> cachedQueue = new HashMap<Long, QueueItem>();
public static ArrayList<String> cachedQueries = new ArrayList<String>();
// need some sort of solution to prevent multiple simultaneous checks from all looking and all finding nothing
public static synchronized Long checkQueue(Context context, File queueFile) {
return checkQueue(context, queueFile.getName());
}
public static synchronized Long checkQueue(Context context, String queueFile) {
loadQueue(context); // fills cached queue
if (cachedQueries.contains(queueFile)) {
Log.d("QUEUE", "QUEUE ITEM IS " + queueFile + " BUT SOMEONE IS ALREADY LOOKING FOR THAT");
return DUPLICATE_QUERY;
} else {
Log.d("QUEUE", "ADDING CACHED QUERY FOR " + queueFile);
cachedQueries.add(queueFile);
}
for (Long queueId : cachedQueue.keySet()) {
Log.d("QUEUE", "QUEUE ITEM IS " + cachedQueue.get(queueId).getQueueFile() + " LOOKING FOR " + queueFile);
if (queueFile.equals(cachedQueue.get(queueId).getQueueFile())) {
Log.d("QUEUE", "QUEUE ITEM FOR " + queueFile + " FOUND WITH ID " + queueId + " REMOVING CACHED QUERY ");
cachedQueries.remove(queueFile);
return queueId;
}
}
Log.d("QUEUE", "QUEUE ITEM FOR " + queueFile + " NOT FOUND");
return null;
}
public static synchronized void checkQueueFinished(Context context, File queueFile) {
checkQueueFinished(context, queueFile.getName());
}
public static synchronized void checkQueueFinished(Context context, String queueFile) {
Log.d("QUEUE", "LOOKING FOR CACHED QUERY FOR " + queueFile);
// done checking queue for item, remove temp item
if (cachedQueries.contains(queueFile)) {
Log.d("QUEUE", "REMOVING CACHED QUERY FOR " + queueFile);
cachedQueries.remove(queueFile);
}
}
public static synchronized HashMap<Long, QueueItem> loadQueue(Context context) {
if (cachedQueue.size() > 0) {
return cachedQueue;
}
String queueJson = null;
String jsonFilePath = ZipHelper.getFileFolderName(context);
//Log.d("QUEUE", "READING JSON FILE " + jsonFilePath + downloadQueueName + " FROM SD CARD");
File jsonFile = new File(jsonFilePath + downloadQueueName);
if (!jsonFile.exists()) {
Log.e("QUEUE", jsonFilePath + downloadQueueName + " WAS NOT FOUND");
return cachedQueue;
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
InputStream jsonStream = new FileInputStream(jsonFile);
int size = jsonStream.available();
byte[] buffer = new byte[size];
jsonStream.read(buffer);
jsonStream.close();
jsonStream = null;
queueJson = new String(buffer);
} catch (IOException ioe) {
Log.e("QUEUE", "READING JSON FILE " + jsonFilePath + downloadQueueName + " FROM SD CARD FAILED");
return cachedQueue;
}
} else {
Log.e("QUEUE", "SD CARD WAS NOT FOUND");
return cachedQueue;
}
if ((queueJson != null) && (queueJson.length() > 0)) {
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
// trying to account for issues with old queue files
try {
cachedQueue = gson.fromJson(queueJson, new TypeToken<HashMap<Long, QueueItem>>() {
}.getType());
} catch (Exception ise) {
// this will hopefully catch existing Long/String queue files
Log.d("QUEUE", "JSON QUEUE FILE APPEARS CORRUPT, PURGING FILE, RETURNING EMPTY QUEUE");
if (jsonFile.exists()) {
jsonFile.delete();
}
cachedQueue = new HashMap<Long, QueueItem>();
}
}
return cachedQueue;
}
// unused
/*
public static long checkQueue(String fileName, HashMap<Long, QueueItem> queueMap) {
for (Long queueNumber : queueMap.keySet()) {
if (queueMap.get(queueNumber).getQueueFile().contains(fileName)) {
return queueNumber.longValue();
}
}
return -1;
}
*/
public static synchronized void addToQueue(Context context, Long queueId, String queueFile) {
if (cachedQueue.size() == 0) {
cachedQueue = loadQueue(context);
}
QueueItem queueItem = new QueueItem(queueFile, new Date());
cachedQueue.put(queueId, queueItem);
// we have an actual entry for the item now, remove temp item
if (cachedQueries.contains(queueFile)) {
Log.d("QUEUE", "REMOVING CACHED QUERY FOR " + queueFile);
cachedQueries.remove(queueFile);
}
Log.d("QUEUE", "PUT " + queueId + " IN QUEUE, NEW QUEUE " + cachedQueue.keySet().toString());
saveQueue(context, cachedQueue, downloadQueueName);
return;
}
public static synchronized boolean removeFromQueue(Context context, Long queueId) {
if (cachedQueue.size() == 0) {
cachedQueue = loadQueue(context);
}
if (cachedQueue.keySet().contains(queueId)) {
QueueItem removedItem = cachedQueue.remove(queueId);
// check for cached queries
checkQueueFinished(context, removedItem.getQueueFile());
Log.d("QUEUE", "REMOVED " + queueId + " FROM QUEUE, NEW QUEUE " + cachedQueue.keySet().toString());
saveQueue(context, cachedQueue, downloadQueueName);
return true;
} else{
return false;
}
}
// unused
/*
public static synchronized boolean purgeFromQueue(Context context, Long queueId) {
HashMap<Long, QueueItem> queueMap = loadQueue(context);
if (queueMap.keySet().contains(queueId)) {
String fileToPurge = queueMap.get(queueId).getQueueFile();
fileToPurge = fileToPurge.substring(fileToPurge.lastIndexOf(File.separator) + 1, fileToPurge.lastIndexOf("."));
Log.d("QUEUE", "REMOVING " + queueId + " AND PURGING ALL OTHER QUEUE ITEMS FOR " + fileToPurge);
queueMap.remove(queueId);
for (Long queueNumber : queueMap.keySet()) {
if (queueMap.get(queueNumber).getQueueFile().contains(fileToPurge)) {
queueMap.remove(queueNumber);
Log.d("QUEUE", "REMOVED " + queueNumber + " FROM QUEUE, NEW QUEUE " + queueMap.keySet().toString());
}
}
saveQueue(context, queueMap, downloadQueueName);
return true;
} else{
return false;
}
}
*/
private static synchronized void saveQueue(Context context, HashMap<Long, QueueItem> queueMap, String jsonFileName) {
String queueJson = "";
String jsonFilePath = ZipHelper.getFileFolderName(context);
//Log.d("QUEUE", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD");
File jsonFile = new File(jsonFilePath + jsonFileName + ".tmp"); // write to temp and rename
if (jsonFile.exists()) {
jsonFile.delete();
}
String sdCardState = Environment.getExternalStorageState();
if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {
try {
jsonFile.createNewFile();
FileOutputStream jsonStream = new FileOutputStream(jsonFile);
GsonBuilder gBuild = new GsonBuilder();
Gson gson = gBuild.create();
queueJson = gson.toJson(queueMap);
byte[] buffer = queueJson.getBytes();
jsonStream.write(buffer);
jsonStream.flush();
jsonStream.close();
jsonStream = null;
Process p = Runtime.getRuntime().exec("mv " + jsonFilePath + jsonFileName + ".tmp " + jsonFilePath + jsonFileName);
} catch (IOException ioe) {
Log.e("QUEUE", "WRITING JSON FILE " + jsonFilePath + jsonFileName + " TO SD CARD FAILED");
return;
}
} else {
Log.e("QUEUE", "SD CARD WAS NOT FOUND");
return;
}
}
}
|
simplifying code by removing useless null checks
|
lib/src/main/java/scal/io/liger/QueueManager.java
|
simplifying code by removing useless null checks
|
<ide><path>ib/src/main/java/scal/io/liger/QueueManager.java
<ide> return cachedQueue;
<ide> }
<ide>
<del> if ((queueJson != null) && (queueJson.length() > 0)) {
<add> if ((queueJson.length() > 0)) {
<ide> GsonBuilder gBuild = new GsonBuilder();
<ide> Gson gson = gBuild.create();
<ide>
|
|
Java
|
apache-2.0
|
eb5d0f795372bc9fb5dc11d84670926f978b1821
| 0 |
Shvid/protostuff,protostuff/protostuff,svn2github/protostuff,protostuff/protostuff,dyu/protostuff,tsheasha/protostuff,svn2github/protostuff,myxyz/protostuff,tsheasha/protostuff,myxyz/protostuff,Shvid/protostuff,dyu/protostuff
|
//========================================================================
//Copyright 2007-2009 David Yu [email protected]
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.dyuproject.protostuff;
import java.io.IOException;
import java.io.OutputStream;
/**
* Encodes and writes protocol message fields.
*
* <p>This class contains two kinds of methods: methods that write specific
* protocol message constructs and field types (e.g. {@link #writeTag} and
* {@link #writeInt32}) and methods that write low-level values (e.g.
* {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are
* writing encoded protocol messages, you should use the former methods, but if
* you are writing some other format of your own design, use the latter.
*
* <p>This class is totally unsynchronized.
*
* @author [email protected] Kenton Varda
* @author David Yu
*/
public final class CodedOutput implements Output {
//START EXTRA
/** Returns a byte array encoded with the {@code message}. */
public static <T extends Message<T>> byte[] toByteArray(T message, boolean forceWritePrimitives) {
try {
final Schema<T> schema = message.getSchema();
final ComputedSizeOutput computedSize = new ComputedSizeOutput(forceWritePrimitives);
schema.writeTo(computedSize, message);
final byte[] result = new byte[computedSize.getSize()];
final CodedOutput output = new CodedOutput(result, 0, result.length,
forceWritePrimitives, computedSize);
schema.writeTo(output, message);
output.checkNoSpaceLeft();
return result;
} catch (IOException e) {
throw new RuntimeException(
"Serializing to a byte array threw an IOException " +
"(should never happen).", e);
}
}
/** Returns a byte array encoded with the tag and var int 32 */
public static byte[] getTagAndRawVarInt32Bytes(int tag, int value) {
int tagSize = computeRawVarint32Size(tag);
int size = computeRawVarint32Size(value);
int offset = 0;
byte[] buffer = new byte[tagSize + size];
if(tagSize==1)
buffer[offset++] = (byte)tag;
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
if(size==1)
buffer[offset] = (byte)value;
else {
for(int i=0,last=size-1; i<last; i++, value >>>= 7)
buffer[offset++] = (byte)((value & 0x7F) | 0x80);
buffer[offset] = (byte)value;
}
return buffer;
}
/** Returns a byte array encoded with the tag and var int 64 */
public static byte[] getTagAndRawVarInt64Bytes(int tag, long value) {
int tagSize = computeRawVarint32Size(tag);
int size = computeRawVarint64Size(value);
int offset = 0;
byte[] buffer = new byte[tagSize + size];
if(tagSize==1) {
buffer[offset++] = (byte)tag;
}
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
if(size==1) {
buffer[offset] = (byte)value;
}
else {
for(int i=0,last=size-1; i<last; i++, value >>>= 7)
buffer[offset++] = (byte)(((int)value & 0x7F) | 0x80);
buffer[offset] = (byte)value;
}
return buffer;
}
/** Returns a byte array encoded with the tag and little endian 32 */
public static byte[] getTagAndRawLittleEndian32Bytes(int tag, int value) {
int tagSize = computeRawVarint32Size(tag);
int offset = 0;
byte[] buffer = new byte[tagSize + LITTLE_ENDIAN_32_SIZE];
if(tagSize==1) {
buffer[offset++] = (byte)tag;
}
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
writeRawLittleEndian32(value, buffer, offset);
return buffer;
}
/** Returns a byte array encoded with the tag and little endian 64 */
public static byte[] getTagAndRawLittleEndian64Bytes(int tag, long value){
int tagSize = computeRawVarint32Size(tag);
int offset = 0;
byte[] buffer = new byte[tagSize + LITTLE_ENDIAN_64_SIZE];
if(tagSize==1) {
buffer[offset++] = (byte)tag;
}
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
writeRawLittleEndian64(value, buffer, offset);
return buffer;
}
/** Writes the encoded little endian 32 and returns the bytes written */
public static int writeRawLittleEndian32(int value, byte[] buffer, int offset) {
if(buffer.length - offset < LITTLE_ENDIAN_32_SIZE)
throw new IllegalArgumentException("buffer capacity not enough.");
buffer[offset++] = (byte)(value & 0xFF);
buffer[offset++] = (byte)(value >> 8 & 0xFF);
buffer[offset++] = (byte)(value >> 16 & 0xFF);
buffer[offset] = (byte)(value >> 24 & 0xFF);
return LITTLE_ENDIAN_32_SIZE;
}
/** Writes the encoded little endian 64 and returns the bytes written */
public static int writeRawLittleEndian64(long value, byte[] buffer, int offset) {
if(buffer.length - offset < LITTLE_ENDIAN_64_SIZE)
throw new IllegalArgumentException("buffer capacity not enough.");
buffer[offset++] = (byte)(value & 0xFF);
buffer[offset++] = (byte)(value >> 8 & 0xFF);
buffer[offset++] = (byte)(value >> 16 & 0xFF);
buffer[offset++] = (byte)(value >> 24 & 0xFF);
buffer[offset++] = (byte)(value >> 32 & 0xFF);
buffer[offset++] = (byte)(value >> 40 & 0xFF);
buffer[offset++] = (byte)(value >> 48 & 0xFF);
buffer[offset] = (byte)(value >> 56 & 0xFF);
return LITTLE_ENDIAN_64_SIZE;
}
//END EXTRA
private final byte[] buffer;
private final int limit;
private int position;
private final OutputStream output;
private final boolean forceWritePrimitives;
private final ComputedSizeOutput computedSize;
private ByteArrayNode current;
/**
* The buffer size used in {@link #newInstance(OutputStream)}.
*/
public static final int DEFAULT_BUFFER_SIZE = 4096;
/**
* Returns the buffer size to efficiently write dataLength bytes to this
* CodedOutputStream. Used by AbstractMessageLite.
*
* @return the buffer size to efficiently write dataLength bytes to this
* CodedOutputStream.
*/
static int computePreferredBufferSize(int dataLength) {
if (dataLength > DEFAULT_BUFFER_SIZE) return DEFAULT_BUFFER_SIZE;
return dataLength;
}
private CodedOutput(final byte[] buffer, final int offset, final int length,
final boolean forceWritePrimitives,final ComputedSizeOutput computedSize) {
int size = computedSize.getSize();
if(size!=0 && size!=length)
throw new IllegalArgumentException("The computed size is not equal to the buffer size.");
output = null;
this.buffer = buffer;
position = offset;
limit = offset + length;
this.forceWritePrimitives = forceWritePrimitives;
this.computedSize = computedSize.resetCount();
}
private CodedOutput(final OutputStream output, final byte[] buffer,
final boolean forceWritePrimitives) {
this.output = output;
this.buffer = buffer;
position = 0;
limit = buffer.length;
this.forceWritePrimitives = forceWritePrimitives;
computedSize = new ComputedSizeOutput(forceWritePrimitives);
}
/**
* Create a new {@code CodedOutputStream} wrapping the given
* {@code OutputStream}.
*/
public static CodedOutput newInstance(final OutputStream output,
final boolean forceWritePrimitives) {
return new CodedOutput(output, new byte[DEFAULT_BUFFER_SIZE], forceWritePrimitives);
}
/**
* Create a new {@code CodedOutputStream} wrapping the given
* {@code OutputStream} with a given buffer size.
*/
public static CodedOutput newInstance(final OutputStream output,
final int bufferSize, final boolean forceWritePrimitives) {
return new CodedOutput(output, new byte[bufferSize], forceWritePrimitives);
}
/**
* Create a new {@code CodedOutputStream} that writes directly to the given
* byte array. If more bytes are written than fit in the array,
* {@link OutOfSpaceException} will be thrown. Writing directly to a flat
* array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*/
public static CodedOutput newInstance(final byte[] flatArray,
final boolean forceWritePrimitives) {
return new CodedOutput(flatArray, 0, flatArray.length, forceWritePrimitives,
new ComputedSizeOutput(forceWritePrimitives));
}
static CodedOutput newInstance(final byte[] flatArray,
final boolean forceWritePrimitives, final ComputedSizeOutput computedSize) {
return new CodedOutput(flatArray, 0, flatArray.length, forceWritePrimitives, computedSize);
}
/*@
/**
* Create a new {@code CodedOutputStream} that writes directly to the given
* byte array slice. If more bytes are written than fit in the slice,
* {@link OutOfSpaceException} will be thrown. Writing directly to a flat
* array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*@
public static CodedOutput newInstance(final byte[] flatArray,
final int offset,
final int length,
final boolean forceWritePrimitives) {
return new CodedOutput(flatArray, offset, length, new SizeCountOutput());
}
/**
* Create a new {@code CodedOutputStream} that writes directly to the given
* byte array slice. If more bytes are written than fit in the slice,
* {@link OutOfSpaceException} will be thrown. Writing directly to a flat
* array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*@
public static CodedOutput newInstance(final byte[] flatArray,
final int offset,
final int length,
final forceWritePrimitives,
SizeCountOutput computedSize) {
return new CodedOutput(flatArray, offset, length, computedSize);
}*/
ComputedSizeOutput getComputedSize() {
return computedSize;
}
// -----------------------------------------------------------------
/** Write a {@code double} field, including tag, to the stream. */
public void writeDouble(final int fieldNumber, final double value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeDoubleNoTag(value);
}
/** Write a {@code float} field, including tag, to the stream. */
public void writeFloat(final int fieldNumber, final float value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeFloatNoTag(value);
}
/** Write a {@code uint64} field, including tag, to the stream. */
public void writeUInt64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeUInt64NoTag(value);
}
/** Write an {@code int64} field, including tag, to the stream. */
public void writeInt64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeInt64NoTag(value);
}
/** Write an {@code int32} field, including tag, to the stream. */
public void writeInt32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeInt32NoTag(value);
}
/** Write a {@code fixed64} field, including tag, to the stream. */
public void writeFixed64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeFixed64NoTag(value);
}
/** Write a {@code fixed32} field, including tag, to the stream. */
public void writeFixed32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeFixed32NoTag(value);
}
/** Write a {@code bool} field, including tag, to the stream. */
public void writeBool(final int fieldNumber, final boolean value)
throws IOException {
if(!value && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeBoolNoTag(value);
}
/** Write a {@code string} field, including tag, to the stream. */
public void writeString(final int fieldNumber, final String value)
throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeStringNoTag(value);
}
/*@ Write a {@code group} field, including tag, to the stream. */
/*public void writeGroup(final int fieldNumber, final MessageLite value)
throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP);
writeGroupNoTag(value);
writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP);
}*/
/*@
* Write a group represented by an {@link UnknownFieldSet}.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #writeGroup}.
*/
/*@Deprecated
public void writeUnknownGroup(final int fieldNumber,
final MessageLite value)
throws IOException {
writeGroup(fieldNumber, value);
}*/
/** Write an embedded message field, including tag, to the stream. */
public <T extends Message<T>> void writeMessage(final int fieldNumber, final T value)
throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeMessageNoTag(value);
}
/** Write a {@code bytes} field, including tag, to the stream. */
public void writeBytes(final int fieldNumber, final ByteString value)
throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeBytesNoTag(value);
}
/** Write a {@code uint32} field, including tag, to the stream. */
public void writeUInt32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeUInt32NoTag(value);
}
/**
* Write an enum field, including tag, to the stream. Caller is responsible
* for converting the enum value to its numeric value.
*/
public void writeEnum(final int fieldNumber, final int value)
throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeEnumNoTag(value);
}
/** Write an {@code sfixed32} field, including tag, to the stream. */
public void writeSFixed32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeSFixed32NoTag(value);
}
/** Write an {@code sfixed64} field, including tag, to the stream. */
public void writeSFixed64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeSFixed64NoTag(value);
}
/** Write an {@code sint32} field, including tag, to the stream. */
public void writeSInt32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeSInt32NoTag(value);
}
/** Write an {@code sint64} field, including tag, to the stream. */
public void writeSInt64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeSInt64NoTag(value);
}
/**
* Write a MessageSet extension field to the stream. For historical reasons,
* the wire format differs from normal fields.
*@
public void writeMessageSetExtension(final int fieldNumber,
final MessageLite value)
throws IOException {
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
writeMessage(WireFormat.MESSAGE_SET_MESSAGE, value);
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
}
/**
* Write an unparsed MessageSet extension field to the stream. For
* historical reasons, the wire format differs from normal fields.
*@
public void writeRawMessageSetExtension(final int fieldNumber,
final ByteString value)
throws IOException {
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
writeBytes(WireFormat.MESSAGE_SET_MESSAGE, value);
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
}*/
// -----------------------------------------------------------------
/** Write a {@code double} field to the stream. */
public void writeDoubleNoTag(final double value) throws IOException {
writeRawLittleEndian64(Double.doubleToRawLongBits(value));
}
/** Write a {@code float} field to the stream. */
public void writeFloatNoTag(final float value) throws IOException {
writeRawLittleEndian32(Float.floatToRawIntBits(value));
}
/** Write a {@code uint64} field to the stream. */
public void writeUInt64NoTag(final long value) throws IOException {
writeRawVarint64(value);
}
/** Write an {@code int64} field to the stream. */
public void writeInt64NoTag(final long value) throws IOException {
writeRawVarint64(value);
}
/** Write an {@code int32} field to the stream. */
public void writeInt32NoTag(final int value) throws IOException {
if (value >= 0) {
writeRawVarint32(value);
} else {
// Must sign-extend.
writeRawVarint64(value);
}
}
/** Write a {@code fixed64} field to the stream. */
public void writeFixed64NoTag(final long value) throws IOException {
writeRawLittleEndian64(value);
}
/** Write a {@code fixed32} field to the stream. */
public void writeFixed32NoTag(final int value) throws IOException {
writeRawLittleEndian32(value);
}
/** Write a {@code bool} field to the stream. */
public void writeBoolNoTag(final boolean value) throws IOException {
writeRawByte(value ? 1 : 0);
}
/** Write a {@code string} field to the stream. */
public void writeStringNoTag(final String value) throws IOException {
// Unfortunately there does not appear to be any way to tell Java to encode
// UTF-8 directly into our buffer, so we have to let it create its own byte
// array and then copy.
final byte[] bytes = value.getBytes(ByteString.UTF8);
writeRawVarint32(bytes.length);
writeRawBytes(bytes);
}
/*@ Write a {@code group} field to the stream. */
/*public void writeGroupNoTag(final MessageLite value) throws IOException {
value.writeTo(this);
}*/
/*@
* Write a group represented by an {@link UnknownFieldSet}.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #writeGroupNoTag}.
*/
/*@Deprecated
public void writeUnknownGroupNoTag(final MessageLite value)
throws IOException {
writeGroupNoTag(value);
}*/
/*@ Write an embedded message field to the stream. */
/*@public void writeMessageNoTag(final MessageLite value) throws IOException {
throws IOException {
writeRawVarint32(value.getSerializedSize());
value.writeTo(this);
}*/
/** Write a {@code bytes} field to the stream. */
public void writeBytesNoTag(final ByteString value) throws IOException {
final byte[] bytes = value.toByteArray();
writeRawVarint32(bytes.length);
writeRawBytes(bytes);
}
/** Write a {@code uint32} field to the stream. */
public void writeUInt32NoTag(final int value) throws IOException {
writeRawVarint32(value);
}
/**
* Write an enum field to the stream. Caller is responsible
* for converting the enum value to its numeric value.
*/
public void writeEnumNoTag(final int value) throws IOException {
writeRawVarint32(value);
}
/** Write an {@code sfixed32} field to the stream. */
public void writeSFixed32NoTag(final int value) throws IOException {
writeRawLittleEndian32(value);
}
/** Write an {@code sfixed64} field to the stream. */
public void writeSFixed64NoTag(final long value) throws IOException {
writeRawLittleEndian64(value);
}
/** Write an {@code sint32} field to the stream. */
public void writeSInt32NoTag(final int value) throws IOException {
writeRawVarint32(encodeZigZag32(value));
}
/** Write an {@code sint64} field to the stream. */
public void writeSInt64NoTag(final long value) throws IOException {
writeRawVarint64(encodeZigZag64(value));
}
// =================================================================
/**
* Compute the number of bytes that would be needed to encode a
* {@code double} field, including tag.
*/
public static int computeDoubleSize(final int fieldNumber,
final double value) {
return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code float} field, including tag.
*/
public static int computeFloatSize(final int fieldNumber, final float value) {
return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint64} field, including tag.
*/
public static int computeUInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int64} field, including tag.
*/
public static int computeInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int32} field, including tag.
*/
public static int computeInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed64} field, including tag.
*/
public static int computeFixed64Size(final int fieldNumber,
final long value) {
return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed32} field, including tag.
*/
public static int computeFixed32Size(final int fieldNumber,
final int value) {
return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bool} field, including tag.
*/
public static int computeBoolSize(final int fieldNumber,
final boolean value) {
return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value);
}
/*@
/**
* Compute the number of bytes that would be needed to encode a
* {@code string} field, including tag.
*@
public static int computeStringSize(final int fieldNumber,
final String value) {
return computeTagSize(fieldNumber) + computeStringSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field, including tag.
*@
public static int computeGroupSize(final int fieldNumber,
final MessageLite value) {
return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field represented by an {@code UnknownFieldSet}, including
* tag.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #computeGroupSize}.
*@
@Deprecated
public static int computeUnknownGroupSize(final int fieldNumber,
final MessageLite value) {
return computeGroupSize(fieldNumber, value);
}
/**
* Compute the number of bytes that would be needed to encode an
* embedded message field, including tag.
*@
public static int computeMessageSize(final int fieldNumber,
final MessageLite value) {
return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bytes} field, including tag.
*@
public static int computeBytesSize(final int fieldNumber,
final ByteString value) {
return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value);
}*/
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint32} field, including tag.
*/
public static int computeUInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* enum field, including tag. Caller is responsible for converting the
* enum value to its numeric value.
*/
public static int computeEnumSize(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed32} field, including tag.
*/
public static int computeSFixed32Size(final int fieldNumber,
final int value) {
return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed64} field, including tag.
*/
public static int computeSFixed64Size(final int fieldNumber,
final long value) {
return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint32} field, including tag.
*/
public static int computeSInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint64} field, including tag.
*/
public static int computeSInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value);
}
/*@
* Compute the number of bytes that would be needed to encode a
* MessageSet extension to the stream. For historical reasons,
* the wire format differs from normal fields.
*/
/*@public static int computeMessageSetExtensionSize(
final int fieldNumber, final MessageLite value) {
return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 +
computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) +
computeMessageSize(WireFormat.MESSAGE_SET_MESSAGE, value);
}*/
/*@
* Compute the number of bytes that would be needed to encode an
* unparsed MessageSet extension field to the stream. For
* historical reasons, the wire format differs from normal fields.
*/
/*@public static int computeRawMessageSetExtensionSize(
final int fieldNumber, final ByteString value) {
return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 +
computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) +
computeBytesSize(WireFormat.MESSAGE_SET_MESSAGE, value);
}*/
// -----------------------------------------------------------------
/**
* Compute the number of bytes that would be needed to encode a
* {@code double} field, including tag.
*/
public static int computeDoubleSizeNoTag(final double value) {
return LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code float} field, including tag.
*/
public static int computeFloatSizeNoTag(final float value) {
return LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint64} field, including tag.
*/
public static int computeUInt64SizeNoTag(final long value) {
return computeRawVarint64Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int64} field, including tag.
*/
public static int computeInt64SizeNoTag(final long value) {
return computeRawVarint64Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int32} field, including tag.
*/
public static int computeInt32SizeNoTag(final int value) {
if (value >= 0) {
return computeRawVarint32Size(value);
} else {
// Must sign-extend.
return 10;
}
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed64} field.
*/
public static int computeFixed64SizeNoTag(final long value) {
return LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed32} field.
*/
public static int computeFixed32SizeNoTag(final int value) {
return LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bool} field.
*/
public static int computeBoolSizeNoTag(final boolean value) {
return 1;
}
/*@
/**
* Compute the number of bytes that would be needed to encode a
* {@code string} field.
*@
public static int computeStringSizeNoTag(final String value) {
try {
final byte[] bytes = value.getBytes("UTF-8");
return computeRawVarint32Size(bytes.length) +
bytes.length;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 not supported.", e);
}
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field.
*@
public static int computeGroupSizeNoTag(final MessageLite value) {
return value.getSerializedSize();
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field represented by an {@code UnknownFieldSet}, including
* tag.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #computeUnknownGroupSizeNoTag}.
*@
@Deprecated
public static int computeUnknownGroupSizeNoTag(final MessageLite value) {
return computeGroupSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an embedded
* message field.
*@
public static int computeMessageSizeNoTag(final MessageLite value) {
final int size = value.getSerializedSize();
return computeRawVarint32Size(size) + size;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bytes} field.
*@
public static int computeBytesSizeNoTag(final ByteString value) {
return computeRawVarint32Size(value.size()) +
value.size();
}*/
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint32} field.
*/
public static int computeUInt32SizeNoTag(final int value) {
return computeRawVarint32Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an enum field.
* Caller is responsible for converting the enum value to its numeric value.
*/
public static int computeEnumSizeNoTag(final int value) {
return computeRawVarint32Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed32} field.
*/
public static int computeSFixed32SizeNoTag(final int value) {
return LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed64} field.
*/
public static int computeSFixed64SizeNoTag(final long value) {
return LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint32} field.
*/
public static int computeSInt32SizeNoTag(final int value) {
return computeRawVarint32Size(encodeZigZag32(value));
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint64} field.
*/
public static int computeSInt64SizeNoTag(final long value) {
return computeRawVarint64Size(encodeZigZag64(value));
}
// =================================================================
/**
* Internal helper that writes the current buffer to the output. The
* buffer position is reset to its initial value when this returns.
*/
private void refreshBuffer() throws IOException {
if (output == null) {
// We're writing to a single buffer.
throw new OutOfSpaceException();
}
// Since we have an output stream, this is our buffer
// and buffer offset == 0
output.write(buffer, 0, position);
position = 0;
}
/**
* Flushes the stream and forces any buffered bytes to be written. This
* does not flush the underlying OutputStream.
*/
public void flush() throws IOException {
if (output != null) {
refreshBuffer();
}
}
/**
* If writing to a flat array, return the space left in the array.
* Otherwise, throws {@code UnsupportedOperationException}.
*/
public int spaceLeft() {
if (output == null) {
return limit - position;
} else {
throw new UnsupportedOperationException(
"spaceLeft() can only be called on CodedOutputStreams that are " +
"writing to a flat array.");
}
}
/**
* Verifies that {@link #spaceLeft()} returns zero. It's common to create
* a byte array that is exactly big enough to hold a message, then write to
* it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()}
* after writing verifies that the message was actually as big as expected,
* which can help catch bugs.
*/
public void checkNoSpaceLeft() {
if (spaceLeft() != 0) {
throw new IllegalStateException(
"Did not write as much data as expected.");
}
}
/**
* If you create a CodedOutputStream around a simple flat array, you must
* not attempt to write more bytes than the array has space. Otherwise,
* this exception will be thrown.
*/
public static class OutOfSpaceException extends IOException {
private static final long serialVersionUID = -6947486886997889499L;
OutOfSpaceException() {
super("CodedOutputStream was writing to a flat byte array and ran " +
"out of space.");
}
}
/** Write a single byte. */
public void writeRawByte(final byte value) throws IOException {
if (position == limit) {
refreshBuffer();
}
buffer[position++] = value;
}
/** Write a single byte, represented by an integer value. */
public void writeRawByte(final int value) throws IOException {
writeRawByte((byte) value);
}
/** Write an array of bytes. */
public void writeRawBytes(final byte[] value) throws IOException {
writeRawBytes(value, 0, value.length);
}
/** Write part of an array of bytes. */
public void writeRawBytes(final byte[] value, int offset, int length)
throws IOException {
if (limit - position >= length) {
// We have room in the current buffer.
System.arraycopy(value, offset, buffer, position, length);
position += length;
} else {
// Write extends past current buffer. Fill the rest of this buffer and
// flush.
final int bytesWritten = limit - position;
System.arraycopy(value, offset, buffer, position, bytesWritten);
offset += bytesWritten;
length -= bytesWritten;
position = limit;
refreshBuffer();
// Now deal with the rest.
// Since we have an output stream, this is our buffer
// and buffer offset == 0
if (length <= limit) {
// Fits in new buffer.
System.arraycopy(value, offset, buffer, 0, length);
position = length;
} else {
// Write is very big. Let's do it all at once.
output.write(value, offset, length);
}
}
}
/** Encode and write a tag. */
public void writeTag(final int fieldNumber, final int wireType)
throws IOException {
writeRawVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
/** Compute the number of bytes that would be needed to encode a tag. */
public static int computeTagSize(final int fieldNumber) {
return computeRawVarint32Size(WireFormat.makeTag(fieldNumber, 0));
}
/**
* Encode and write a varint. {@code value} is treated as
* unsigned, so it won't be sign-extended if negative.
*/
public void writeRawVarint32(int value) throws IOException {
while (true) {
if ((value & ~0x7F) == 0) {
writeRawByte(value);
return;
} else {
writeRawByte((value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
/**
* Compute the number of bytes that would be needed to encode a varint.
* {@code value} is treated as unsigned, so it won't be sign-extended if
* negative.
*/
public static int computeRawVarint32Size(final int value) {
if ((value & (0xffffffff << 7)) == 0) return 1;
if ((value & (0xffffffff << 14)) == 0) return 2;
if ((value & (0xffffffff << 21)) == 0) return 3;
if ((value & (0xffffffff << 28)) == 0) return 4;
return 5;
}
/** Encode and write a varint. */
public void writeRawVarint64(long value) throws IOException {
while (true) {
if ((value & ~0x7FL) == 0) {
writeRawByte((int)value);
return;
} else {
writeRawByte(((int)value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
/** Compute the number of bytes that would be needed to encode a varint. */
public static int computeRawVarint64Size(final long value) {
if ((value & (0xffffffffffffffffL << 7)) == 0) return 1;
if ((value & (0xffffffffffffffffL << 14)) == 0) return 2;
if ((value & (0xffffffffffffffffL << 21)) == 0) return 3;
if ((value & (0xffffffffffffffffL << 28)) == 0) return 4;
if ((value & (0xffffffffffffffffL << 35)) == 0) return 5;
if ((value & (0xffffffffffffffffL << 42)) == 0) return 6;
if ((value & (0xffffffffffffffffL << 49)) == 0) return 7;
if ((value & (0xffffffffffffffffL << 56)) == 0) return 8;
if ((value & (0xffffffffffffffffL << 63)) == 0) return 9;
return 10;
}
/** Write a little-endian 32-bit integer. */
public void writeRawLittleEndian32(final int value) throws IOException {
writeRawByte((value ) & 0xFF);
writeRawByte((value >> 8) & 0xFF);
writeRawByte((value >> 16) & 0xFF);
writeRawByte((value >> 24) & 0xFF);
}
public static final int LITTLE_ENDIAN_32_SIZE = 4;
/** Write a little-endian 64-bit integer. */
public void writeRawLittleEndian64(final long value) throws IOException {
writeRawByte((int)(value ) & 0xFF);
writeRawByte((int)(value >> 8) & 0xFF);
writeRawByte((int)(value >> 16) & 0xFF);
writeRawByte((int)(value >> 24) & 0xFF);
writeRawByte((int)(value >> 32) & 0xFF);
writeRawByte((int)(value >> 40) & 0xFF);
writeRawByte((int)(value >> 48) & 0xFF);
writeRawByte((int)(value >> 56) & 0xFF);
}
public static final int LITTLE_ENDIAN_64_SIZE = 8;
/**
* Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers
* into values that can be efficiently encoded with varint. (Otherwise,
* negative values must be sign-extended to 64 bits to be varint encoded,
* thus always taking 10 bytes on the wire.)
*
* @param n A signed 32-bit integer.
* @return An unsigned 32-bit integer, stored in a signed int because
* Java has no explicit unsigned support.
*/
public static int encodeZigZag32(final int n) {
// Note: the right-shift must be arithmetic
return (n << 1) ^ (n >> 31);
}
/**
* Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
* into values that can be efficiently encoded with varint. (Otherwise,
* negative values must be sign-extended to 64 bits to be varint encoded,
* thus always taking 10 bytes on the wire.)
*
* @param n A signed 64-bit integer.
* @return An unsigned 64-bit integer, stored in a signed int because
* Java has no explicit unsigned support.
*/
public static long encodeZigZag64(final long n) {
// Note: the right-shift must be arithmetic
return (n << 1) ^ (n >> 63);
}
//START EXTRA
public void writeByteArray(int fieldNumber, byte[] value) throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeByteArrayNoTag(value);
}
public <T> void writeObject(int fieldNumber, T value, Schema<T> schema) throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
ComputedSizeOutput sc = computedSize;
int last = sc.getSize();
schema.writeTo(sc, value);
writeRawVarint32(sc.getSize() - last);
schema.writeTo(this, value);
}
public <T> void writeObject(int fieldNumber, T value, Class<T> typeClass) throws IOException {
if(value==null)
return;
ByteArrayNode node = current;
if(node==null)
node = computedSize.getRoot();
writeRawBytes(node.bytes);
writeRawBytes(node.next.bytes);
current = node.next.next;
}
public void writeByteArrayNoTag(byte[] value) throws IOException {
writeRawVarint32(value.length);
writeRawBytes(value);
}
public <T extends Message<T>> void writeMessageNoTag(T value) throws IOException {
Schema<T> schema = value.getSchema();
ComputedSizeOutput sc = computedSize;
int last = sc.getSize();
schema.writeTo(sc, value);
writeRawVarint32(sc.getSize() - last);
schema.writeTo(this, value);
}
//END EXTRA
}
|
protostuff-core/src/main/java/com/dyuproject/protostuff/CodedOutput.java
|
//========================================================================
//Copyright 2007-2009 David Yu [email protected]
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.dyuproject.protostuff;
import java.io.IOException;
import java.io.OutputStream;
/**
* Encodes and writes protocol message fields.
*
* <p>This class contains two kinds of methods: methods that write specific
* protocol message constructs and field types (e.g. {@link #writeTag} and
* {@link #writeInt32}) and methods that write low-level values (e.g.
* {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are
* writing encoded protocol messages, you should use the former methods, but if
* you are writing some other format of your own design, use the latter.
*
* <p>This class is totally unsynchronized.
*
* @author [email protected] Kenton Varda
* @author David Yu
*/
public final class CodedOutput implements Output {
//START EXTRA
/** Returns a byte array encoded with the {@code message}. */
public static <T extends Message<T>> byte[] toByteArray(T message, boolean forceWritePrimitives) {
try {
final Schema<T> schema = message.getSchema();
final ComputedSizeOutput computedSize = new ComputedSizeOutput(forceWritePrimitives);
schema.writeTo(computedSize, message);
final byte[] result = new byte[computedSize.getSize()];
final CodedOutput output = new CodedOutput(result, 0, result.length,
forceWritePrimitives, computedSize);
schema.writeTo(output, message);
output.checkNoSpaceLeft();
return result;
} catch (IOException e) {
throw new RuntimeException(
"Serializing to a byte array threw an IOException " +
"(should never happen).", e);
}
}
/** Returns a byte array encoded with the tag and var int 32 */
public static byte[] getTagAndRawVarInt32Bytes(int tag, int value) {
int tagSize = computeRawVarint32Size(tag);
int size = computeRawVarint32Size(value);
int offset = 0;
byte[] buffer = new byte[tagSize + size];
if(tagSize==1)
buffer[offset++] = (byte)tag;
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
if(size==1)
buffer[offset] = (byte)value;
else {
for(int i=0,last=size-1; i<last; i++, value >>>= 7)
buffer[offset++] = (byte)((value & 0x7F) | 0x80);
buffer[offset] = (byte)value;
}
return buffer;
}
/** Returns a byte array encoded with the tag and var int 64 */
public static byte[] getTagAndRawVarInt64Bytes(int tag, long value) {
int tagSize = computeRawVarint32Size(tag);
int size = computeRawVarint64Size(value);
int offset = 0;
byte[] buffer = new byte[tagSize + size];
if(tagSize==1) {
buffer[offset++] = (byte)tag;
}
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
if(size==1) {
buffer[offset] = (byte)value;
}
else {
for(int i=0,last=size-1; i<last; i++, value >>>= 7)
buffer[offset++] = (byte)(((int)value & 0x7F) | 0x80);
buffer[offset] = (byte)value;
}
return buffer;
}
/** Returns a byte array encoded with the tag and little endian 32 */
public static byte[] getTagAndRawLittleEndian32Bytes(int tag, int value) {
int tagSize = computeRawVarint32Size(tag);
int offset = 0;
byte[] buffer = new byte[tagSize + LITTLE_ENDIAN_32_SIZE];
if(tagSize==1) {
buffer[offset++] = (byte)tag;
}
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
writeRawLittleEndian32(value, buffer, offset);
return buffer;
}
/** Returns a byte array encoded with the tag and little endian 64 */
public static byte[] getTagAndRawLittleEndian64Bytes(int tag, long value){
int tagSize = computeRawVarint32Size(tag);
int offset = 0;
byte[] buffer = new byte[tagSize + LITTLE_ENDIAN_64_SIZE];
if(tagSize==1) {
buffer[offset++] = (byte)tag;
}
else {
for(int i=0,last=tagSize-1; i<last; i++, tag >>>= 7)
buffer[offset++] = (byte)((tag & 0x7F) | 0x80);
buffer[offset++] = (byte)tag;
}
writeRawLittleEndian64(value, buffer, offset);
return buffer;
}
/** Writes the encoded little endian 32 and returns the bytes written */
public static int writeRawLittleEndian32(int value, byte[] buffer, int offset) {
if(buffer.length - offset < LITTLE_ENDIAN_32_SIZE)
throw new IllegalArgumentException("buffer capacity not enough.");
buffer[offset++] = (byte)(value & 0xFF);
buffer[offset++] = (byte)(value >> 8 & 0xFF);
buffer[offset++] = (byte)(value >> 16 & 0xFF);
buffer[offset++] = (byte)(value >> 24 & 0xFF);
return LITTLE_ENDIAN_32_SIZE;
}
/** Writes the encoded little endian 64 and returns the bytes written */
public static int writeRawLittleEndian64(long value, byte[] buffer, int offset) {
if(buffer.length - offset < LITTLE_ENDIAN_64_SIZE)
throw new IllegalArgumentException("buffer capacity not enough.");
buffer[offset++] = (byte)((int)value & 0xFF);
buffer[offset++] = (byte)((int)value >> 8 & 0xFF);
buffer[offset++] = (byte)((int)value >> 16 & 0xFF);
buffer[offset++] = (byte)((int)value >> 24 & 0xFF);
buffer[offset++] = (byte)((int)value >> 32 & 0xFF);
buffer[offset++] = (byte)((int)value >> 40 & 0xFF);
buffer[offset++] = (byte)((int)value >> 48 & 0xFF);
buffer[offset++] = (byte)((int)value >> 56 & 0xFF);
return LITTLE_ENDIAN_64_SIZE;
}
//END EXTRA
private final byte[] buffer;
private final int limit;
private int position;
private final OutputStream output;
private final boolean forceWritePrimitives;
private final ComputedSizeOutput computedSize;
private ByteArrayNode current;
/**
* The buffer size used in {@link #newInstance(OutputStream)}.
*/
public static final int DEFAULT_BUFFER_SIZE = 4096;
/**
* Returns the buffer size to efficiently write dataLength bytes to this
* CodedOutputStream. Used by AbstractMessageLite.
*
* @return the buffer size to efficiently write dataLength bytes to this
* CodedOutputStream.
*/
static int computePreferredBufferSize(int dataLength) {
if (dataLength > DEFAULT_BUFFER_SIZE) return DEFAULT_BUFFER_SIZE;
return dataLength;
}
private CodedOutput(final byte[] buffer, final int offset, final int length,
final boolean forceWritePrimitives,final ComputedSizeOutput computedSize) {
int size = computedSize.getSize();
if(size!=0 && size!=length)
throw new IllegalArgumentException("The computed size is not equal to the buffer size.");
output = null;
this.buffer = buffer;
position = offset;
limit = offset + length;
this.forceWritePrimitives = forceWritePrimitives;
this.computedSize = computedSize.resetCount();
}
private CodedOutput(final OutputStream output, final byte[] buffer,
final boolean forceWritePrimitives) {
this.output = output;
this.buffer = buffer;
position = 0;
limit = buffer.length;
this.forceWritePrimitives = forceWritePrimitives;
computedSize = new ComputedSizeOutput(forceWritePrimitives);
}
/**
* Create a new {@code CodedOutputStream} wrapping the given
* {@code OutputStream}.
*/
public static CodedOutput newInstance(final OutputStream output,
final boolean forceWritePrimitives) {
return new CodedOutput(output, new byte[DEFAULT_BUFFER_SIZE], forceWritePrimitives);
}
/**
* Create a new {@code CodedOutputStream} wrapping the given
* {@code OutputStream} with a given buffer size.
*/
public static CodedOutput newInstance(final OutputStream output,
final int bufferSize, final boolean forceWritePrimitives) {
return new CodedOutput(output, new byte[bufferSize], forceWritePrimitives);
}
/**
* Create a new {@code CodedOutputStream} that writes directly to the given
* byte array. If more bytes are written than fit in the array,
* {@link OutOfSpaceException} will be thrown. Writing directly to a flat
* array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*/
public static CodedOutput newInstance(final byte[] flatArray,
final boolean forceWritePrimitives) {
return new CodedOutput(flatArray, 0, flatArray.length, forceWritePrimitives,
new ComputedSizeOutput(forceWritePrimitives));
}
static CodedOutput newInstance(final byte[] flatArray,
final boolean forceWritePrimitives, final ComputedSizeOutput computedSize) {
return new CodedOutput(flatArray, 0, flatArray.length, forceWritePrimitives, computedSize);
}
/*@
/**
* Create a new {@code CodedOutputStream} that writes directly to the given
* byte array slice. If more bytes are written than fit in the slice,
* {@link OutOfSpaceException} will be thrown. Writing directly to a flat
* array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*@
public static CodedOutput newInstance(final byte[] flatArray,
final int offset,
final int length,
final boolean forceWritePrimitives) {
return new CodedOutput(flatArray, offset, length, new SizeCountOutput());
}
/**
* Create a new {@code CodedOutputStream} that writes directly to the given
* byte array slice. If more bytes are written than fit in the slice,
* {@link OutOfSpaceException} will be thrown. Writing directly to a flat
* array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*@
public static CodedOutput newInstance(final byte[] flatArray,
final int offset,
final int length,
final forceWritePrimitives,
SizeCountOutput computedSize) {
return new CodedOutput(flatArray, offset, length, computedSize);
}*/
ComputedSizeOutput getComputedSize() {
return computedSize;
}
// -----------------------------------------------------------------
/** Write a {@code double} field, including tag, to the stream. */
public void writeDouble(final int fieldNumber, final double value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeDoubleNoTag(value);
}
/** Write a {@code float} field, including tag, to the stream. */
public void writeFloat(final int fieldNumber, final float value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeFloatNoTag(value);
}
/** Write a {@code uint64} field, including tag, to the stream. */
public void writeUInt64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeUInt64NoTag(value);
}
/** Write an {@code int64} field, including tag, to the stream. */
public void writeInt64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeInt64NoTag(value);
}
/** Write an {@code int32} field, including tag, to the stream. */
public void writeInt32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeInt32NoTag(value);
}
/** Write a {@code fixed64} field, including tag, to the stream. */
public void writeFixed64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeFixed64NoTag(value);
}
/** Write a {@code fixed32} field, including tag, to the stream. */
public void writeFixed32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeFixed32NoTag(value);
}
/** Write a {@code bool} field, including tag, to the stream. */
public void writeBool(final int fieldNumber, final boolean value)
throws IOException {
if(!value && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeBoolNoTag(value);
}
/** Write a {@code string} field, including tag, to the stream. */
public void writeString(final int fieldNumber, final String value)
throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeStringNoTag(value);
}
/*@ Write a {@code group} field, including tag, to the stream. */
/*public void writeGroup(final int fieldNumber, final MessageLite value)
throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP);
writeGroupNoTag(value);
writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP);
}*/
/*@
* Write a group represented by an {@link UnknownFieldSet}.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #writeGroup}.
*/
/*@Deprecated
public void writeUnknownGroup(final int fieldNumber,
final MessageLite value)
throws IOException {
writeGroup(fieldNumber, value);
}*/
/** Write an embedded message field, including tag, to the stream. */
public <T extends Message<T>> void writeMessage(final int fieldNumber, final T value)
throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeMessageNoTag(value);
}
/** Write a {@code bytes} field, including tag, to the stream. */
public void writeBytes(final int fieldNumber, final ByteString value)
throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeBytesNoTag(value);
}
/** Write a {@code uint32} field, including tag, to the stream. */
public void writeUInt32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeUInt32NoTag(value);
}
/**
* Write an enum field, including tag, to the stream. Caller is responsible
* for converting the enum value to its numeric value.
*/
public void writeEnum(final int fieldNumber, final int value)
throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeEnumNoTag(value);
}
/** Write an {@code sfixed32} field, including tag, to the stream. */
public void writeSFixed32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeSFixed32NoTag(value);
}
/** Write an {@code sfixed64} field, including tag, to the stream. */
public void writeSFixed64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeSFixed64NoTag(value);
}
/** Write an {@code sint32} field, including tag, to the stream. */
public void writeSInt32(final int fieldNumber, final int value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeSInt32NoTag(value);
}
/** Write an {@code sint64} field, including tag, to the stream. */
public void writeSInt64(final int fieldNumber, final long value)
throws IOException {
if(value==0 && !forceWritePrimitives)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeSInt64NoTag(value);
}
/**
* Write a MessageSet extension field to the stream. For historical reasons,
* the wire format differs from normal fields.
*@
public void writeMessageSetExtension(final int fieldNumber,
final MessageLite value)
throws IOException {
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
writeMessage(WireFormat.MESSAGE_SET_MESSAGE, value);
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
}
/**
* Write an unparsed MessageSet extension field to the stream. For
* historical reasons, the wire format differs from normal fields.
*@
public void writeRawMessageSetExtension(final int fieldNumber,
final ByteString value)
throws IOException {
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
writeBytes(WireFormat.MESSAGE_SET_MESSAGE, value);
writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
}*/
// -----------------------------------------------------------------
/** Write a {@code double} field to the stream. */
public void writeDoubleNoTag(final double value) throws IOException {
writeRawLittleEndian64(Double.doubleToRawLongBits(value));
}
/** Write a {@code float} field to the stream. */
public void writeFloatNoTag(final float value) throws IOException {
writeRawLittleEndian32(Float.floatToRawIntBits(value));
}
/** Write a {@code uint64} field to the stream. */
public void writeUInt64NoTag(final long value) throws IOException {
writeRawVarint64(value);
}
/** Write an {@code int64} field to the stream. */
public void writeInt64NoTag(final long value) throws IOException {
writeRawVarint64(value);
}
/** Write an {@code int32} field to the stream. */
public void writeInt32NoTag(final int value) throws IOException {
if (value >= 0) {
writeRawVarint32(value);
} else {
// Must sign-extend.
writeRawVarint64(value);
}
}
/** Write a {@code fixed64} field to the stream. */
public void writeFixed64NoTag(final long value) throws IOException {
writeRawLittleEndian64(value);
}
/** Write a {@code fixed32} field to the stream. */
public void writeFixed32NoTag(final int value) throws IOException {
writeRawLittleEndian32(value);
}
/** Write a {@code bool} field to the stream. */
public void writeBoolNoTag(final boolean value) throws IOException {
writeRawByte(value ? 1 : 0);
}
/** Write a {@code string} field to the stream. */
public void writeStringNoTag(final String value) throws IOException {
// Unfortunately there does not appear to be any way to tell Java to encode
// UTF-8 directly into our buffer, so we have to let it create its own byte
// array and then copy.
final byte[] bytes = value.getBytes(ByteString.UTF8);
writeRawVarint32(bytes.length);
writeRawBytes(bytes);
}
/*@ Write a {@code group} field to the stream. */
/*public void writeGroupNoTag(final MessageLite value) throws IOException {
value.writeTo(this);
}*/
/*@
* Write a group represented by an {@link UnknownFieldSet}.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #writeGroupNoTag}.
*/
/*@Deprecated
public void writeUnknownGroupNoTag(final MessageLite value)
throws IOException {
writeGroupNoTag(value);
}*/
/*@ Write an embedded message field to the stream. */
/*@public void writeMessageNoTag(final MessageLite value) throws IOException {
throws IOException {
writeRawVarint32(value.getSerializedSize());
value.writeTo(this);
}*/
/** Write a {@code bytes} field to the stream. */
public void writeBytesNoTag(final ByteString value) throws IOException {
final byte[] bytes = value.toByteArray();
writeRawVarint32(bytes.length);
writeRawBytes(bytes);
}
/** Write a {@code uint32} field to the stream. */
public void writeUInt32NoTag(final int value) throws IOException {
writeRawVarint32(value);
}
/**
* Write an enum field to the stream. Caller is responsible
* for converting the enum value to its numeric value.
*/
public void writeEnumNoTag(final int value) throws IOException {
writeRawVarint32(value);
}
/** Write an {@code sfixed32} field to the stream. */
public void writeSFixed32NoTag(final int value) throws IOException {
writeRawLittleEndian32(value);
}
/** Write an {@code sfixed64} field to the stream. */
public void writeSFixed64NoTag(final long value) throws IOException {
writeRawLittleEndian64(value);
}
/** Write an {@code sint32} field to the stream. */
public void writeSInt32NoTag(final int value) throws IOException {
writeRawVarint32(encodeZigZag32(value));
}
/** Write an {@code sint64} field to the stream. */
public void writeSInt64NoTag(final long value) throws IOException {
writeRawVarint64(encodeZigZag64(value));
}
// =================================================================
/**
* Compute the number of bytes that would be needed to encode a
* {@code double} field, including tag.
*/
public static int computeDoubleSize(final int fieldNumber,
final double value) {
return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code float} field, including tag.
*/
public static int computeFloatSize(final int fieldNumber, final float value) {
return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint64} field, including tag.
*/
public static int computeUInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int64} field, including tag.
*/
public static int computeInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int32} field, including tag.
*/
public static int computeInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed64} field, including tag.
*/
public static int computeFixed64Size(final int fieldNumber,
final long value) {
return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed32} field, including tag.
*/
public static int computeFixed32Size(final int fieldNumber,
final int value) {
return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bool} field, including tag.
*/
public static int computeBoolSize(final int fieldNumber,
final boolean value) {
return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value);
}
/*@
/**
* Compute the number of bytes that would be needed to encode a
* {@code string} field, including tag.
*@
public static int computeStringSize(final int fieldNumber,
final String value) {
return computeTagSize(fieldNumber) + computeStringSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field, including tag.
*@
public static int computeGroupSize(final int fieldNumber,
final MessageLite value) {
return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field represented by an {@code UnknownFieldSet}, including
* tag.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #computeGroupSize}.
*@
@Deprecated
public static int computeUnknownGroupSize(final int fieldNumber,
final MessageLite value) {
return computeGroupSize(fieldNumber, value);
}
/**
* Compute the number of bytes that would be needed to encode an
* embedded message field, including tag.
*@
public static int computeMessageSize(final int fieldNumber,
final MessageLite value) {
return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bytes} field, including tag.
*@
public static int computeBytesSize(final int fieldNumber,
final ByteString value) {
return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value);
}*/
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint32} field, including tag.
*/
public static int computeUInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* enum field, including tag. Caller is responsible for converting the
* enum value to its numeric value.
*/
public static int computeEnumSize(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed32} field, including tag.
*/
public static int computeSFixed32Size(final int fieldNumber,
final int value) {
return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed64} field, including tag.
*/
public static int computeSFixed64Size(final int fieldNumber,
final long value) {
return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint32} field, including tag.
*/
public static int computeSInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint64} field, including tag.
*/
public static int computeSInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value);
}
/*@
* Compute the number of bytes that would be needed to encode a
* MessageSet extension to the stream. For historical reasons,
* the wire format differs from normal fields.
*/
/*@public static int computeMessageSetExtensionSize(
final int fieldNumber, final MessageLite value) {
return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 +
computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) +
computeMessageSize(WireFormat.MESSAGE_SET_MESSAGE, value);
}*/
/*@
* Compute the number of bytes that would be needed to encode an
* unparsed MessageSet extension field to the stream. For
* historical reasons, the wire format differs from normal fields.
*/
/*@public static int computeRawMessageSetExtensionSize(
final int fieldNumber, final ByteString value) {
return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 +
computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) +
computeBytesSize(WireFormat.MESSAGE_SET_MESSAGE, value);
}*/
// -----------------------------------------------------------------
/**
* Compute the number of bytes that would be needed to encode a
* {@code double} field, including tag.
*/
public static int computeDoubleSizeNoTag(final double value) {
return LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code float} field, including tag.
*/
public static int computeFloatSizeNoTag(final float value) {
return LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint64} field, including tag.
*/
public static int computeUInt64SizeNoTag(final long value) {
return computeRawVarint64Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int64} field, including tag.
*/
public static int computeInt64SizeNoTag(final long value) {
return computeRawVarint64Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code int32} field, including tag.
*/
public static int computeInt32SizeNoTag(final int value) {
if (value >= 0) {
return computeRawVarint32Size(value);
} else {
// Must sign-extend.
return 10;
}
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed64} field.
*/
public static int computeFixed64SizeNoTag(final long value) {
return LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code fixed32} field.
*/
public static int computeFixed32SizeNoTag(final int value) {
return LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bool} field.
*/
public static int computeBoolSizeNoTag(final boolean value) {
return 1;
}
/*@
/**
* Compute the number of bytes that would be needed to encode a
* {@code string} field.
*@
public static int computeStringSizeNoTag(final String value) {
try {
final byte[] bytes = value.getBytes("UTF-8");
return computeRawVarint32Size(bytes.length) +
bytes.length;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 not supported.", e);
}
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field.
*@
public static int computeGroupSizeNoTag(final MessageLite value) {
return value.getSerializedSize();
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code group} field represented by an {@code UnknownFieldSet}, including
* tag.
*
* @deprecated UnknownFieldSet now implements MessageLite, so you can just
* call {@link #computeUnknownGroupSizeNoTag}.
*@
@Deprecated
public static int computeUnknownGroupSizeNoTag(final MessageLite value) {
return computeGroupSizeNoTag(value);
}
/**
* Compute the number of bytes that would be needed to encode an embedded
* message field.
*@
public static int computeMessageSizeNoTag(final MessageLite value) {
final int size = value.getSerializedSize();
return computeRawVarint32Size(size) + size;
}
/**
* Compute the number of bytes that would be needed to encode a
* {@code bytes} field.
*@
public static int computeBytesSizeNoTag(final ByteString value) {
return computeRawVarint32Size(value.size()) +
value.size();
}*/
/**
* Compute the number of bytes that would be needed to encode a
* {@code uint32} field.
*/
public static int computeUInt32SizeNoTag(final int value) {
return computeRawVarint32Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an enum field.
* Caller is responsible for converting the enum value to its numeric value.
*/
public static int computeEnumSizeNoTag(final int value) {
return computeRawVarint32Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed32} field.
*/
public static int computeSFixed32SizeNoTag(final int value) {
return LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sfixed64} field.
*/
public static int computeSFixed64SizeNoTag(final long value) {
return LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint32} field.
*/
public static int computeSInt32SizeNoTag(final int value) {
return computeRawVarint32Size(encodeZigZag32(value));
}
/**
* Compute the number of bytes that would be needed to encode an
* {@code sint64} field.
*/
public static int computeSInt64SizeNoTag(final long value) {
return computeRawVarint64Size(encodeZigZag64(value));
}
// =================================================================
/**
* Internal helper that writes the current buffer to the output. The
* buffer position is reset to its initial value when this returns.
*/
private void refreshBuffer() throws IOException {
if (output == null) {
// We're writing to a single buffer.
throw new OutOfSpaceException();
}
// Since we have an output stream, this is our buffer
// and buffer offset == 0
output.write(buffer, 0, position);
position = 0;
}
/**
* Flushes the stream and forces any buffered bytes to be written. This
* does not flush the underlying OutputStream.
*/
public void flush() throws IOException {
if (output != null) {
refreshBuffer();
}
}
/**
* If writing to a flat array, return the space left in the array.
* Otherwise, throws {@code UnsupportedOperationException}.
*/
public int spaceLeft() {
if (output == null) {
return limit - position;
} else {
throw new UnsupportedOperationException(
"spaceLeft() can only be called on CodedOutputStreams that are " +
"writing to a flat array.");
}
}
/**
* Verifies that {@link #spaceLeft()} returns zero. It's common to create
* a byte array that is exactly big enough to hold a message, then write to
* it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()}
* after writing verifies that the message was actually as big as expected,
* which can help catch bugs.
*/
public void checkNoSpaceLeft() {
if (spaceLeft() != 0) {
throw new IllegalStateException(
"Did not write as much data as expected.");
}
}
/**
* If you create a CodedOutputStream around a simple flat array, you must
* not attempt to write more bytes than the array has space. Otherwise,
* this exception will be thrown.
*/
public static class OutOfSpaceException extends IOException {
private static final long serialVersionUID = -6947486886997889499L;
OutOfSpaceException() {
super("CodedOutputStream was writing to a flat byte array and ran " +
"out of space.");
}
}
/** Write a single byte. */
public void writeRawByte(final byte value) throws IOException {
if (position == limit) {
refreshBuffer();
}
buffer[position++] = value;
}
/** Write a single byte, represented by an integer value. */
public void writeRawByte(final int value) throws IOException {
writeRawByte((byte) value);
}
/** Write an array of bytes. */
public void writeRawBytes(final byte[] value) throws IOException {
writeRawBytes(value, 0, value.length);
}
/** Write part of an array of bytes. */
public void writeRawBytes(final byte[] value, int offset, int length)
throws IOException {
if (limit - position >= length) {
// We have room in the current buffer.
System.arraycopy(value, offset, buffer, position, length);
position += length;
} else {
// Write extends past current buffer. Fill the rest of this buffer and
// flush.
final int bytesWritten = limit - position;
System.arraycopy(value, offset, buffer, position, bytesWritten);
offset += bytesWritten;
length -= bytesWritten;
position = limit;
refreshBuffer();
// Now deal with the rest.
// Since we have an output stream, this is our buffer
// and buffer offset == 0
if (length <= limit) {
// Fits in new buffer.
System.arraycopy(value, offset, buffer, 0, length);
position = length;
} else {
// Write is very big. Let's do it all at once.
output.write(value, offset, length);
}
}
}
/** Encode and write a tag. */
public void writeTag(final int fieldNumber, final int wireType)
throws IOException {
writeRawVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
/** Compute the number of bytes that would be needed to encode a tag. */
public static int computeTagSize(final int fieldNumber) {
return computeRawVarint32Size(WireFormat.makeTag(fieldNumber, 0));
}
/**
* Encode and write a varint. {@code value} is treated as
* unsigned, so it won't be sign-extended if negative.
*/
public void writeRawVarint32(int value) throws IOException {
while (true) {
if ((value & ~0x7F) == 0) {
writeRawByte(value);
return;
} else {
writeRawByte((value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
/**
* Compute the number of bytes that would be needed to encode a varint.
* {@code value} is treated as unsigned, so it won't be sign-extended if
* negative.
*/
public static int computeRawVarint32Size(final int value) {
if ((value & (0xffffffff << 7)) == 0) return 1;
if ((value & (0xffffffff << 14)) == 0) return 2;
if ((value & (0xffffffff << 21)) == 0) return 3;
if ((value & (0xffffffff << 28)) == 0) return 4;
return 5;
}
/** Encode and write a varint. */
public void writeRawVarint64(long value) throws IOException {
while (true) {
if ((value & ~0x7FL) == 0) {
writeRawByte((int)value);
return;
} else {
writeRawByte(((int)value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
/** Compute the number of bytes that would be needed to encode a varint. */
public static int computeRawVarint64Size(final long value) {
if ((value & (0xffffffffffffffffL << 7)) == 0) return 1;
if ((value & (0xffffffffffffffffL << 14)) == 0) return 2;
if ((value & (0xffffffffffffffffL << 21)) == 0) return 3;
if ((value & (0xffffffffffffffffL << 28)) == 0) return 4;
if ((value & (0xffffffffffffffffL << 35)) == 0) return 5;
if ((value & (0xffffffffffffffffL << 42)) == 0) return 6;
if ((value & (0xffffffffffffffffL << 49)) == 0) return 7;
if ((value & (0xffffffffffffffffL << 56)) == 0) return 8;
if ((value & (0xffffffffffffffffL << 63)) == 0) return 9;
return 10;
}
/** Write a little-endian 32-bit integer. */
public void writeRawLittleEndian32(final int value) throws IOException {
writeRawByte((value ) & 0xFF);
writeRawByte((value >> 8) & 0xFF);
writeRawByte((value >> 16) & 0xFF);
writeRawByte((value >> 24) & 0xFF);
}
public static final int LITTLE_ENDIAN_32_SIZE = 4;
/** Write a little-endian 64-bit integer. */
public void writeRawLittleEndian64(final long value) throws IOException {
writeRawByte((int)(value ) & 0xFF);
writeRawByte((int)(value >> 8) & 0xFF);
writeRawByte((int)(value >> 16) & 0xFF);
writeRawByte((int)(value >> 24) & 0xFF);
writeRawByte((int)(value >> 32) & 0xFF);
writeRawByte((int)(value >> 40) & 0xFF);
writeRawByte((int)(value >> 48) & 0xFF);
writeRawByte((int)(value >> 56) & 0xFF);
}
public static final int LITTLE_ENDIAN_64_SIZE = 8;
/**
* Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers
* into values that can be efficiently encoded with varint. (Otherwise,
* negative values must be sign-extended to 64 bits to be varint encoded,
* thus always taking 10 bytes on the wire.)
*
* @param n A signed 32-bit integer.
* @return An unsigned 32-bit integer, stored in a signed int because
* Java has no explicit unsigned support.
*/
public static int encodeZigZag32(final int n) {
// Note: the right-shift must be arithmetic
return (n << 1) ^ (n >> 31);
}
/**
* Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
* into values that can be efficiently encoded with varint. (Otherwise,
* negative values must be sign-extended to 64 bits to be varint encoded,
* thus always taking 10 bytes on the wire.)
*
* @param n A signed 64-bit integer.
* @return An unsigned 64-bit integer, stored in a signed int because
* Java has no explicit unsigned support.
*/
public static long encodeZigZag64(final long n) {
// Note: the right-shift must be arithmetic
return (n << 1) ^ (n >> 63);
}
//START EXTRA
public void writeByteArray(int fieldNumber, byte[] value) throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeByteArrayNoTag(value);
}
public <T> void writeObject(int fieldNumber, T value, Schema<T> schema) throws IOException {
if(value==null)
return;
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
ComputedSizeOutput sc = computedSize;
int last = sc.getSize();
schema.writeTo(sc, value);
writeRawVarint32(sc.getSize() - last);
schema.writeTo(this, value);
}
public <T> void writeObject(int fieldNumber, T value, Class<T> typeClass) throws IOException {
if(value==null)
return;
ByteArrayNode node = current;
if(node==null)
node = computedSize.getRoot();
writeRawBytes(node.bytes);
writeRawBytes(node.next.bytes);
current = node.next.next;
}
public void writeByteArrayNoTag(byte[] value) throws IOException {
writeRawVarint32(value.length);
writeRawBytes(value);
}
public <T extends Message<T>> void writeMessageNoTag(T value) throws IOException {
Schema<T> schema = value.getSchema();
ComputedSizeOutput sc = computedSize;
int last = sc.getSize();
schema.writeTo(sc, value);
writeRawVarint32(sc.getSize() - last);
schema.writeTo(this, value);
}
//END EXTRA
}
|
fix write raw little endian
git-svn-id: 3d5cc44e79dd7516812cdf5c8b2c4439073f5b70@534 3b38d51a-9144-11de-8ad7-8b2c2f1e2016
|
protostuff-core/src/main/java/com/dyuproject/protostuff/CodedOutput.java
|
fix write raw little endian
|
<ide><path>rotostuff-core/src/main/java/com/dyuproject/protostuff/CodedOutput.java
<ide> buffer[offset++] = (byte)(value & 0xFF);
<ide> buffer[offset++] = (byte)(value >> 8 & 0xFF);
<ide> buffer[offset++] = (byte)(value >> 16 & 0xFF);
<del> buffer[offset++] = (byte)(value >> 24 & 0xFF);
<add> buffer[offset] = (byte)(value >> 24 & 0xFF);
<ide>
<ide> return LITTLE_ENDIAN_32_SIZE;
<ide> }
<ide> if(buffer.length - offset < LITTLE_ENDIAN_64_SIZE)
<ide> throw new IllegalArgumentException("buffer capacity not enough.");
<ide>
<del> buffer[offset++] = (byte)((int)value & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 8 & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 16 & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 24 & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 32 & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 40 & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 48 & 0xFF);
<del> buffer[offset++] = (byte)((int)value >> 56 & 0xFF);
<add> buffer[offset++] = (byte)(value & 0xFF);
<add> buffer[offset++] = (byte)(value >> 8 & 0xFF);
<add> buffer[offset++] = (byte)(value >> 16 & 0xFF);
<add> buffer[offset++] = (byte)(value >> 24 & 0xFF);
<add> buffer[offset++] = (byte)(value >> 32 & 0xFF);
<add> buffer[offset++] = (byte)(value >> 40 & 0xFF);
<add> buffer[offset++] = (byte)(value >> 48 & 0xFF);
<add> buffer[offset] = (byte)(value >> 56 & 0xFF);
<ide>
<ide> return LITTLE_ENDIAN_64_SIZE;
<ide> }
|
|
Java
|
apache-2.0
|
113ec5053e6215dccf7cf872704789c6504e9e80
| 0 |
venicegeo/pz-servicecontroller,venicegeo/pz-servicecontroller,venicegeo/pz-servicecontroller
|
/*******************************************************************************
* Copyright 2016, RadiantBlue Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.venice.piazza.servicecontroller.elasticsearch.accessors;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.venice.piazza.servicecontroller.messaging.ServiceMessageWorker;
import org.venice.piazza.servicecontroller.util.CoreServiceProperties;
import model.job.type.ServiceMetadataIngestJob;
import model.response.ErrorResponse;
import model.response.PiazzaResponse;
import model.service.metadata.Service;
import util.PiazzaLogger;
/**
*
* @author mlynum & Sonny.Saniev
*
*/
@Component
@DependsOn("coreInitDestroy")
public class ElasticSearchAccessor {
private String SERVICEMETADATA_INGEST_URL;
private String SERVICEMETADATA_UPDATE_URL;
private String SERVICEMETADATA_DELETE_URL;
private RestTemplate restTemplate = new RestTemplate();
@Autowired
private PiazzaLogger logger;
@Autowired
private CoreServiceProperties coreServiceProperties;
private final static Logger LOGGER = LoggerFactory.getLogger(ElasticSearchAccessor.class);
public ElasticSearchAccessor() {
}
@PostConstruct
private void initialize() {
SERVICEMETADATA_INGEST_URL = coreServiceProperties.getPzServicemetadataIngestUrl();
SERVICEMETADATA_UPDATE_URL = coreServiceProperties.getPzServicemetadataUpdateUrl();
SERVICEMETADATA_DELETE_URL = coreServiceProperties.getPzServicemetadataDeleteUrl();
logger.log("Search endpoint is " + SERVICEMETADATA_INGEST_URL, logger.DEBUG);
}
/**
* Dispatches request to elastic search for service updates
*
* @param service
* Service object
* @return PiazzaResponse
*/
public PiazzaResponse save(Service service) {
logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_INGEST_URL, logger.DEBUG);
return dispatchElasticSearch(service, SERVICEMETADATA_INGEST_URL);
}
/**
* Dispatches request to elastic search for service updates
*
* @param service
* Service object
* @return PiazzaResponse
*/
public PiazzaResponse update(Service service) {
logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_UPDATE_URL, logger.DEBUG);
return dispatchElasticSearch(service, SERVICEMETADATA_UPDATE_URL);
}
/**
* Dispatches request to elastic search for service updates
*
* @param service
* Service object
* @return PiazzaResponse
*/
public PiazzaResponse delete(Service service) {
logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_DELETE_URL, logger.DEBUG);
return dispatchElasticSearch(service, SERVICEMETADATA_DELETE_URL);
}
/**
* Private method to post requests to elastic search for
* registering / updating / deleting the service metadata.
*
* @param Service object
* @param url
* elastic search endpoints to post to
* @return PiazzaResponse response
*/
private PiazzaResponse dispatchElasticSearch(Service service, String url) {
try {
ServiceMetadataIngestJob job = new ServiceMetadataIngestJob();
job.setData(service);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<ServiceMetadataIngestJob> entity = new HttpEntity<ServiceMetadataIngestJob>(job, headers);
return restTemplate.postForObject(url, entity, PiazzaResponse.class);
} catch (Exception exception) {
logger.log(String.format("Could not Index ServiceMetaData to Service: %s", exception.getMessage()), PiazzaLogger.ERROR);
return new ErrorResponse(null, "Error connecting to ServiceMetadata Service: " + exception.getMessage(), "ServiceController");
}
}
}
|
mainServiceController/src/main/java/org/venice/piazza/servicecontroller/elasticsearch/accessors/ElasticSearchAccessor.java
|
/*******************************************************************************
* Copyright 2016, RadiantBlue Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.venice.piazza.servicecontroller.elasticsearch.accessors;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.venice.piazza.servicecontroller.messaging.ServiceMessageWorker;
import org.venice.piazza.servicecontroller.util.CoreServiceProperties;
import model.job.type.ServiceMetadataIngestJob;
import model.response.ErrorResponse;
import model.response.PiazzaResponse;
import model.service.metadata.Service;
import util.PiazzaLogger;
/**
*
* @author mlynum & Sonny.Saniev
*
*/
@Component
@DependsOn("coreInitDestroy")
public class ElasticSearchAccessor {
private String SERVICEMETADATA_INGEST_URL;
private String SERVICEMETADATA_UPDATE_URL;
private String SERVICEMETADATA_DELETE_URL;
private RestTemplate restTemplate = new RestTemplate();
@Autowired
private PiazzaLogger logger;
@Autowired
private CoreServiceProperties coreServiceProperties;
private final static Logger LOGGER = LoggerFactory.getLogger(ElasticSearchAccessor.class);
public ElasticSearchAccessor() {
}
@PostConstruct
private void initialize() {
SERVICEMETADATA_INGEST_URL = coreServiceProperties.getPzServicemetadataIngestUrl();
SERVICEMETADATA_UPDATE_URL = coreServiceProperties.getPzServicemetadataUpdateUrl();
SERVICEMETADATA_DELETE_URL = coreServiceProperties.getPzServicemetadataDeleteUrl();
logger.log("Search endpoint is " + SERVICEMETADATA_INGEST_URL, logger.DEBUG);
LOGGER.debug("Search endpoint is " + SERVICEMETADATA_INGEST_URL);
}
/**
* Dispatches request to elastic search for service updates
*
* @param service
* Service object
* @return PiazzaResponse
*/
public PiazzaResponse save(Service service) {
logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_INGEST_URL, logger.DEBUG);
LOGGER.debug("Search endpoint is " + service.getServiceId() + SERVICEMETADATA_INGEST_URL);
return dispatchElasticSearch(service, SERVICEMETADATA_INGEST_URL);
}
/**
* Dispatches request to elastic search for service updates
*
* @param service
* Service object
* @return PiazzaResponse
*/
public PiazzaResponse update(Service service) {
return dispatchElasticSearch(service, SERVICEMETADATA_UPDATE_URL);
}
/**
* Dispatches request to elastic search for service updates
*
* @param service
* Service object
* @return PiazzaResponse
*/
public PiazzaResponse delete(Service service) {
return dispatchElasticSearch(service, SERVICEMETADATA_DELETE_URL);
}
/**
* Private method to post requests to elastic search for
* registering / updating / deleting the service metadata.
*
* @param Service object
* @param url
* elastic search endpoints to post to
* @return PiazzaResponse response
*/
private PiazzaResponse dispatchElasticSearch(Service service, String url) {
try {
ServiceMetadataIngestJob job = new ServiceMetadataIngestJob();
job.setData(service);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<ServiceMetadataIngestJob> entity = new HttpEntity<ServiceMetadataIngestJob>(job, headers);
return restTemplate.postForObject(url, entity, PiazzaResponse.class);
} catch (Exception exception) {
logger.log(String.format("Could not Index ServiceMetaData to Service: %s", exception.getMessage()), PiazzaLogger.ERROR);
return new ErrorResponse(null, "Error connecting to ServiceMetadata Service: " + exception.getMessage(), "ServiceController");
}
}
}
|
Updated to add more debug
|
mainServiceController/src/main/java/org/venice/piazza/servicecontroller/elasticsearch/accessors/ElasticSearchAccessor.java
|
Updated to add more debug
|
<ide><path>ainServiceController/src/main/java/org/venice/piazza/servicecontroller/elasticsearch/accessors/ElasticSearchAccessor.java
<ide> SERVICEMETADATA_UPDATE_URL = coreServiceProperties.getPzServicemetadataUpdateUrl();
<ide> SERVICEMETADATA_DELETE_URL = coreServiceProperties.getPzServicemetadataDeleteUrl();
<ide> logger.log("Search endpoint is " + SERVICEMETADATA_INGEST_URL, logger.DEBUG);
<del> LOGGER.debug("Search endpoint is " + SERVICEMETADATA_INGEST_URL);
<ide>
<ide> }
<ide>
<ide> */
<ide> public PiazzaResponse save(Service service) {
<ide> logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_INGEST_URL, logger.DEBUG);
<del> LOGGER.debug("Search endpoint is " + service.getServiceId() + SERVICEMETADATA_INGEST_URL);
<ide> return dispatchElasticSearch(service, SERVICEMETADATA_INGEST_URL);
<ide> }
<ide>
<ide> * @return PiazzaResponse
<ide> */
<ide> public PiazzaResponse update(Service service) {
<add> logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_UPDATE_URL, logger.DEBUG);
<add>
<ide> return dispatchElasticSearch(service, SERVICEMETADATA_UPDATE_URL);
<ide> }
<ide>
<ide> * @return PiazzaResponse
<ide> */
<ide> public PiazzaResponse delete(Service service) {
<add> logger.log("Saving service " + service.getServiceId() + SERVICEMETADATA_DELETE_URL, logger.DEBUG);
<ide> return dispatchElasticSearch(service, SERVICEMETADATA_DELETE_URL);
<ide> }
<ide>
|
|
JavaScript
|
agpl-3.0
|
2bde01bd4547c080710e3a44af64a8a073823d4b
| 0 |
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
|
// ************************ Surveys *************************
FLOW.SurveySidebarView = Ember.View.extend({
surveyTitle:null,
surveyDescription: null,
surveyTypeControl:null,
surveySectorTypeControl:null,
init: function(){
this._super();
this.set('surveyTitle',FLOW.selectedControl.selectedSurvey.get('name'));
this.set('surveyDescription',FLOW.selectedControl.selectedSurvey.get('description'));
this.set('typeTypeControl',FLOW.selectedControl.selectedSurvey.get('pointType'));
// TODO imlement sector codes on surveys
//surveySectorTypeControl=FLOW.selectedControl.selectedSurvey.get('sector');
},
doSaveSurvey:function(){
var sgId=FLOW.selectedControl.selectedSurvey.get('id');
var survey=FLOW.store.find(FLOW.Survey, sgId);
survey.set('name',this.get('surveyTitle'));
survey.set('description',this.get('surveyDescription'));
survey.set('pointType',this.get('surveyTypeControl'));
FLOW.store.commit();
//FLOW.selectedControl.set('selectedSurvey',FLOW.store.find(FLOW.Survey, sgId));
},
doPreviewSurvey:function(){
console.log("TODO: implement preview survey");
},
doPublishSurvey:function(){
console.log("TODO: implement publish survey");
}
});
FLOW.QuestionGroupItemView = Ember.View.extend({
content: null, // question group content comes through binding in handlebars file
zeroItem: false,
renderView:false,
showQGDeletedialog:false,
showQGroupNameEditField:false,
questionGroupName:null,
amVisible: function() {
var selected = FLOW.selectedControl.get('selectedQuestionGroup');
if (selected) {
var isVis = (this.content.get('keyId') === FLOW.selectedControl.selectedQuestionGroup.get('keyId'));
return isVis;
} else {
return null;
}
}.property('FLOW.selectedControl.selectedQuestionGroup', 'content.keyId').cacheable(),
toggleVisibility: function() {
if (this.get('amVisible')) {
FLOW.selectedControl.set('selectedQuestionGroup', null);
} else {
FLOW.selectedControl.set('selectedQuestionGroup', this.content);
}
},
doQGroupNameEdit: function() {
this.set('questionGroupName',this.content.get('code'));
this.set('showQGroupNameEditField',true);
},
// fired when 'save' is clicked while showing edit group name field. Saves the new group name
saveQuestionGroupNameEdit: function() {
var qgId=this.content.get('id');
var questionGroup=FLOW.store.find(FLOW.QuestionGroup, qgId);
questionGroup.set('code',this.get('questionGroupName'));
FLOW.store.commit();
this.set('showQGroupNameEditField',false);
},
// fired when 'cancel' is clicked while showing edit group name field. Cancels the edit.
cancelQuestionGroupNameEdit: function() {
this.set('questionGroupName',null);
this.set('showQGroupNameEditField',false);
},
// true if one question group has been selected for Move
oneSelectedForMove: function() {
var selectedForMove = FLOW.selectedControl.get('selectedForMoveQuestionGroup');
if (selectedForMove) {
return true;
} else {
return false;
}
}.property('FLOW.selectedControl.selectedForMoveQuestionGroup'),
// true if one question group has been selected for Copy
oneSelectedForCopy: function() {
var selectedForCopy = FLOW.selectedControl.get('selectedForCopyQuestionGroup');
if (selectedForCopy) {
return true;
} else {
return false;
}
}.property('FLOW.selectedControl.selectedForCopyQuestionGroup'),
// show delete QGroup dialog
showQGroupDeletedialog:function(){
this.set('showQGDeletedialog',true);
},
// cancel question group delete
cancelQGroupDelete:function(){
this.set('showQGDeletedialog',false);
},
// execute group delete
doQGroupDelete:function(){
this.set('showQGDeletedialog',false);
var qgDeleteOrder = this.content.get('order');
var qgDeleteId = this.content.get('keyId');
// move items down
FLOW.store.filter(FLOW.QuestionGroup,function(data){return true;}).forEach(function(item){
var currentOrder=item.get('order');
if (currentOrder>qgDeleteOrder){
item.set('order',item.get('order')-1);
}
});
var questionGroup = FLOW.store.find(FLOW.QuestionGroup, qgDeleteId);
questionGroup.deleteRecord();
FLOW.store.commit();
},
// insert group
doInsertQuestionGroup: function(){
var insertAfterOrder;
if (this.get('zeroItem')) {
insertAfterOrder=0;
} else {
insertAfterOrder=this.content.get('order');
}
// move up to make space
FLOW.store.filter(FLOW.QuestionGroup,function(data){return true;}).forEach(function(item){
var currentOrder=item.get('order');
if (currentOrder>insertAfterOrder) {
item.set('order',item.get('order')+1);
}
});
// create new QuestionGroup item in the store
var newRec = FLOW.store.createRecord(FLOW.QuestionGroup,{
"code":"New group - please change name",
"order":insertAfterOrder+1,
"surveyId":FLOW.selectedControl.selectedSurvey.get('keyId')});
FLOW.store.commit();
},
// prepare for group copy. Shows 'copy to here' buttons
doQGroupCopy:function(){
FLOW.selectedControl.set('selectedForCopyQuestionGroup', this.content);
FLOW.selectedControl.set('selectedForMoveQuestionGroup', null);
},
// cancel group copy
doQGroupCopyCancel:function(){
FLOW.selectedControl.set('selectedForCopyQuestionGroup', null);
},
// prepare for group move. Shows 'move here' buttons
doQGroupMove:function(){
FLOW.selectedControl.set('selectedForMoveQuestionGroup', this.content);
FLOW.selectedControl.set('selectedForCopyQuestionGroup', null);
},
// cancel group move
doQGroupMoveCancel:function(){
FLOW.selectedControl.set('selectedForMoveQuestionGroup', null);
},
// execture group move to selected location
doQGroupMoveHere:function(){
var selectedOrder = FLOW.selectedControl.selectedForMoveQuestionGroup.get('order');
var insertAfterOrder;
var movingUp=false;
if (this.get('zeroItem')) {insertAfterOrder=0;} else {insertAfterOrder=this.content.get('order');}
// moving to the same place => do nothing
if ((selectedOrder==insertAfterOrder)||(selectedOrder==(insertAfterOrder+1))){}
else {
// determine if the item is moving up or down
movingUp = (selectedOrder<insertAfterOrder);
FLOW.questionGroupControl.get('content').forEach(function(item){
var currentOrder=item.get('order');
// item moving up
if (movingUp) {
// if outside of change region, do not move
if ((currentOrder<selectedOrder) || (currentOrder>insertAfterOrder)){ }
// move moving item to right location
else if (currentOrder==selectedOrder) { item.set('order',insertAfterOrder); }
// move rest down
else { item.set('order',item.get('order')-1); }
}
// item moving down
else {
if ((currentOrder<=insertAfterOrder) || (currentOrder>selectedOrder)){ }
else if (currentOrder==selectedOrder) { item.set('order',insertAfterOrder+1); }
else { item.set('order',item.get('order')+1); }
}
}); // end of forEach
} // end of top else
FLOW.store.commit();
FLOW.selectedControl.set('selectedForMoveQuestionGroup', null);
},
// execute group copy to selected location
doQGroupCopyHere:function(){
var selectedOrder = FLOW.selectedControl.selectedForCopyQuestionGroup.get('order');
var insertAfterOrder;
if (this.get('zeroItem')) {insertAfterOrder=0;} else {insertAfterOrder=this.content.get('order');}
// move up to make space
FLOW.questionGroupControl.get('content').forEach(function(item){
var currentOrder=item.get('order');
if (currentOrder>insertAfterOrder) {
item.set('order',item.get('order')+1);
}
}); // end of forEach
// create copy of QuestionGroup item in the store
var newRec = FLOW.store.createRecord(FLOW.QuestionGroup,{
"description": FLOW.selectedControl.selectedForCopyQuestionGroup.get('description'),
"order":insertAfterOrder+1,
"code":FLOW.selectedControl.selectedForCopyQuestionGroup.get('code'),
"surveyId":FLOW.selectedControl.selectedForCopyQuestionGroup.get('surveyId'),
"displayName":FLOW.selectedControl.selectedForCopyQuestionGroup.get('displayName')});
FLOW.store.commit();
FLOW.selectedControl.set('selectedForCopyQuestionGroup', null);
}
});
FLOW.QuestionView = Ember.View.extend({
content:null,
questionName:null,
checkedMandatory: false,
checkedDependent: false,
checkedOptionMultiple:false,
checkedOptionOther:false,
selectedQuestionType:null,
selectedOptionEdit:null,
amOpenQuestion: function() {
var selected = FLOW.selectedControl.get('selectedQuestion');
if (selected) {
var isOpen = (this.content.get('keyId') == FLOW.selectedControl.selectedQuestion.get('keyId'));
return isOpen;
} else {
return false;
}
}.property('FLOW.selectedControl.selectedQuestion', 'content.keyId').cacheable(),
amOptionType:function() {
if (this.selectedQuestionType){ return (this.selectedQuestionType.get('value')=='option') ? true : false;}
else {return false;}
}.property('this.selectedQuestionType').cacheable(),
amNumberType:function() {
if (this.selectedQuestionType){ return (this.selectedQuestionType.get('value')=='number') ? true : false;}
else {return false;}
}.property('this.selectedQuestionType').cacheable(),
doEdit: function() {
FLOW.selectedControl.set('selectedQuestion', this.content);
this.set('questionName',FLOW.selectedControl.selectedQuestion.get('displayName'));
//FLOW.optionControl.set('editCopy',FLOW.optionControl.get('questionOptionsList'));
//TODO populate selected question type
//TODO populate tooltip
//TODO populate question options
//TODO populate help
//TODO populate translations
},
doCancelEditQuestion: function() {
FLOW.selectedControl.set('selectedQuestion', null);
console.log('canceling edit');
},
doSaveEditQuestion: function() {
},
doCopy: function() {
console.log("doing doDuplicate");
},
doMove: function() {
console.log("doing doMove");
},
doDelete: function() {
console.log("doing doDelete");
}
});
FLOW.SavingQuestionGroupsView = Ember.View.extend({
showQGSavingDialogBool:false,
showQGSavingDialog:function(){
if (FLOW.questionGroupControl.get('allRecordsSaved')){
this.set('showQGSavingDialogBool', false)
} else {
this.set('showQGSavingDialogBool', true)
}
}.observes('FLOW.questionGroupControl.allRecordsSaved')
});
|
Dashboard/app/js/lib/views/survey-details-views.js
|
// ************************ Surveys *************************
FLOW.SurveySidebarView = Ember.View.extend({
surveyTitle:null,
surveyDescription: null,
surveyTypeControl:null,
surveySectorTypeControl:null,
init: function(){
this._super();
this.set('surveyTitle',FLOW.selectedControl.selectedSurvey.get('name'));
this.set('surveyDescription',FLOW.selectedControl.selectedSurvey.get('description'));
this.set('typeTypeControl',FLOW.selectedControl.selectedSurvey.get('pointType'));
// TODO imlement sector codes on surveys
//surveySectorTypeControl=FLOW.selectedControl.selectedSurvey.get('sector');
},
doSaveSurvey:function(){
var sgId=FLOW.selectedControl.selectedSurvey.get('id');
var survey=FLOW.store.find(FLOW.Survey, sgId);
survey.set('name',this.get('surveyTitle'));
survey.set('description',this.get('surveyDescription'));
survey.set('pointType',this.get('surveyTypeControl'));
FLOW.store.commit();
//FLOW.selectedControl.set('selectedSurvey',FLOW.store.find(FLOW.Survey, sgId));
},
doPreviewSurvey:function(){
console.log("TODO: implement preview survey");
},
doPublishSurvey:function(){
console.log("TODO: implement publish survey");
}
});
FLOW.QuestionGroupItemView = Ember.View.extend({
content: null, // question group content comes through binding in handlebars file
zeroItem: false,
renderView:false,
showQGDeletedialog:false,
showQGroupNameEditField:false,
questionGroupName:null,
amVisible: function() {
var selected = FLOW.selectedControl.get('selectedQuestionGroup');
if (selected) {
var isVis = (this.content.get('keyId') === FLOW.selectedControl.selectedQuestionGroup.get('keyId'));
return isVis;
} else {
return null;
}
}.property('FLOW.selectedControl.selectedQuestionGroup', 'content.keyId').cacheable(),
toggleVisibility: function() {
if (this.get('amVisible')) {
FLOW.selectedControl.set('selectedQuestionGroup', null);
} else {
FLOW.selectedControl.set('selectedQuestionGroup', this.content);
}
},
doQGroupNameEdit: function() {
this.set('questionGroupName',this.content.get('name'));
this.set('showQGroupNameEditField',true);
},
// fired when 'save' is clicked while showing edit group name field. Saves the new group name
saveQuestionGroupNameEdit: function() {
var qgId=this.content.get('id');
var questionGroup=FLOW.store.find(FLOW.QuestionGroup, qgId);
questionGroup.set('code',this.get('questionGroupName'));
FLOW.store.commit();
this.set('showQGroupNameEditField',false);
},
// fired when 'cancel' is clicked while showing edit group name field. Cancels the edit.
cancelQuestionGroupNameEdit: function() {
this.set('questionGroupName',null);
this.set('showQGroupNameEditField',false);
},
// true if one question group has been selected for Move
oneSelectedForMove: function() {
var selectedForMove = FLOW.selectedControl.get('selectedForMoveQuestionGroup');
if (selectedForMove) {
return true;
} else {
return false;
}
}.property('FLOW.selectedControl.selectedForMoveQuestionGroup'),
// true if one question group has been selected for Copy
oneSelectedForCopy: function() {
var selectedForCopy = FLOW.selectedControl.get('selectedForCopyQuestionGroup');
if (selectedForCopy) {
return true;
} else {
return false;
}
}.property('FLOW.selectedControl.selectedForCopyQuestionGroup'),
// show delete QGroup dialog
showQGroupDeletedialog:function(){
this.set('showQGDeletedialog',true);
},
// cancel question group delete
cancelQGroupDelete:function(){
this.set('showQGDeletedialog',false);
},
// execute group delete
doQGroupDelete:function(){
this.set('showQGDeletedialog',false);
var qgDeleteOrder = this.content.get('order');
var qgDeleteId = this.content.get('keyId');
// move items down
FLOW.store.filter(FLOW.QuestionGroup,function(data){return true;}).forEach(function(item){
var currentOrder=item.get('order');
if (currentOrder>qgDeleteOrder){
item.set('order',item.get('order')-1);
}
});
var questionGroup = FLOW.store.find(FLOW.QuestionGroup, qgDeleteId);
questionGroup.deleteRecord();
FLOW.store.commit();
},
// insert group
doInsertQuestionGroup: function(){
var insertAfterOrder;
if (this.get('zeroItem')) {
insertAfterOrder=0;
} else {
insertAfterOrder=this.content.get('order');
}
// move up to make space
FLOW.store.filter(FLOW.QuestionGroup,function(data){return true;}).forEach(function(item){
var currentOrder=item.get('order');
if (currentOrder>insertAfterOrder) {
item.set('order',item.get('order')+1);
}
});
// create new QuestionGroup item in the store
var newRec = FLOW.store.createRecord(FLOW.QuestionGroup,{
"code":"New group - please change name",
"order":insertAfterOrder+1,
"surveyId":FLOW.selectedControl.selectedSurvey.get('keyId')});
FLOW.store.commit();
},
// prepare for group copy. Shows 'copy to here' buttons
doQGroupCopy:function(){
FLOW.selectedControl.set('selectedForCopyQuestionGroup', this.content);
FLOW.selectedControl.set('selectedForMoveQuestionGroup', null);
},
// cancel group copy
doQGroupCopyCancel:function(){
FLOW.selectedControl.set('selectedForCopyQuestionGroup', null);
},
// prepare for group move. Shows 'move here' buttons
doQGroupMove:function(){
FLOW.selectedControl.set('selectedForMoveQuestionGroup', this.content);
FLOW.selectedControl.set('selectedForCopyQuestionGroup', null);
},
// cancel group move
doQGroupMoveCancel:function(){
FLOW.selectedControl.set('selectedForMoveQuestionGroup', null);
},
// execture group move to selected location
doQGroupMoveHere:function(){
var selectedOrder = FLOW.selectedControl.selectedForMoveQuestionGroup.get('order');
var insertAfterOrder;
var movingUp=false;
if (this.get('zeroItem')) {insertAfterOrder=0;} else {insertAfterOrder=this.content.get('order');}
// moving to the same place => do nothing
if ((selectedOrder==insertAfterOrder)||(selectedOrder==(insertAfterOrder+1))){}
else {
// determine if the item is moving up or down
movingUp = (selectedOrder<insertAfterOrder);
FLOW.questionGroupControl.get('content').forEach(function(item){
var currentOrder=item.get('order');
// item moving up
if (movingUp) {
// if outside of change region, do not move
if ((currentOrder<selectedOrder) || (currentOrder>insertAfterOrder)){ }
// move moving item to right location
else if (currentOrder==selectedOrder) { item.set('order',insertAfterOrder); }
// move rest down
else { item.set('order',item.get('order')-1); }
}
// item moving down
else {
if ((currentOrder<=insertAfterOrder) || (currentOrder>selectedOrder)){ }
else if (currentOrder==selectedOrder) { item.set('order',insertAfterOrder+1); }
else { item.set('order',item.get('order')+1); }
}
}); // end of forEach
} // end of top else
FLOW.store.commit();
FLOW.selectedControl.set('selectedForMoveQuestionGroup', null);
},
// execute group copy to selected location
doQGroupCopyHere:function(){
var selectedOrder = FLOW.selectedControl.selectedForCopyQuestionGroup.get('order');
var insertAfterOrder;
if (this.get('zeroItem')) {insertAfterOrder=0;} else {insertAfterOrder=this.content.get('order');}
// move up to make space
FLOW.questionGroupControl.get('content').forEach(function(item){
var currentOrder=item.get('order');
if (currentOrder>insertAfterOrder) {
item.set('order',item.get('order')+1);
}
}); // end of forEach
// create copy of QuestionGroup item in the store
var newRec = FLOW.store.createRecord(FLOW.QuestionGroup,{
"description": FLOW.selectedControl.selectedForCopyQuestionGroup.get('description'),
"order":insertAfterOrder+1,
"code":FLOW.selectedControl.selectedForCopyQuestionGroup.get('code'),
"surveyId":FLOW.selectedControl.selectedForCopyQuestionGroup.get('surveyId'),
"displayName":FLOW.selectedControl.selectedForCopyQuestionGroup.get('displayName')});
FLOW.store.commit();
FLOW.selectedControl.set('selectedForCopyQuestionGroup', null);
}
});
FLOW.QuestionView = Ember.View.extend({
content:null,
questionName:null,
checkedMandatory: false,
checkedDependent: false,
checkedOptionMultiple:false,
checkedOptionOther:false,
selectedQuestionType:null,
selectedOptionEdit:null,
amOpenQuestion: function() {
var selected = FLOW.selectedControl.get('selectedQuestion');
if (selected) {
var isOpen = (this.content.get('keyId') == FLOW.selectedControl.selectedQuestion.get('keyId'));
return isOpen;
} else {
return false;
}
}.property('FLOW.selectedControl.selectedQuestion', 'content.keyId').cacheable(),
amOptionType:function() {
if (this.selectedQuestionType){ return (this.selectedQuestionType.get('value')=='option') ? true : false;}
else {return false;}
}.property('this.selectedQuestionType').cacheable(),
amNumberType:function() {
if (this.selectedQuestionType){ return (this.selectedQuestionType.get('value')=='number') ? true : false;}
else {return false;}
}.property('this.selectedQuestionType').cacheable(),
doEdit: function() {
FLOW.selectedControl.set('selectedQuestion', this.content);
this.set('questionName',FLOW.selectedControl.selectedQuestion.get('displayName'));
//FLOW.optionControl.set('editCopy',FLOW.optionControl.get('questionOptionsList'));
//TODO populate selected question type
//TODO populate tooltip
//TODO populate question options
//TODO populate help
//TODO populate translations
},
doCancelEditQuestion: function() {
FLOW.selectedControl.set('selectedQuestion', null);
console.log('canceling edit');
},
doSaveEditQuestion: function() {
},
doCopy: function() {
console.log("doing doDuplicate");
},
doMove: function() {
console.log("doing doMove");
},
doDelete: function() {
console.log("doing doDelete");
}
});
FLOW.SavingQuestionGroupsView = Ember.View.extend({
showQGSavingDialogBool:false,
showQGSavingDialog:function(){
if (FLOW.questionGroupControl.get('allRecordsSaved')){
this.set('showQGSavingDialogBool', false)
} else {
this.set('showQGSavingDialogBool', true)
}
}.observes('FLOW.questionGroupControl.allRecordsSaved')
});
|
display code instead of name field in question group
|
Dashboard/app/js/lib/views/survey-details-views.js
|
display code instead of name field in question group
|
<ide><path>ashboard/app/js/lib/views/survey-details-views.js
<ide> },
<ide>
<ide> doQGroupNameEdit: function() {
<del> this.set('questionGroupName',this.content.get('name'));
<add> this.set('questionGroupName',this.content.get('code'));
<ide> this.set('showQGroupNameEditField',true);
<ide> },
<ide>
|
|
Java
|
apache-2.0
|
87f08e376d95e1cb27777858b402ccc8500d435b
| 0 |
3sidedcube/Android-LightningUi
|
package com.cube.storm.ui.fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.cube.storm.UiSettings;
import com.cube.storm.ui.R;
import com.cube.storm.ui.activity.StormActivity;
import com.cube.storm.ui.activity.StormInterface;
import com.cube.storm.ui.controller.adapter.StormListAdapter;
import com.cube.storm.ui.model.page.GridPage;
import com.cube.storm.ui.model.page.ListPage;
import com.cube.storm.ui.model.page.Page;
import com.cube.storm.ui.view.AdapterLinearLayout;
import lombok.Getter;
/**
* Static content fragment used to render an entire storm page into a single ViewGroup. Use this fragment
* when you want to embed some storm content into a scroll view, or any other type of view as a stub.
* <br/>
* Currently only works with {@link com.cube.storm.ui.model.page.ListPage} pages. {@link com.cube.storm.ui.model.page.GridPage} to be added.
*
* @author Callum Taylor
* @project LightningUi
*/
public class StormStaticFragment extends Fragment implements StormInterface
{
@Getter protected AdapterLinearLayout adapterView;
@Getter protected StormListAdapter adapter;
@Getter protected Page page;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(getLayoutResource(), container, false);
adapterView = (AdapterLinearLayout)v.findViewById(R.id.adapterview);
return v;
}
@Override public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
adapter = new StormListAdapter();
if (savedInstanceState == null)
{
if (getArguments().containsKey(StormActivity.EXTRA_URI))
{
String pageUri = getArguments().getString(StormActivity.EXTRA_URI);
loadPage(pageUri);
}
else
{
onLoadFail();
}
}
else
{
if (savedInstanceState.containsKey("page"))
{
page = (Page)savedInstanceState.get("page");
setAdapter();
setTitle();
}
if (savedInstanceState.containsKey("adapter"))
{
adapter.restoreState((StormListAdapter.AdapterState)savedInstanceState.getSerializable("adapter"));
}
}
}
public void setAdapter()
{
if (page instanceof ListPage)
{
adapter.setItems(page.getChildren());
}
else if (page instanceof GridPage)
{
adapter.setItems(((GridPage)page).getGrid().getChildren());
}
adapterView.setAdapter(adapter);
adapterView.notifyDataSetChanged();
}
public void setTitle()
{
if (page.getTitle() != null)
{
String title = UiSettings.getInstance().getTextProcessor().process(getPage().getTitle());
if (!TextUtils.isEmpty(title))
{
getActivity().setTitle(title);
}
}
}
@Override public int getLayoutResource()
{
return R.layout.static_page_fragment_view;
}
@Override public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (adapter != null)
{
outState.putSerializable("adapter", adapter.saveState());
}
if (page != null)
{
outState.putSerializable("page", page);
}
}
@Override public void loadPage(String pageUri)
{
page = UiSettings.getInstance().getViewBuilder().buildPage(Uri.parse(pageUri));
if (page != null)
{
setAdapter();
setTitle();
}
else
{
onLoadFail();
}
}
@Override public void onLoadFail()
{
Toast.makeText(getActivity(), "Failed to load page", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
|
library/src/main/java/com/cube/storm/ui/fragment/StormStaticFragment.java
|
package com.cube.storm.ui.fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.cube.storm.UiSettings;
import com.cube.storm.ui.R;
import com.cube.storm.ui.activity.StormActivity;
import com.cube.storm.ui.activity.StormInterface;
import com.cube.storm.ui.controller.adapter.StormListAdapter;
import com.cube.storm.ui.model.page.GridPage;
import com.cube.storm.ui.model.page.ListPage;
import com.cube.storm.ui.model.page.Page;
import com.cube.storm.ui.view.AdapterLinearLayout;
import lombok.Getter;
/**
* Static content fragment used to render an entire storm page into a single ViewGroup. Use this fragment
* when you want to embed some storm content into a scroll view, or any other type of view as a stub.
* <br/>
* Currently only works with {@link com.cube.storm.ui.model.page.ListPage} pages. {@link com.cube.storm.ui.model.page.GridPage} to be added.
*
* @author Callum Taylor
* @project LightningUi
*/
public class StormStaticFragment extends Fragment implements StormInterface
{
@Getter protected AdapterLinearLayout adapterView;
@Getter protected StormListAdapter adapter;
@Getter protected Page page;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(getLayoutResource(), container, false);
adapterView = (AdapterLinearLayout)v.findViewById(R.id.adapterview);
return v;
}
@Override public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
adapter = new StormListAdapter();
if (getArguments().containsKey(StormActivity.EXTRA_URI))
{
String pageUri = getArguments().getString(StormActivity.EXTRA_URI);
loadPage(pageUri);
}
else
{
onLoadFail();
return;
}
}
@Override public int getLayoutResource()
{
return R.layout.static_page_fragment_view;
}
@Override public void loadPage(String pageUri)
{
page = UiSettings.getInstance().getViewBuilder().buildPage(Uri.parse(pageUri));
if (page != null)
{
if (page instanceof ListPage)
{
adapter.setItems(page.getChildren());
}
else if (page instanceof GridPage)
{
adapter.setItems(((GridPage)page).getGrid().getChildren());
}
adapterView.setAdapter(adapter);
adapterView.notifyDataSetChanged();
}
else
{
onLoadFail();
}
}
@Override public void onLoadFail()
{
Toast.makeText(getActivity(), "Failed to load page", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
|
Added onsaveinstancestate for storm static fragment
|
library/src/main/java/com/cube/storm/ui/fragment/StormStaticFragment.java
|
Added onsaveinstancestate for storm static fragment
|
<ide><path>ibrary/src/main/java/com/cube/storm/ui/fragment/StormStaticFragment.java
<ide> import android.net.Uri;
<ide> import android.os.Bundle;
<ide> import android.support.v4.app.Fragment;
<add>import android.text.TextUtils;
<ide> import android.view.LayoutInflater;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide>
<ide> adapter = new StormListAdapter();
<ide>
<del> if (getArguments().containsKey(StormActivity.EXTRA_URI))
<add> if (savedInstanceState == null)
<ide> {
<del> String pageUri = getArguments().getString(StormActivity.EXTRA_URI);
<del> loadPage(pageUri);
<add> if (getArguments().containsKey(StormActivity.EXTRA_URI))
<add> {
<add> String pageUri = getArguments().getString(StormActivity.EXTRA_URI);
<add> loadPage(pageUri);
<add> }
<add> else
<add> {
<add> onLoadFail();
<add> }
<ide> }
<ide> else
<ide> {
<del> onLoadFail();
<del> return;
<add> if (savedInstanceState.containsKey("page"))
<add> {
<add> page = (Page)savedInstanceState.get("page");
<add> setAdapter();
<add> setTitle();
<add> }
<add>
<add> if (savedInstanceState.containsKey("adapter"))
<add> {
<add> adapter.restoreState((StormListAdapter.AdapterState)savedInstanceState.getSerializable("adapter"));
<add> }
<add> }
<add> }
<add>
<add> public void setAdapter()
<add> {
<add> if (page instanceof ListPage)
<add> {
<add> adapter.setItems(page.getChildren());
<add> }
<add> else if (page instanceof GridPage)
<add> {
<add> adapter.setItems(((GridPage)page).getGrid().getChildren());
<add> }
<add>
<add> adapterView.setAdapter(adapter);
<add> adapterView.notifyDataSetChanged();
<add> }
<add>
<add> public void setTitle()
<add> {
<add> if (page.getTitle() != null)
<add> {
<add> String title = UiSettings.getInstance().getTextProcessor().process(getPage().getTitle());
<add>
<add> if (!TextUtils.isEmpty(title))
<add> {
<add> getActivity().setTitle(title);
<add> }
<ide> }
<ide> }
<ide>
<ide> return R.layout.static_page_fragment_view;
<ide> }
<ide>
<add> @Override public void onSaveInstanceState(Bundle outState)
<add> {
<add> super.onSaveInstanceState(outState);
<add>
<add> if (adapter != null)
<add> {
<add> outState.putSerializable("adapter", adapter.saveState());
<add> }
<add>
<add> if (page != null)
<add> {
<add> outState.putSerializable("page", page);
<add> }
<add> }
<add>
<ide> @Override public void loadPage(String pageUri)
<ide> {
<ide> page = UiSettings.getInstance().getViewBuilder().buildPage(Uri.parse(pageUri));
<ide>
<ide> if (page != null)
<ide> {
<del> if (page instanceof ListPage)
<del> {
<del> adapter.setItems(page.getChildren());
<del> }
<del> else if (page instanceof GridPage)
<del> {
<del> adapter.setItems(((GridPage)page).getGrid().getChildren());
<del> }
<del>
<del> adapterView.setAdapter(adapter);
<del> adapterView.notifyDataSetChanged();
<add> setAdapter();
<add> setTitle();
<ide> }
<ide> else
<ide> {
|
|
Java
|
mit
|
99767d68824bbcf1fb99b38d742a69f1ea7e0fa0
| 0 |
rsandell/jenkins,oleg-nenashev/jenkins,rsandell/jenkins,ikedam/jenkins,damianszczepanik/jenkins,jenkinsci/jenkins,DanielWeber/jenkins,pjanouse/jenkins,daniel-beck/jenkins,v1v/jenkins,recena/jenkins,recena/jenkins,viqueen/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,ikedam/jenkins,v1v/jenkins,MarkEWaite/jenkins,viqueen/jenkins,DanielWeber/jenkins,v1v/jenkins,patbos/jenkins,ikedam/jenkins,rsandell/jenkins,viqueen/jenkins,v1v/jenkins,ikedam/jenkins,pjanouse/jenkins,MarkEWaite/jenkins,pjanouse/jenkins,MarkEWaite/jenkins,ikedam/jenkins,patbos/jenkins,viqueen/jenkins,viqueen/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,v1v/jenkins,DanielWeber/jenkins,damianszczepanik/jenkins,oleg-nenashev/jenkins,ikedam/jenkins,recena/jenkins,jenkinsci/jenkins,DanielWeber/jenkins,MarkEWaite/jenkins,viqueen/jenkins,pjanouse/jenkins,rsandell/jenkins,DanielWeber/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,rsandell/jenkins,daniel-beck/jenkins,daniel-beck/jenkins,daniel-beck/jenkins,pjanouse/jenkins,ikedam/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,patbos/jenkins,damianszczepanik/jenkins,patbos/jenkins,patbos/jenkins,DanielWeber/jenkins,pjanouse/jenkins,rsandell/jenkins,recena/jenkins,oleg-nenashev/jenkins,v1v/jenkins,recena/jenkins,MarkEWaite/jenkins,patbos/jenkins,jenkinsci/jenkins,oleg-nenashev/jenkins,damianszczepanik/jenkins,DanielWeber/jenkins,ikedam/jenkins,jenkinsci/jenkins,jenkinsci/jenkins,damianszczepanik/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,damianszczepanik/jenkins,oleg-nenashev/jenkins,recena/jenkins,daniel-beck/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,viqueen/jenkins,jenkinsci/jenkins,jenkinsci/jenkins,recena/jenkins,daniel-beck/jenkins,v1v/jenkins,patbos/jenkins,pjanouse/jenkins
|
/*
* The MIT License
*
* Copyright 2016 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import jenkins.model.DirectlyModifiableTopLevelItemGroup;
import static org.junit.Assert.*;
import org.awaitility.Awaitility;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockFolder;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.StaplerRequest;
import net.sf.json.JSONObject;
public class ViewDescriptorTest {
@Rule
public JenkinsRule r = new JenkinsRule();
/** Checks that {@link ViewDescriptor#doAutoCompleteCopyNewItemFrom} honors {@link DirectlyModifiableTopLevelItemGroup#canAdd}. */
@Test
public void canAdd() throws Exception {
MockFolder d1 = r.createFolder("d1");
d1.createProject(MockFolder.class, "sub");
d1.createProject(FreeStyleProject.class, "prj");
MockFolder d2 = r.jenkins.createProject(RestrictiveFolder.class, "d2");
assertContains(r.jenkins.getDescriptorByType(AllView.DescriptorImpl.class).doAutoCompleteCopyNewItemFrom("../d1/", d2), "../d1/prj");
}
@SuppressWarnings({"unchecked", "rawtypes"}) // the usual API mistakes
public static class RestrictiveFolder extends MockFolder {
public RestrictiveFolder(ItemGroup parent, String name) {
super(parent, name);
}
@Override
public boolean canAdd(TopLevelItem item) {
return item instanceof FreeStyleProject;
}
@TestExtension("canAdd") public static class DescriptorImpl extends TopLevelItemDescriptor {
@Override public TopLevelItem newInstance(ItemGroup parent, String name) {
return new RestrictiveFolder(parent, name);
}
}
}
private void assertContains(AutoCompletionCandidates c, String... values) {
assertEquals(new TreeSet<>(Arrays.asList(values)), new TreeSet<>(c.getValues()));
}
@Test
@Issue("JENKINS-60579")
public void invisiblePropertiesOnViewShoudBePersisted() throws Exception {
//GIVEN a listView that have an invisible property
ListView myListView = new ListView("Rock");
myListView.setRecurse(true);
myListView.setIncludeRegex(".*");
CustomInvisibleProperty invisibleProperty = new CustomInvisibleProperty();
invisibleProperty.setSomeProperty("You cannot see me.");
invisibleProperty.setView(myListView);
myListView.getProperties().add(invisibleProperty);
r.jenkins.addView(myListView);
assertEquals(r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class).getSomeProperty(),
"You cannot see me.");
//WHEN the users goes with "Edit View" on the configure page
JenkinsRule.WebClient webClient = r.createWebClient();
HtmlPage editViewPage = webClient.getPage(myListView, "configure");
//THEN the invisible property is not displayed on page
assertFalse("CustomInvisibleProperty should not be displayed on the View edition page UI.",
editViewPage.asText().contains("CustomInvisibleProperty"));
HtmlForm editViewForm = editViewPage.getFormByName("viewConfig");
editViewForm.getTextAreaByName("description").type("This list view is awesome !");
r.submit(editViewForm);
//Check that the description is updated on view
Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> webClient.getPage(myListView)
.asText()
.contains("This list view is awesome !"));
//AND THEN after View save, the invisible property is still persisted with the View.
assertNotNull("The CustomInvisibleProperty should be persisted on the View.",
r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class));
assertEquals(r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class).getSomeProperty(),
"You cannot see me.");
}
private static class CustomInvisibleProperty extends ViewProperty {
private String someProperty;
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public String getSomeProperty() {
return this.someProperty;
}
public CustomInvisibleProperty() {
this.someProperty = "undefined";
}
@Override
public ViewProperty reconfigure(StaplerRequest req, JSONObject form) {
return this;
}
@TestExtension
public static final class CustomInvisibleDescriptorImpl extends ViewPropertyDescriptor {
@Override
public String getId() {
return "CustomInvisibleDescriptorImpl";
}
@Override
public boolean isEnabledFor(View view) {
return true;
}
}
@TestExtension
public static final class CustomInvisibleDescriptorVisibilityFilterImpl extends DescriptorVisibilityFilter {
@Override
public boolean filter(Object context, Descriptor descriptor) {
return false;
}
}
}
}
|
test/src/test/java/hudson/model/ViewDescriptorTest.java
|
/*
* The MIT License
*
* Copyright 2016 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import jenkins.model.DirectlyModifiableTopLevelItemGroup;
import static org.junit.Assert.*;
import org.awaitility.Awaitility;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockFolder;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.StaplerRequest;
import net.sf.json.JSONObject;
public class ViewDescriptorTest {
@Rule
public JenkinsRule r = new JenkinsRule();
/** Checks that {@link ViewDescriptor#doAutoCompleteCopyNewItemFrom} honors {@link DirectlyModifiableTopLevelItemGroup#canAdd}. */
@Test
public void canAdd() throws Exception {
MockFolder d1 = r.createFolder("d1");
d1.createProject(MockFolder.class, "sub");
d1.createProject(FreeStyleProject.class, "prj");
MockFolder d2 = r.jenkins.createProject(RestrictiveFolder.class, "d2");
assertContains(r.jenkins.getDescriptorByType(AllView.DescriptorImpl.class).doAutoCompleteCopyNewItemFrom("../d1/", d2), "../d1/prj");
}
@SuppressWarnings({"unchecked", "rawtypes"}) // the usual API mistakes
public static class RestrictiveFolder extends MockFolder {
public RestrictiveFolder(ItemGroup parent, String name) {
super(parent, name);
}
@Override
public boolean canAdd(TopLevelItem item) {
return item instanceof FreeStyleProject;
}
@TestExtension("canAdd") public static class DescriptorImpl extends TopLevelItemDescriptor {
@Override public TopLevelItem newInstance(ItemGroup parent, String name) {
return new RestrictiveFolder(parent, name);
}
}
}
private void assertContains(AutoCompletionCandidates c, String... values) {
assertEquals(new TreeSet<>(Arrays.asList(values)), new TreeSet<>(c.getValues()));
}
@Test
@Issue("JENKINS-60579")
public void invisiblePropertiesOnViewShoudBePersisted() throws Exception {
//GIVEN a listView that have an invisible property
ListView myListView = new ListView("Rock");
myListView.setRecurse(true);
myListView.setIncludeRegex(".*");
CustomInvisibleProperty invisibleProperty = new CustomInvisibleProperty();
invisibleProperty.setSomeProperty("You cannot see me.");
invisibleProperty.setView(myListView);
myListView.getProperties().add(invisibleProperty);
r.jenkins.addView(myListView);
assertEquals(r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class).getSomeProperty(),
"You cannot see me.");
//WHEN the users goes with "Edit View" on the configure page
JenkinsRule.WebClient webClient = r.createWebClient();
HtmlPage editViewPage = webClient.getPage(myListView, "configure");
//THEN the invisible property is not displayed on page
assertFalse("CustomInvisibleProperty should not be displayed on the View edition page UI.",
editViewPage.asText().contains("CustomInvisibleProperty"));
HtmlForm editViewForm = editViewPage.getFormByName("viewConfig");
editViewForm.getTextAreaByName("description").type("This list view is awesome !");
r.submit(editViewForm);
//Check that the description is updated on view
Awaitility.waitAtMost(3, TimeUnit.SECONDS).until(() -> webClient.getPage(myListView)
.asText()
.contains("This list view is awesome !"));
//AND THEN after View save, the invisible property is still persisted with the View.
assertNotNull("The CustomInvisibleProperty should be persisted on the View.",
r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class));
assertEquals(r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class).getSomeProperty(),
"You cannot see me.");
}
private static class CustomInvisibleProperty extends ViewProperty {
private String someProperty;
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public String getSomeProperty() {
return this.someProperty;
}
public CustomInvisibleProperty() {
this.someProperty = "undefined";
}
@Override
public ViewProperty reconfigure(StaplerRequest req, JSONObject form) {
return this;
}
@TestExtension
public static final class CustomInvisibleDescriptorImpl extends ViewPropertyDescriptor {
@Override
public String getId() {
return "CustomInvisibleDescriptorImpl";
}
@Override
public boolean isEnabledFor(View view) {
return true;
}
}
@TestExtension
public static final class CustomInvisibleDescriptorVisibilityFilterImpl extends DescriptorVisibilityFilter {
@Override
public boolean filter(Object context, Descriptor descriptor) {
return false;
}
}
}
}
|
Increase timeout on test to stop flaking
|
test/src/test/java/hudson/model/ViewDescriptorTest.java
|
Increase timeout on test to stop flaking
|
<ide><path>est/src/test/java/hudson/model/ViewDescriptorTest.java
<ide> r.submit(editViewForm);
<ide>
<ide> //Check that the description is updated on view
<del> Awaitility.waitAtMost(3, TimeUnit.SECONDS).until(() -> webClient.getPage(myListView)
<add> Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> webClient.getPage(myListView)
<ide> .asText()
<ide> .contains("This list view is awesome !"));
<ide>
|
|
Java
|
apache-2.0
|
83a37fcf54c15ed2e19352aeab6e8ae49d3db51e
| 0 |
shaunstanislaus/Doradus,kod3r/Doradus,shaunstanislaus/Doradus,dell-oss/Doradus,kod3r/Doradus,dell-oss/Doradus,kod3r/Doradus,shaunstanislaus/Doradus,dell-oss/Doradus
|
/*
* Copyright (C) 2014 Dell, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dell.doradus.testprocessor.diff;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import com.dell.doradus.testprocessor.common.Utils;
public class Differ
{
private boolean m_ignoreWhiteSpace;
//TODO: private boolean m_ignoreEmptyLines;
private boolean m_ignoreCase;
public Differ(boolean ignoreWhiteSpace, boolean ignoreCase) {
m_ignoreWhiteSpace = ignoreWhiteSpace;
m_ignoreCase = ignoreCase;
}
public CompareResult compareFiles(String pathA, String pathB)
throws Exception
{
String textA = readTextFile(pathA);
String textB = readTextFile(pathB);
return compareStrings(textA, textB);
}
private String readTextFile(String path)
throws Exception
{
return new String(Files.readAllBytes(Paths.get(path)));
}
public CompareResult compareStrings(String textA, String textB)
throws Exception
{
List<DiffLine> diffLines = new ArrayList<DiffLine>();
boolean identical = true;
DiffResult diffResult = createLineDiffs(textA, textB);
int posB = 0;
for (int ind = 0; ind < diffResult.diffBlocks.size(); ind++)
{
DiffBlock diffBlock = diffResult.diffBlocks.get(ind);
for (; posB < diffBlock.insertStartB; posB++) {
diffLines.add(new DiffLine(ChangeType.UNCHANGED, diffResult.linesB[posB]));
}
int i = 0;
for (; i < Math.min(diffBlock.deleteCountA, diffBlock.insertCountB); i++) {
diffLines.add(new DiffLine(ChangeType.DELETED, diffResult.linesA[i + diffBlock.deleteStartA]));
identical = false;
}
i = 0;
for (; i < Math.min(diffBlock.deleteCountA, diffBlock.insertCountB); i++) {
diffLines.add(new DiffLine(ChangeType.INSERTED, diffResult.linesB[i + diffBlock.insertStartB]));
posB++;
identical = false;
}
if (diffBlock.deleteCountA > diffBlock.insertCountB)
{
for (; i < diffBlock.deleteCountA; i++) {
diffLines.add(new DiffLine(ChangeType.DELETED, diffResult.linesA[i + diffBlock.deleteStartA]));
identical = false;
}
}
else {
for (; i < diffBlock.insertCountB; i++) {
diffLines.add(new DiffLine(ChangeType.INSERTED, diffResult.linesB[i + diffBlock.insertStartB]));
posB++;
identical = false;
}
}
}
for (; posB < diffResult.linesB.length; posB++) {
diffLines.add(new DiffLine(ChangeType.UNCHANGED, diffResult.linesB[posB]));
}
return new CompareResult(diffLines, identical);
}
private DiffResult createLineDiffs(String textA, String textB)
throws Exception
{
String[] sourceLinesA = textA.split("[\\r\\n]+");
String[] sourceLinesB = textB.split("[\\r\\n]+");
Map<String, Integer> lineHash = new HashMap<String, Integer>();
int[] hashedLinesA = new int[sourceLinesA.length];
int[] hashedLinesB = new int[sourceLinesB.length];
buildLineHashes(lineHash, sourceLinesA, hashedLinesA);
buildLineHashes(lineHash, sourceLinesB, hashedLinesB);
boolean[] modificationsA = new boolean[sourceLinesA.length];
boolean[] modificationsB = new boolean[sourceLinesB.length];
buildModifications(
hashedLinesA, modificationsA,
hashedLinesB, modificationsB);
List<DiffBlock> diffBlocks = new ArrayList<DiffBlock>();
int nLinesA = hashedLinesA.length;
int nLinesB = hashedLinesB.length;
int posA = 0;
int posB = 0;
do {
while (posA < nLinesA && posB < nLinesB && !modificationsA[posA] && !modificationsB[posB]) {
posA++; posB++;
}
int beginA = posA;
int beginB = posB;
while (posA < nLinesA && modificationsA[posA]) ++posA;
while (posB < nLinesB && modificationsB[posB]) ++posB;
int deleteCount = posA - beginA;
int insertCount = posB - beginB;
if (deleteCount > 0 || insertCount > 0)
diffBlocks.add(new DiffBlock(beginA, deleteCount, beginB, insertCount));
}
while (posA < nLinesA && posB < nLinesB);
DiffResult result = new DiffResult(sourceLinesA, sourceLinesB, diffBlocks);
return result;
}
private void buildLineHashes(
Map<String, Integer> lineHash,
String[] sourceLines,
int[] hashedLines)
throws Exception
{
for (int i = 0; i < sourceLines.length; i++)
{
String line = sourceLines[i];
if (m_ignoreWhiteSpace) line = line.trim();
if (m_ignoreCase) line = line.toLowerCase();
if (lineHash.containsKey(line)) {
hashedLines[i] = lineHash.get(line);
}
else {
hashedLines[i] = lineHash.size();
lineHash.put(line, lineHash.size());
}
}
}
private void buildModifications(
int[] hashedLinesA, boolean[] modificationsA,
int[] hashedLinesB, boolean[] modificationsB)
throws Exception
{
int n = hashedLinesA.length;
int m = hashedLinesB.length;
int max = m + n + 1;
int[] forwardDiagonal = new int[max + 1];
int[] reverseDiagonal = new int[max + 1];
buildModificationData(
hashedLinesA, modificationsA, 0, n,
hashedLinesB, modificationsB, 0, m,
forwardDiagonal, reverseDiagonal);
}
private void buildModificationData(
int[] hashedLinesA, boolean[] modificationsA, int startA, int endA,
int[] hashedLinesB, boolean[] modificationsB, int startB, int endB,
int[] forwardDiagonal,
int[] reverseDiagonal)
throws Exception
{
while (startA < endA && startB < endB && hashedLinesA[startA] == hashedLinesB[startB]) {
startA++; startB++;
}
while (startA < endA && startB < endB && hashedLinesA[endA - 1] == hashedLinesB[endB - 1]) {
endA--; endB--;
}
int lengthA = endA - startA;
int lengthB = endB - startB;
if (lengthA > 0 && lengthB > 0)
{
EditLengthResult result = calculateEditLength(
hashedLinesA, startA, endA,
hashedLinesB, startB, endB,
forwardDiagonal, reverseDiagonal);
if (result.editLength <= 0)
return;
if (result.lastEdit == Edit.DELETE_RIGHT && result.startX - 1 > startA)
modificationsA[--result.startX] = true;
else if (result.lastEdit == Edit.INSERT_DOWN && result.startY - 1 > startB)
modificationsB[--result.startY] = true;
else if (result.lastEdit == Edit.DELETE_LEFT && result.endX < endA)
modificationsA[result.endX++] = true;
else if (result.lastEdit == Edit.INSERT_UP && result.endY < endB)
modificationsB[result.endY++] = true;
buildModificationData(
hashedLinesA, modificationsA, startA, result.startX,
hashedLinesB, modificationsB, startB, result.startY,
forwardDiagonal, reverseDiagonal);
buildModificationData(
hashedLinesA, modificationsA, result.endX, endA,
hashedLinesB, modificationsB, result.endY, endB,
forwardDiagonal, reverseDiagonal);
}
else if (lengthA > 0) // && lengthB = 0
{
for (int i = startA; i < endA; i++)
modificationsA[i] = true;
}
else if (lengthB > 0) // && lengthA = 0
{
for (int i = startB; i < endB; i++)
modificationsB[i] = true;
}
}
private EditLengthResult calculateEditLength(
int[] hashedLinesA, int startA, int endA,
int[] hashedLinesB, int startB, int endB,
int[] forwardDiagonal,
int[] reverseDiagonal)
throws Exception
{
if (hashedLinesA.length == 0 && hashedLinesB.length == 0)
return new EditLengthResult();
int n = endA - startA;
int m = endB - startB;
int max = m + n + 1;
int half = max / 2;
int delta = n - m;
boolean isDeltaEven = delta % 2 == 0;
forwardDiagonal[1 + half] = 0;
reverseDiagonal[1 + half] = n + 1;
Edit lastEdit;
for (int d = 0; d <= half; d++)
{
for (int k = -d; k <= d; k += 2)
{
int kIndex = k + half;
int x;
if (k == -d || (k != d && forwardDiagonal[kIndex - 1] < forwardDiagonal[kIndex + 1])) {
x = forwardDiagonal[kIndex + 1];
lastEdit = Edit.INSERT_DOWN;
}
else {
x = forwardDiagonal[kIndex - 1] + 1;
lastEdit = Edit.DELETE_RIGHT;
}
int y = x - k;
int startX = x;
int startY = y;
while (x < n && y < m && hashedLinesA[x + startA] == hashedLinesB[y + startB]) {
x += 1; y += 1;
}
forwardDiagonal[kIndex] = x;
if (!isDeltaEven && k - delta >= (-d + 1) && k - delta <= (d - 1))
{
int revKIndex = (k - delta) + half;
int revX = reverseDiagonal[revKIndex];
int revY = revX - k;
if (revX <= x && revY <= y)
{
EditLengthResult result = new EditLengthResult();
result.editLength = 2 * d - 1;
result.startX = startX + startA;
result.startY = startY + startB;
result.endX = x + startA;
result.endY = y + startB;
result.lastEdit = lastEdit;
return result;
}
}
}
for (int k = -d; k <= d; k += 2)
{
int kIndex = k + half;
int x;
if (k == -d || (k != d && reverseDiagonal[kIndex + 1] <= reverseDiagonal[kIndex - 1])) {
x = reverseDiagonal[kIndex + 1] - 1;
lastEdit = Edit.DELETE_LEFT;
}
else {
x = reverseDiagonal[kIndex - 1];
lastEdit = Edit.INSERT_UP;
}
int y = x - (k + delta);
int endX = x;
int endY = y;
while (x > 0 && y > 0 && hashedLinesA[startA + x - 1] == hashedLinesB[startB + y - 1]) {
x -= 1; y -= 1;
}
reverseDiagonal[kIndex] = x;
if (isDeltaEven && k + delta >= -d && k + delta <= d)
{
int forKIndex = (k + delta) + half;
int forX = forwardDiagonal[forKIndex];
int forY = forX - (k + delta);
if (forX >= x && forY >= y)
{
EditLengthResult result = new EditLengthResult();
result.editLength = 2 * d;
result.startX = x + startA;
result.startY = y + startB;
result.endX = endX + startA;
result.endY = endY + startB;
result.lastEdit = lastEdit;
return result;
}
}
}
}
throw new Exception("XDiffer.calculateEditLength: Should never get here");
}
}
|
test-processor/src/com/dell/doradus/testprocessor/diff/Differ.java
|
/*
* Copyright (C) 2014 Dell, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dell.doradus.testprocessor.diff;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import com.dell.doradus.testprocessor.common.Utils;
public class Differ
{
private boolean m_ignoreWhiteSpace;
//TODO: private boolean m_ignoreEmptyLines;
private boolean m_ignoreCase;
public Differ(boolean ignoreWhiteSpace, boolean ignoreCase) {
m_ignoreWhiteSpace = ignoreWhiteSpace;
m_ignoreCase = ignoreCase;
}
public CompareResult compareFiles(String pathA, String pathB)
throws Exception
{
String textA = readTextFile(pathA);
String textB = readTextFile(pathB);
return compareStrings(textA, textB);
}
private String readTextFile(String path)
throws Exception
{
return new String(Files.readAllBytes(Paths.get(path)));
}
public CompareResult compareStrings(String textA, String textB)
throws Exception
{
List<DiffLine> diffLines = new ArrayList<DiffLine>();
boolean identical = true;
DiffResult diffResult = createLineDiffs(textA, textB);
int posB = 0;
for (int ind = 0; ind < diffResult.diffBlocks.size(); ind++)
{
DiffBlock diffBlock = diffResult.diffBlocks.get(ind);
for (; posB < diffBlock.insertStartB; posB++) {
diffLines.add(new DiffLine(ChangeType.UNCHANGED, diffResult.linesB[posB]));
}
int i = 0;
for (; i < Math.min(diffBlock.deleteCountA, diffBlock.insertCountB); i++) {
diffLines.add(new DiffLine(ChangeType.DELETED, diffResult.linesA[i + diffBlock.deleteStartA]));
identical = false;
}
i = 0;
for (; i < Math.min(diffBlock.deleteCountA, diffBlock.insertCountB); i++) {
diffLines.add(new DiffLine(ChangeType.INSERTED, diffResult.linesB[i + diffBlock.insertStartB]));
posB++;
identical = false;
}
if (diffBlock.deleteCountA > diffBlock.insertCountB)
{
for (; i < diffBlock.deleteCountA; i++) {
diffLines.add(new DiffLine(ChangeType.DELETED, diffResult.linesA[i + diffBlock.deleteStartA]));
identical = false;
}
}
else {
for (; i < diffBlock.insertCountB; i++) {
diffLines.add(new DiffLine(ChangeType.INSERTED, diffResult.linesB[i + diffBlock.insertStartB]));
posB++;
identical = false;
}
}
}
for (; posB < diffResult.linesB.length; posB++) {
diffLines.add(new DiffLine(ChangeType.UNCHANGED, diffResult.linesB[posB]));
}
return new CompareResult(diffLines, identical);
}
private DiffResult createLineDiffs(String textA, String textB)
throws Exception
{
String[] sourceLinesA = textA.split(Utils.EOL);
String[] sourceLinesB = textB.split(Utils.EOL);
Map<String, Integer> lineHash = new HashMap<String, Integer>();
int[] hashedLinesA = new int[sourceLinesA.length];
int[] hashedLinesB = new int[sourceLinesB.length];
buildLineHashes(lineHash, sourceLinesA, hashedLinesA);
buildLineHashes(lineHash, sourceLinesB, hashedLinesB);
boolean[] modificationsA = new boolean[sourceLinesA.length];
boolean[] modificationsB = new boolean[sourceLinesB.length];
buildModifications(
hashedLinesA, modificationsA,
hashedLinesB, modificationsB);
List<DiffBlock> diffBlocks = new ArrayList<DiffBlock>();
int nLinesA = hashedLinesA.length;
int nLinesB = hashedLinesB.length;
int posA = 0;
int posB = 0;
do {
while (posA < nLinesA && posB < nLinesB && !modificationsA[posA] && !modificationsB[posB]) {
posA++; posB++;
}
int beginA = posA;
int beginB = posB;
while (posA < nLinesA && modificationsA[posA]) ++posA;
while (posB < nLinesB && modificationsB[posB]) ++posB;
int deleteCount = posA - beginA;
int insertCount = posB - beginB;
if (deleteCount > 0 || insertCount > 0)
diffBlocks.add(new DiffBlock(beginA, deleteCount, beginB, insertCount));
}
while (posA < nLinesA && posB < nLinesB);
DiffResult result = new DiffResult(sourceLinesA, sourceLinesB, diffBlocks);
return result;
}
private void buildLineHashes(
Map<String, Integer> lineHash,
String[] sourceLines,
int[] hashedLines)
throws Exception
{
for (int i = 0; i < sourceLines.length; i++)
{
String line = sourceLines[i];
if (m_ignoreWhiteSpace) line = line.trim();
if (m_ignoreCase) line = line.toLowerCase();
if (lineHash.containsKey(line)) {
hashedLines[i] = lineHash.get(line);
}
else {
hashedLines[i] = lineHash.size();
lineHash.put(line, lineHash.size());
}
}
}
private void buildModifications(
int[] hashedLinesA, boolean[] modificationsA,
int[] hashedLinesB, boolean[] modificationsB)
throws Exception
{
int n = hashedLinesA.length;
int m = hashedLinesB.length;
int max = m + n + 1;
int[] forwardDiagonal = new int[max + 1];
int[] reverseDiagonal = new int[max + 1];
buildModificationData(
hashedLinesA, modificationsA, 0, n,
hashedLinesB, modificationsB, 0, m,
forwardDiagonal, reverseDiagonal);
}
private void buildModificationData(
int[] hashedLinesA, boolean[] modificationsA, int startA, int endA,
int[] hashedLinesB, boolean[] modificationsB, int startB, int endB,
int[] forwardDiagonal,
int[] reverseDiagonal)
throws Exception
{
while (startA < endA && startB < endB && hashedLinesA[startA] == hashedLinesB[startB]) {
startA++; startB++;
}
while (startA < endA && startB < endB && hashedLinesA[endA - 1] == hashedLinesB[endB - 1]) {
endA--; endB--;
}
int lengthA = endA - startA;
int lengthB = endB - startB;
if (lengthA > 0 && lengthB > 0)
{
EditLengthResult result = calculateEditLength(
hashedLinesA, startA, endA,
hashedLinesB, startB, endB,
forwardDiagonal, reverseDiagonal);
if (result.editLength <= 0)
return;
if (result.lastEdit == Edit.DELETE_RIGHT && result.startX - 1 > startA)
modificationsA[--result.startX] = true;
else if (result.lastEdit == Edit.INSERT_DOWN && result.startY - 1 > startB)
modificationsB[--result.startY] = true;
else if (result.lastEdit == Edit.DELETE_LEFT && result.endX < endA)
modificationsA[result.endX++] = true;
else if (result.lastEdit == Edit.INSERT_UP && result.endY < endB)
modificationsB[result.endY++] = true;
buildModificationData(
hashedLinesA, modificationsA, startA, result.startX,
hashedLinesB, modificationsB, startB, result.startY,
forwardDiagonal, reverseDiagonal);
buildModificationData(
hashedLinesA, modificationsA, result.endX, endA,
hashedLinesB, modificationsB, result.endY, endB,
forwardDiagonal, reverseDiagonal);
}
else if (lengthA > 0) // && lengthB = 0
{
for (int i = startA; i < endA; i++)
modificationsA[i] = true;
}
else if (lengthB > 0) // && lengthA = 0
{
for (int i = startB; i < endB; i++)
modificationsB[i] = true;
}
}
private EditLengthResult calculateEditLength(
int[] hashedLinesA, int startA, int endA,
int[] hashedLinesB, int startB, int endB,
int[] forwardDiagonal,
int[] reverseDiagonal)
throws Exception
{
if (hashedLinesA.length == 0 && hashedLinesB.length == 0)
return new EditLengthResult();
int n = endA - startA;
int m = endB - startB;
int max = m + n + 1;
int half = max / 2;
int delta = n - m;
boolean isDeltaEven = delta % 2 == 0;
forwardDiagonal[1 + half] = 0;
reverseDiagonal[1 + half] = n + 1;
Edit lastEdit;
for (int d = 0; d <= half; d++)
{
for (int k = -d; k <= d; k += 2)
{
int kIndex = k + half;
int x;
if (k == -d || (k != d && forwardDiagonal[kIndex - 1] < forwardDiagonal[kIndex + 1])) {
x = forwardDiagonal[kIndex + 1];
lastEdit = Edit.INSERT_DOWN;
}
else {
x = forwardDiagonal[kIndex - 1] + 1;
lastEdit = Edit.DELETE_RIGHT;
}
int y = x - k;
int startX = x;
int startY = y;
while (x < n && y < m && hashedLinesA[x + startA] == hashedLinesB[y + startB]) {
x += 1; y += 1;
}
forwardDiagonal[kIndex] = x;
if (!isDeltaEven && k - delta >= (-d + 1) && k - delta <= (d - 1))
{
int revKIndex = (k - delta) + half;
int revX = reverseDiagonal[revKIndex];
int revY = revX - k;
if (revX <= x && revY <= y)
{
EditLengthResult result = new EditLengthResult();
result.editLength = 2 * d - 1;
result.startX = startX + startA;
result.startY = startY + startB;
result.endX = x + startA;
result.endY = y + startB;
result.lastEdit = lastEdit;
return result;
}
}
}
for (int k = -d; k <= d; k += 2)
{
int kIndex = k + half;
int x;
if (k == -d || (k != d && reverseDiagonal[kIndex + 1] <= reverseDiagonal[kIndex - 1])) {
x = reverseDiagonal[kIndex + 1] - 1;
lastEdit = Edit.DELETE_LEFT;
}
else {
x = reverseDiagonal[kIndex - 1];
lastEdit = Edit.INSERT_UP;
}
int y = x - (k + delta);
int endX = x;
int endY = y;
while (x > 0 && y > 0 && hashedLinesA[startA + x - 1] == hashedLinesB[startB + y - 1]) {
x -= 1; y -= 1;
}
reverseDiagonal[kIndex] = x;
if (isDeltaEven && k + delta >= -d && k + delta <= d)
{
int forKIndex = (k + delta) + half;
int forX = forwardDiagonal[forKIndex];
int forY = forX - (k + delta);
if (forX >= x && forY >= y)
{
EditLengthResult result = new EditLengthResult();
result.editLength = 2 * d;
result.startX = x + startA;
result.startY = y + startB;
result.endX = endX + startA;
result.endY = endY + startB;
result.lastEdit = lastEdit;
return result;
}
}
}
}
throw new Exception("XDiffer.calculateEditLength: Should never get here");
}
}
|
Splitting into lines corrected
|
test-processor/src/com/dell/doradus/testprocessor/diff/Differ.java
|
Splitting into lines corrected
|
<ide><path>est-processor/src/com/dell/doradus/testprocessor/diff/Differ.java
<ide> private DiffResult createLineDiffs(String textA, String textB)
<ide> throws Exception
<ide> {
<del> String[] sourceLinesA = textA.split(Utils.EOL);
<del> String[] sourceLinesB = textB.split(Utils.EOL);
<del>
<add> String[] sourceLinesA = textA.split("[\\r\\n]+");
<add> String[] sourceLinesB = textB.split("[\\r\\n]+");
<add>
<ide> Map<String, Integer> lineHash = new HashMap<String, Integer>();
<ide>
<ide> int[] hashedLinesA = new int[sourceLinesA.length];
|
|
Java
|
mit
|
9194c49915ee0a0e3fb1e22242d6fbc505ad89e3
| 0 |
chennanni/the-brave-rats
|
package com.north.cardspack;
import com.north.gamecore.Card;
public class Ambassador extends Card {
private final int NUMBER = 4;
private final String NAME = "Ambassador";
private final String DESCRIPTION ="If you win, it counts as 2 rounds.";
public Ambassador() {
super.setNumber(NUMBER);
super.setName(NAME);
super.setDescription(DESCRIPTION);
}
public void magic() {
// 4 – Ambassador: If you win, it counts as 2 rounds.
}
}
|
src/com/north/cardspack/Ambassador.java
|
package com.north.cardspack;
public class Ambassador extends Card {
private final int NUMBER = 4;
private final String NAME = "Ambassador";
private final String DESCRIPTION ="If you win, it counts as 2 rounds.";
Ambassador() {
super.setNumber(NUMBER);
super.setName(NAME);
super.setDescription(DESCRIPTION);
}
public void magic() {
System.out.println("I'm a Ambassador, magic!");
}
}
|
Update Ambassador.java
|
src/com/north/cardspack/Ambassador.java
|
Update Ambassador.java
|
<ide><path>rc/com/north/cardspack/Ambassador.java
<ide> package com.north.cardspack;
<add>
<add>import com.north.gamecore.Card;
<ide>
<ide> public class Ambassador extends Card {
<ide> private final int NUMBER = 4;
<ide> private final String NAME = "Ambassador";
<ide> private final String DESCRIPTION ="If you win, it counts as 2 rounds.";
<ide>
<del> Ambassador() {
<add> public Ambassador() {
<ide> super.setNumber(NUMBER);
<ide> super.setName(NAME);
<ide> super.setDescription(DESCRIPTION);
<ide> }
<ide>
<ide> public void magic() {
<del> System.out.println("I'm a Ambassador, magic!");
<add> // 4 – Ambassador: If you win, it counts as 2 rounds.
<ide> }
<ide> }
|
|
Java
|
bsd-3-clause
|
ea101e5f47f559840c08568d17f3744c6f6d7882
| 0 |
FRCteam4909/2017-Steamworks
|
package org.usfirst.frc4909.STEAMWORKS.utils;
import org.usfirst.frc4909.STEAMWORKS.Robot;
import org.usfirst.frc4909.STEAMWORKS.PID.PIDController;
import org.usfirst.frc4909.STEAMWORKS.utils.Subsystem;
import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Timer;
public abstract class DrivetrainSubsystem extends Subsystem {
private boolean inversion = false;
private double rotateP = 0.00000;
private double rotateI = 0.00000;
private double rotateD = 0.00000;
private final PIDController rotatePID = new PIDController(rotateP, rotateI, rotateD,.5);
public abstract RobotDrive getRobotDrive();
public abstract AHRS getNavX();
public abstract double getLeftEncDistance();
public abstract double getRightEncDistance();
public void moveTank(){
double leftY = Robot.oi.getLeftDriveJoystick().getThresholdAxis(1, 0.15);
double rightY = Robot.oi.getRightDriveJoystick().getThresholdAxis(1, 0.15);
if(inversion)
this.getRobotDrive().tankDrive(-rightY, -leftY);
else
this.getRobotDrive().tankDrive(leftY, rightY);
}
public boolean getInversion(){
return inversion;
}
public void setInversion(boolean newInversion){
inversion = newInversion;
}
public void stop(){
this.getRobotDrive().drive(0, 0);
}
/**
* Rotate to a Given Angle using the NavX, and PID
* @param angle Angle in degrees
*/
public void rotateAngle(double angle, double rotateP, double rotateI, double rotateD){
// Default PID is 0.15, 0.0, 0.0
rotatePID.resetPID();
double targetTime=Timer.getFPGATimestamp();
while(Timer.getFPGATimestamp()-targetTime<.5){
rotatePID.atTarget=false;
rotatePID.changePIDGains(rotateP, rotateI, rotateD);
double currentAngle = this.getNavX().getYaw();
if(Math.abs(angle-currentAngle) > 180)
angle = angle + (currentAngle / Math.abs(currentAngle))*360;
this.getRobotDrive().arcadeDrive(0, rotatePID.calcPID(angle, currentAngle, 4));
if(!rotatePID.isDone())
targetTime=Timer.getFPGATimestamp();
}
}
}
|
src/org/usfirst/frc4909/STEAMWORKS/utils/DrivetrainSubsystem.java
|
package org.usfirst.frc4909.STEAMWORKS.utils;
import org.usfirst.frc4909.STEAMWORKS.Robot;
import org.usfirst.frc4909.STEAMWORKS.PID.PIDController;
import org.usfirst.frc4909.STEAMWORKS.utils.Subsystem;
import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Timer;
public abstract class DrivetrainSubsystem extends Subsystem {
private boolean inversion = false;
private double rotateP = 0.00000;
private double rotateI = 0.00000;
private double rotateD = 0.00000;
private final PIDController rotatePID = new PIDController(rotateP, rotateI, rotateD,.5);
public abstract RobotDrive getRobotDrive();
public abstract AHRS getNavX();
public abstract double getLeftEncDistance();
public abstract double getRightEncDistance();
public void moveTank(){
double leftY = Robot.oi.getLeftDriveJoystick().getThresholdAxis(1, 0.15);
double rightY = Robot.oi.getLeftDriveJoystick().getThresholdAxis(1, 0.15);
if(inversion)
this.getRobotDrive().tankDrive(-rightY, -leftY);
else
this.getRobotDrive().tankDrive(leftY, rightY);
}
public boolean getInversion(){
return inversion;
}
public void setInversion(boolean newInversion){
inversion = newInversion;
}
public void stop(){
this.getRobotDrive().drive(0, 0);
}
/**
* Rotate to a Given Angle using the NavX, and PID
* @param angle Angle in degrees
*/
public void rotateAngle(double angle, double rotateP, double rotateI, double rotateD){
// Default PID is 0.15, 0.0, 0.0
rotatePID.resetPID();
double targetTime=Timer.getFPGATimestamp();
while(Timer.getFPGATimestamp()-targetTime<.5){
rotatePID.atTarget=false;
rotatePID.changePIDGains(rotateP, rotateI, rotateD);
double currentAngle = this.getNavX().getYaw();
if(Math.abs(angle-currentAngle) > 180)
angle = angle + (currentAngle / Math.abs(currentAngle))*360;
this.getRobotDrive().arcadeDrive(0, rotatePID.calcPID(angle, currentAngle, 4));
if(!rotatePID.isDone())
targetTime=Timer.getFPGATimestamp();
}
}
}
|
Fix Teleop. Drive Code
|
src/org/usfirst/frc4909/STEAMWORKS/utils/DrivetrainSubsystem.java
|
Fix Teleop. Drive Code
|
<ide><path>rc/org/usfirst/frc4909/STEAMWORKS/utils/DrivetrainSubsystem.java
<ide>
<ide> public void moveTank(){
<ide> double leftY = Robot.oi.getLeftDriveJoystick().getThresholdAxis(1, 0.15);
<del> double rightY = Robot.oi.getLeftDriveJoystick().getThresholdAxis(1, 0.15);
<add> double rightY = Robot.oi.getRightDriveJoystick().getThresholdAxis(1, 0.15);
<ide>
<ide> if(inversion)
<ide> this.getRobotDrive().tankDrive(-rightY, -leftY);
|
|
Java
|
mit
|
9fa85555359b82fe3dc398ddb8f2dceed2b6f6c3
| 0 |
trustyuri/trustyuri-java,trustyuri/trustyuri-java
|
package ch.tkuhn.hashuri.rdf;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.ContextStatementImpl;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
public class RdfFileContent implements RDFHandler {
private Map<Value,Value> rdfEntityMap = new HashMap<>();
private RDFFormat originalFormat = null;
private List<Pair<String,String>> namespaces;
private List<Statement> statements;
public RdfFileContent(RDFFormat originalFormat) {
this.originalFormat = originalFormat;
}
@Override
public void startRDF() throws RDFHandlerException {
namespaces = new ArrayList<>();
statements = new ArrayList<>();
}
@Override
public void endRDF() throws RDFHandlerException {
}
@Override
public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
namespaces.add(Pair.of(prefix, uri));
}
@Override
public void handleStatement(Statement st) throws RDFHandlerException {
Resource subj = (Resource) rdfEntityMap.get(st.getSubject());
if (subj == null) {
subj = st.getSubject();
rdfEntityMap.put(subj, subj);
}
URI pred = (URI) rdfEntityMap.get(st.getPredicate());
if (pred == null) {
pred = st.getPredicate();
rdfEntityMap.put(pred, pred);
}
Value obj = (Value) rdfEntityMap.get(st.getObject());
if (obj == null) {
obj = st.getObject();
rdfEntityMap.put(obj, obj);
}
Resource context = null;
if (st.getContext() == null) {
st = new StatementImpl(subj, pred, obj);
} else {
context = (Resource) rdfEntityMap.get(st.getContext());
if (context == null) {
context = st.getContext();
rdfEntityMap.put(context, context);
}
st = new ContextStatementImpl(subj, pred, obj, context);
}
statements.add(st);
}
@Override
public void handleComment(String comment) throws RDFHandlerException {
// Ignore comments
}
public List<Statement> getStatements() {
return statements;
}
public void propagate(RDFHandler handler) throws RDFHandlerException {
handler.startRDF();
for (Pair<String,String> ns : namespaces) {
handler.handleNamespace(ns.getLeft(), ns.getRight());
}
for (Statement st : statements) {
handler.handleStatement(st);
}
handler.endRDF();
}
public RDFFormat getOriginalFormat() {
return originalFormat;
}
}
|
src/main/java/ch/tkuhn/hashuri/rdf/RdfFileContent.java
|
package ch.tkuhn.hashuri.rdf;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.ContextStatementImpl;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
public class RdfFileContent implements RDFHandler {
static Map<Value,Value> rdfEntityMap = new HashMap<>();
private RDFFormat originalFormat = null;
private List<Pair<String,String>> namespaces;
private List<Statement> statements;
public RdfFileContent(RDFFormat originalFormat) {
this.originalFormat = originalFormat;
}
@Override
public void startRDF() throws RDFHandlerException {
namespaces = new ArrayList<>();
statements = new ArrayList<>();
}
@Override
public void endRDF() throws RDFHandlerException {
}
@Override
public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
namespaces.add(Pair.of(prefix, uri));
}
@Override
public void handleStatement(Statement st) throws RDFHandlerException {
Resource subj = (Resource) rdfEntityMap.get(st.getSubject());
if (subj == null) {
subj = st.getSubject();
rdfEntityMap.put(subj, subj);
}
URI pred = (URI) rdfEntityMap.get(st.getPredicate());
if (pred == null) {
pred = st.getPredicate();
rdfEntityMap.put(pred, pred);
}
Value obj = (Value) rdfEntityMap.get(st.getObject());
if (obj == null) {
obj = st.getObject();
rdfEntityMap.put(obj, obj);
}
Resource context = null;
if (st.getContext() == null) {
st = new StatementImpl(subj, pred, obj);
} else {
context = (Resource) rdfEntityMap.get(st.getContext());
if (context == null) {
context = st.getContext();
rdfEntityMap.put(context, context);
}
st = new ContextStatementImpl(subj, pred, obj, context);
}
statements.add(st);
}
@Override
public void handleComment(String comment) throws RDFHandlerException {
// Ignore comments
}
public List<Statement> getStatements() {
return statements;
}
public void propagate(RDFHandler handler) throws RDFHandlerException {
handler.startRDF();
for (Pair<String,String> ns : namespaces) {
handler.handleNamespace(ns.getLeft(), ns.getRight());
}
for (Statement st : statements) {
handler.handleStatement(st);
}
handler.endRDF();
}
public RDFFormat getOriginalFormat() {
return originalFormat;
}
}
|
Entity map should not be static
|
src/main/java/ch/tkuhn/hashuri/rdf/RdfFileContent.java
|
Entity map should not be static
|
<ide><path>rc/main/java/ch/tkuhn/hashuri/rdf/RdfFileContent.java
<ide>
<ide> public class RdfFileContent implements RDFHandler {
<ide>
<del> static Map<Value,Value> rdfEntityMap = new HashMap<>();
<add> private Map<Value,Value> rdfEntityMap = new HashMap<>();
<ide>
<ide> private RDFFormat originalFormat = null;
<ide> private List<Pair<String,String>> namespaces;
|
|
Java
|
apache-2.0
|
5b6a4f18c6b918c865a2556aa5d92ed0ed1cb238
| 0 |
virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,winhamwr/selenium
|
/*
Copyright 2011 WebDriver committers
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.ie;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.win32.StdCallLibrary;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.io.TemporaryFilesystem;
import org.openqa.selenium.net.PortProber;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class InternetExplorerDriverServer {
// Constantly reloading the DLL causes JVM crashes. Prefer a static field this one time.
private static IEServer lib = initializeLib();
private Pointer server;
private int port;
public InternetExplorerDriverServer(int port) {
this.port = port;
}
public URL getUrl() {
if (!lib.ServerIsRunning()) {
throw new WebDriverException("Server has not yet been started");
}
try {
return new URL("http://localhost:" + port);
} catch (MalformedURLException e) {
throw new WebDriverException(e);
}
}
public void start() {
if (lib.ServerIsRunning()) {
port = lib.GetServerPort();
return;
}
// TODO: Race. Need to lock across processes to avoid port being assigned
if (port == 0) {
port = PortProber.findFreePort();
}
server = lib.StartServer(port);
}
public void stop() {
if (lib != null) {
lib.StopServer(server);
}
}
private static synchronized IEServer initializeLib() {
File parentDir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("webdriver", "libs");
try {
FileHandler.copyResource(parentDir, InternetExplorerDriverServer.class, "IEDriver.dll");
} catch (IOException ioe) {
// TODO(simon): Delete this. Test code should not be in production code
try {
if (Boolean.getBoolean("webdriver.development")) {
String arch = System.getProperty("os.arch", "")
.contains("64") ? "x64" : "Win32";
List<String> sourcePaths = new ArrayList<String>();
sourcePaths.add("build\\cpp\\" + arch + "\\Debug");
sourcePaths.add("..\\build\\cpp\\" + arch + "\\Debug");
sourcePaths.add("..\\..\\build\\cpp\\" + arch + "\\Debug");
boolean copied = false;
for (String path : sourcePaths) {
File sourceFile = new File(path, "IEDriver.dll");
if (sourceFile.exists()) {
FileHandler.copy(sourceFile, new File(
parentDir, "IEDriver.dll"));
copied = true;
break;
}
}
if (!copied) {
throw new WebDriverException(
"Couldn't find IEDriver.dll: " + arch);
}
} else {
throw new WebDriverException(ioe);
}
} catch (IOException ioe2) {
throw new WebDriverException(ioe2);
}
}
System.setProperty("jna.library.path",
System.getProperty("jna.library.path", "")
+ File.pathSeparator + parentDir);
try {
return (IEServer) Native.loadLibrary("IEDriver", IEServer.class);
} catch (UnsatisfiedLinkError e) {
System.out.println("new File(\".\").getAbsolutePath() = "
+ new File(".").getAbsolutePath());
throw new WebDriverException(e);
}
}
private interface IEServer extends StdCallLibrary {
Pointer StartServer(int port);
void StopServer(Pointer server);
int GetServerPort();
boolean ServerIsRunning();
}
}
|
java/client/src/org/openqa/selenium/ie/InternetExplorerDriverServer.java
|
/*
Copyright 2011 WebDriver committers
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.ie;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.win32.StdCallLibrary;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.io.TemporaryFilesystem;
import org.openqa.selenium.net.PortProber;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class InternetExplorerDriverServer {
// Constantly reloading the DLL causes JVM crashes. Prefer a static field this one time.
private static IEServer lib = initializeLib();
private Pointer server;
private int port;
public InternetExplorerDriverServer(int port) {
this.port = port;
}
public URL getUrl() {
if (!lib.ServerIsRunning()) {
throw new WebDriverException("Server has not yet been started");
}
try {
return new URL("http://localhost:" + port);
} catch (MalformedURLException e) {
throw new WebDriverException(e);
}
}
public void start() {
if (lib.ServerIsRunning()) {
port = lib.GetServerPort();
return;
}
// TODO: Race. Need to lock across processes to avoid port being assigned
if (port == 0) {
port = PortProber.findFreePort();
}
server = lib.StartServer(port);
}
public void stop() {
if (lib != null) {
lib.StopServer(server);
}
}
private static IEServer initializeLib() {
File parentDir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("webdriver", "libs");
try {
FileHandler.copyResource(parentDir, InternetExplorerDriverServer.class, "IEDriver.dll");
} catch (IOException ioe) {
// TODO(simon): Delete this. Test code should not be in production code
try {
if (Boolean.getBoolean("webdriver.development")) {
String arch = System.getProperty("os.arch", "")
.contains("64") ? "x64" : "Win32";
List<String> sourcePaths = new ArrayList<String>();
sourcePaths.add("build\\cpp\\" + arch + "\\Debug");
sourcePaths.add("..\\build\\cpp\\" + arch + "\\Debug");
sourcePaths.add("..\\..\\build\\cpp\\" + arch + "\\Debug");
boolean copied = false;
for (String path : sourcePaths) {
File sourceFile = new File(path, "IEDriver.dll");
if (sourceFile.exists()) {
FileHandler.copy(sourceFile, new File(
parentDir, "IEDriver.dll"));
copied = true;
break;
}
}
if (!copied) {
throw new WebDriverException(
"Couldn't find IEDriver.dll: " + arch);
}
} else {
throw new WebDriverException(ioe);
}
} catch (IOException ioe2) {
throw new WebDriverException(ioe2);
}
}
System.setProperty("jna.library.path",
System.getProperty("jna.library.path", "")
+ File.pathSeparator + parentDir);
try {
return (IEServer) Native.loadLibrary("IEDriver", IEServer.class);
} catch (UnsatisfiedLinkError e) {
System.out.println("new File(\".\").getAbsolutePath() = "
+ new File(".").getAbsolutePath());
throw new WebDriverException(e);
}
}
private interface IEServer extends StdCallLibrary {
Pointer StartServer(int port);
void StopServer(Pointer server);
int GetServerPort();
boolean ServerIsRunning();
}
}
|
DanielWagnerHall: Lock on InternetExplorerDriverServer.class when initing the DLL, for added safety
git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@12802 07704840-8298-11de-bf8c-fd130f914ac9
|
java/client/src/org/openqa/selenium/ie/InternetExplorerDriverServer.java
|
DanielWagnerHall: Lock on InternetExplorerDriverServer.class when initing the DLL, for added safety
|
<ide><path>ava/client/src/org/openqa/selenium/ie/InternetExplorerDriverServer.java
<ide> }
<ide> }
<ide>
<del> private static IEServer initializeLib() {
<add> private static synchronized IEServer initializeLib() {
<ide> File parentDir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("webdriver", "libs");
<ide> try {
<ide> FileHandler.copyResource(parentDir, InternetExplorerDriverServer.class, "IEDriver.dll");
|
|
Java
|
mit
|
6e54fdd957d649707624ab20cab209b6019410f4
| 0 |
jotatoledo/Programmieren-WS16-17
|
package test.java.tessellation;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import main.java.tessellation.Board;
import main.java.tessellation.LineType;
import main.java.tessellation.Tile;
/**
* Unit test for {@linkplain Board}
* @author Jose Toledo Navarro
* @version 1.00
*/
public class BoardTest {
/**
* <pre>
* Empty board
*
* ------;------;------;
* ------;------;------;
* ------;------;------;
* ------;------;------;
* </pre>
*/
private static final Board EMPTY_BOARD = new Board();
/**
* <pre>
* Example in picture 9
*
* ------;GGY-Y-;----RR;
* ------;RGRGYY;GG----;
* --YGGY;G--RGR;-YY---;
* ------;---YY-;Y----Y;
* </pre>
*/
private static final Board VALID_BOARD = new Board();
/**
* <pre>
* Example in picture 10
*
* ------;-GGY-Y;RR----;
* ------;RGRGYY;GG----;
* Y--YGG;G--RGR;-YY---;
* ------;---YY-;YY----;
* </pre>
*/
private static final Board INVALID_BOARD = new Board();
/**
* Used to populate the general test cases
*/
public BoardTest() {
VALID_BOARD.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
VALID_BOARD.setTile(2, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.NONE, LineType.RED, LineType.RED }));
VALID_BOARD.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
VALID_BOARD.setTile(5, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
VALID_BOARD.setTile(6, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.YELLOW,
LineType.GREEN, LineType.GREEN, LineType.YELLOW }));
VALID_BOARD.setTile(7, new Tile(new LineType[] {
LineType.GREEN, LineType.NONE, LineType.NONE,
LineType.RED, LineType.GREEN, LineType.RED }));
VALID_BOARD.setTile(8, new Tile(new LineType[] {
LineType.NONE, LineType.YELLOW, LineType.YELLOW,
LineType.NONE, LineType.NONE, LineType.NONE }));
VALID_BOARD.setTile(10, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.YELLOW, LineType.YELLOW, LineType.NONE }));
VALID_BOARD.setTile(11, new Tile(new LineType[] {
LineType.YELLOW, LineType.NONE, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.YELLOW }));
INVALID_BOARD.setTile(1, new Tile(new LineType[] {
LineType.NONE, LineType.GREEN, LineType.GREEN,
LineType.YELLOW, LineType.NONE, LineType.YELLOW }));
INVALID_BOARD.setTile(2, new Tile(new LineType[] {
LineType.RED, LineType.RED, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
INVALID_BOARD.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
INVALID_BOARD.setTile(5, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
INVALID_BOARD.setTile(6, new Tile(new LineType[] {
LineType.YELLOW, LineType.NONE, LineType.NONE,
LineType.YELLOW, LineType.GREEN, LineType.GREEN }));
INVALID_BOARD.setTile(7, new Tile(new LineType[] {
LineType.GREEN, LineType.NONE, LineType.NONE,
LineType.RED, LineType.GREEN, LineType.RED }));
INVALID_BOARD.setTile(8, new Tile(new LineType[] {
LineType.NONE, LineType.YELLOW, LineType.YELLOW,
LineType.NONE, LineType.NONE, LineType.NONE }));
INVALID_BOARD.setTile(10, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.YELLOW, LineType.YELLOW, LineType.NONE }));
INVALID_BOARD.setTile(11, new Tile(new LineType[] {
LineType.YELLOW, LineType.YELLOW, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
}
@Test
public void testBoard() {
Board firstTest = new Board();
StringBuilder builder = new StringBuilder();
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertTrue(firstTest != null);
assertTrue(firstTest.isEmpty() == true);
assertThat(firstTest.toString(), is(builder.toString()));
}
@Test
public void testGetTile() {
Tile actualResult = null;
Tile expectedResult = null;
actualResult = VALID_BOARD.getTile(1);
expectedResult = new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE });
assertThat(actualResult.toString(), is(expectedResult.toString()));
actualResult = EMPTY_BOARD.getTile(5);
expectedResult = new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE });
assertThat(actualResult.toString(), is(expectedResult.toString()));
}
@Test
public void testSetTile() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
builder.append("------;GGY-Y-;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
builder.setLength(0);
builder.append("------;GGY-Y-;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testRemoveTile() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
builder.append("------;GGY-Y-;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
test.removeTile(4);
builder.setLength(0);
builder.append("------;GGY-Y-;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testIsEmpty() {
assertTrue(EMPTY_BOARD.isEmpty() == true);
assertTrue(INVALID_BOARD.isEmpty() == false);
assertTrue(VALID_BOARD.isEmpty() == false);
}
@Test
public void testRotateTileClockwise() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
test.rotateTileClockwise(1);
builder.append("------;-GGY-Y;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testRotateTileCounterClockwise() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
test.rotateTileCounterClockwise(1);
builder.append("------;GY-Y-G;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testGetNumberOfColors() {
Board test = new Board();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
assertTrue(test.getNumberOfColors() == 3);
test.removeTile(4);
assertTrue(test.getNumberOfColors() == 2);
assertTrue(EMPTY_BOARD.getNumberOfColors() == 0);
assertTrue(INVALID_BOARD.getNumberOfColors() == 3);
assertTrue(INVALID_BOARD.getNumberOfColors() == 3);
}
@Test
public void testIsValid() {
Board test = new Board();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
assertTrue(test.isValid() == true); //Example in code snippet 3
test.rotateTileClockwise(1);
assertTrue(test.isValid() == false); //Example in code snippet 3
assertTrue(EMPTY_BOARD.isValid() == true);
assertTrue(VALID_BOARD.isValid() == true);
assertTrue(INVALID_BOARD.isValid() == false);
}
@Test
public void testGetConnectedPathColor() {
Board test = new Board();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
assertTrue(test.getConnectedPathColor(new int[]{1, 4}) == LineType.YELLOW);
test.rotateTileClockwise(1);
assertTrue(test.getConnectedPathColor(new int[] {1, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {0, 3}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {1, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {1, 2, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4, 5, 7}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {8, 10, 11}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {8, 10, 11, 8}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {0, 3}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {1, 4}) == LineType.YELLOW);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {1, 4, 5}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {1, 2, 4}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4, 5, 7}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11}) == LineType.YELLOW);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11, 8}) == LineType.YELLOW);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {0, 3}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {1, 4}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {1, 2, 4}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7}) == LineType.GREEN);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4, 5, 7}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11}) == LineType.YELLOW);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11, 8}) == LineType.NONE);
}
@Test
public void testToString() {
StringBuilder builder = new StringBuilder();
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(EMPTY_BOARD.toString(), is(builder.toString()));
builder.setLength(0);
builder.append("------;-GGY-Y;RR----;\n");
builder.append("------;RGRGYY;GG----;\n");
builder.append("Y--YGG;G--RGR;-YY---;\n");
builder.append("------;---YY-;YY----;");
assertThat(INVALID_BOARD.toString(), is(builder.toString()));
builder.setLength(0);
builder.append("------;GGY-Y-;----RR;\n");
builder.append("------;RGRGYY;GG----;\n");
builder.append("--YGGY;G--RGR;-YY---;\n");
builder.append("------;---YY-;Y----Y;");
assertThat(VALID_BOARD.toString(), is(builder.toString()));
}
}
|
src/test/java/tessellation/BoardTest.java
|
package test.java.tessellation;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import main.java.tessellation.Board;
import main.java.tessellation.LineType;
import main.java.tessellation.Tile;
/**
* Unit test for {@linkplain Board}
* @author Jose Toledo Navarro
* @version 1.00
*/
public class BoardTest {
/**
* <pre>
* Empty board
*
* ------;------;------;
* ------;------;------;
* ------;------;------;
* ------;------;------;
* </pre>
*/
private static final Board EMPTY_BOARD = new Board();
/**
* <pre>
* Example in picture 9
*
* ------;GGY-Y-;----RR;
* ------;RGRGYY;GG----;
* --YGGY;G--RGR;-YY---;
* ------;---YY-;Y----Y;
* </pre>
*/
private static final Board VALID_BOARD = new Board();
/**
* <pre>
* Example in picture 10
*
* ------;-GGY-Y;RR----;
* ------;RGRGYY;GG----;
* Y--YGG;G--RGR;-YY---;
* ------;---YY-;YY----;
* </pre>
*/
private static final Board INVALID_BOARD = new Board();
/**
* Used to populate the general test cases
*/
public BoardTest() {
VALID_BOARD.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
VALID_BOARD.setTile(2, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.NONE, LineType.RED, LineType.RED }));
VALID_BOARD.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
VALID_BOARD.setTile(5, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
VALID_BOARD.setTile(6, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.YELLOW,
LineType.GREEN, LineType.GREEN, LineType.YELLOW }));
VALID_BOARD.setTile(7, new Tile(new LineType[] {
LineType.GREEN, LineType.NONE, LineType.NONE,
LineType.RED, LineType.GREEN, LineType.RED }));
VALID_BOARD.setTile(8, new Tile(new LineType[] {
LineType.NONE, LineType.YELLOW, LineType.YELLOW,
LineType.NONE, LineType.NONE, LineType.NONE }));
VALID_BOARD.setTile(10, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.YELLOW, LineType.YELLOW, LineType.NONE }));
VALID_BOARD.setTile(11, new Tile(new LineType[] {
LineType.YELLOW, LineType.NONE, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.YELLOW }));
INVALID_BOARD.setTile(1, new Tile(new LineType[] {
LineType.NONE, LineType.GREEN, LineType.GREEN,
LineType.YELLOW, LineType.NONE, LineType.YELLOW }));
INVALID_BOARD.setTile(2, new Tile(new LineType[] {
LineType.RED, LineType.RED, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
INVALID_BOARD.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
INVALID_BOARD.setTile(5, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
INVALID_BOARD.setTile(6, new Tile(new LineType[] {
LineType.YELLOW, LineType.NONE, LineType.NONE,
LineType.YELLOW, LineType.GREEN, LineType.GREEN }));
INVALID_BOARD.setTile(7, new Tile(new LineType[] {
LineType.GREEN, LineType.NONE, LineType.NONE,
LineType.RED, LineType.GREEN, LineType.RED }));
INVALID_BOARD.setTile(8, new Tile(new LineType[] {
LineType.NONE, LineType.YELLOW, LineType.YELLOW,
LineType.NONE, LineType.NONE, LineType.NONE }));
INVALID_BOARD.setTile(10, new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.YELLOW, LineType.YELLOW, LineType.NONE }));
INVALID_BOARD.setTile(11, new Tile(new LineType[] {
LineType.YELLOW, LineType.YELLOW, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE }));
}
@Test
public void testBoard() {
Board firstTest = new Board();
StringBuilder builder = new StringBuilder();
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertTrue(firstTest != null);
assertTrue(firstTest.isEmpty() == true);
assertThat(firstTest.toString(), is(builder.toString()));
}
@Test
public void testGetTile() {
Tile actualResult = null;
Tile expectedResult = null;
actualResult = VALID_BOARD.getTile(1);
expectedResult = new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE });
assertThat(actualResult.toString(), is(expectedResult.toString()));
actualResult = EMPTY_BOARD.getTile(5);
expectedResult = new Tile(new LineType[] {
LineType.NONE, LineType.NONE, LineType.NONE,
LineType.NONE, LineType.NONE, LineType.NONE });
assertThat(actualResult.toString(), is(expectedResult.toString()));
}
@Test
public void testSetTile() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
builder.append("------;GGY-Y-;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
builder.setLength(0);
builder.append("------;GGY-Y-;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testRemoveTile() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
builder.append("------;GGY-Y-;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
test.removeTile(4);
builder.setLength(0);
builder.append("------;GGY-Y-;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testIsEmpty() {
assertTrue(EMPTY_BOARD.isEmpty() == true);
assertTrue(INVALID_BOARD.isEmpty() == false);
assertTrue(VALID_BOARD.isEmpty() == false);
}
@Test
public void testRotateTileClockwise() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
test.rotateTileClockwise(1);
builder.append("------;-GGY-Y;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testRotateTileCounterClockwise() {
Board test = new Board();
StringBuilder builder = new StringBuilder();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
test.rotateTileCounterClockwise(1);
builder.append("------;GY-Y-G;------;\n");
builder.append("------;RGRGYY;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(test.toString(), is(builder.toString()));
}
@Test
public void testGetNumberOfColors() {
Board test = new Board();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
assertTrue(test.getNumberOfColors() == 3);
test.removeTile(4);
assertTrue(test.getNumberOfColors() == 2);
assertTrue(EMPTY_BOARD.getNumberOfColors() == 0);
assertTrue(INVALID_BOARD.getNumberOfColors() == 3);
assertTrue(INVALID_BOARD.getNumberOfColors() == 3);
}
@Test
public void testIsValid() {
Board test = new Board();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
assertTrue(test.isValid() == true); //Example in code snippet 3
test.rotateTileClockwise(1);
assertTrue(test.isValid() == false); //Example in code snippet 3
assertTrue(EMPTY_BOARD.isValid() == true);
assertTrue(VALID_BOARD.isValid() == true);
assertTrue(INVALID_BOARD.isValid() == false);
}
@Test
public void testGetConnectedPathColor() {
Board test = new Board();
test.setTile(1, new Tile(new LineType[] {
LineType.GREEN, LineType.GREEN, LineType.YELLOW,
LineType.NONE, LineType.YELLOW, LineType.NONE }));
test.setTile(4, new Tile(new LineType[] {
LineType.RED, LineType.GREEN, LineType.RED,
LineType.GREEN, LineType.YELLOW, LineType.YELLOW }));
assertTrue(test.getConnectedPathColor(new int[]{1, 4}) == LineType.YELLOW);
test.rotateTileClockwise(1);
assertTrue(test.getConnectedPathColor(new int[] {1, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {0, 3}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {1, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {1, 2, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4, 5, 7}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {8, 10, 11}) == LineType.NONE);
assertTrue(EMPTY_BOARD.getConnectedPathColor(new int[] {8, 10, 11, 8}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {0, 3}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {1, 4}) == LineType.YELLOW);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {1, 4, 5}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {1, 2, 4}) == LineType.NONE);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4, 5, 7}) == LineType.GREEN);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11}) == LineType.YELLOW);
assertTrue(VALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11, 8}) == LineType.YELLOW);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {0, 3}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {1, 4}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {1, 2, 4}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7}) == LineType.GREEN);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {4, 5, 7, 6, 4, 5, 7}) == LineType.NONE);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11}) == LineType.YELLOW);
assertTrue(INVALID_BOARD.getConnectedPathColor(new int[] {8, 10, 11, 8}) == LineType.NONE);
}
@Test
public void testToString() {
StringBuilder builder = new StringBuilder();
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;\n");
builder.append("------;------;------;");
assertThat(EMPTY_BOARD.toString(), is(builder.toString()));
builder.setLength(0);
builder.append("------;-GGY-Y;RR----;\n");
builder.append("------;RGRGYY;GG----;\n");
builder.append("Y--YGG;G--RGR;-YY---;\n");
builder.append("------;---YY-;YY----;");
assertThat(INVALID_BOARD.toString(), is(builder.toString()));
builder.setLength(0);
builder.append("------;GGY-Y-;----RR;\n");
builder.append("------;RGRGYY;GG----;\n");
builder.append("--YGGY;G--RGR;-YY---;\n");
builder.append("------;---YY-;Y----Y;");
assertThat(VALID_BOARD.toString(), is(builder.toString()));
}
}
|
Reorganised imports
|
src/test/java/tessellation/BoardTest.java
|
Reorganised imports
|
<ide><path>rc/test/java/tessellation/BoardTest.java
<ide> import main.java.tessellation.Board;
<ide> import main.java.tessellation.LineType;
<ide> import main.java.tessellation.Tile;
<add>
<ide> /**
<ide> * Unit test for {@linkplain Board}
<ide> * @author Jose Toledo Navarro
|
|
Java
|
agpl-3.0
|
0b6ded37a6ce4afccbb71099c02c58379f7af04c
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
f6366ee8-2e61-11e5-9284-b827eb9e62be
|
hello.java
|
f630f3dc-2e61-11e5-9284-b827eb9e62be
|
f6366ee8-2e61-11e5-9284-b827eb9e62be
|
hello.java
|
f6366ee8-2e61-11e5-9284-b827eb9e62be
|
<ide><path>ello.java
<del>f630f3dc-2e61-11e5-9284-b827eb9e62be
<add>f6366ee8-2e61-11e5-9284-b827eb9e62be
|
|
JavaScript
|
isc
|
b214a2e880f7822a469918d42746fc40f44f120d
| 0 |
Kryten0807/cacofonix
|
// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow, render, mount } from 'enzyme';
import chai from 'chai';
import Form from '../Form';
const expect = chai.expect;
/* eslint-disable no-unused-vars */
const debug = (component) => {
console.info('------------------------------------------------------------');
console.info(component.debug());
console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */
/* *****************************************************************************
a Form component with a TextInput element
should include a <Form.TextInput> as a child
should not include a label if label is omitted
should include a label if the label is set
*/
describe('a Form component with a TextInput element', () => {
it('should include a <Form.TextInput> as a child', () => {
const component = shallow(
<Form>
<Form.TextInput />
</Form>
);
expect(component.find(Form.TextInput)).to.have.length(1);
});
it('should not include a label if label is omitted', () => {
const component = render(
<Form>
<Form.TextInput />
</Form>
);
expect(component.find('label')).to.have.length(0);
});
it('should include a label if the label is set', () => {
const label = 'about this control';
const component = render(
<Form>
<Form.TextInput label={label} />
</Form>
);
expect(component.find('label')).to.have.length(1);
expect(component.find('label').text()).to.equal(label);
});
});
/* *****************************************************************************
when initializing a Form with a required TextInput
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when initializing a Form with a required TextInput', () => {
const required = true;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when initializing a Form with a non-required TextInput
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when initializing a Form with a non-required TextInput', () => {
const required = false;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when changing the value of a required TextInput (but not blurring)
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when changing the value of a required TextInput (but not blurring)', () => {
const required = true;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when changing the value of a non-required TextInput (but not blurring)
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when changing the value of a non-required TextInput (but not blurring)', () => {
const required = false;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when changing (and blurring) the value of a required TextInput
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message SHOULD be displayed with an invalid value
the component validation message SHOULD be displayed with an invalid value
*/
describe('when changing (and blurring) the value of a required TextInput', () => {
const required = true;
it('the global validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'valid';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'valid';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the global validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(1, 'Alert');
});
it('the component validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(1, 'has-error');
expect(component.find('.help-block')).to.have.length(1, 'help-block');
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput with a pattern function
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message SHOULD be displayed with an invalid value
the component validation message SHOULD be displayed with an invalid value
*/
describe('when changing (and blurring) the value of a TextInput with a pattern function', () => {
const pattern = (value) => value === 'the only valid value';
it('the global validation message should not be displayed with a valid value', () => {
const initialValue = 'the only valid value';
const finalValue = initialValue;
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0, 'Alert');
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'the only valid value';
const finalValue = initialValue;
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0, 'has-error');
expect(component.find('.help-block')).to.have.length(0, 'help-block');
});
it('the global validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'the only valid value';
const finalValue = 'this does not match';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(1, 'Alert');
});
it('the component validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'the only valid value';
const finalValue = 'not the right value';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(1, 'has-error');
expect(component.find('.help-block')).to.have.length(1, 'help-block');
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput with a pattern regex
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message SHOULD be displayed with an invalid value
the component validation message SHOULD be displayed with an invalid value
*/
describe('when changing (and blurring) the value of a TextInput with a pattern regex', () => {
// a simple zip code pattern
//
const pattern = /^[0-9]{5}$/;
it('the global validation message should not be displayed with a valid value', () => {
const initialValue = '12345';
const finalValue = '54321';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0, 'Alert');
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = '12345';
const finalValue = '54321';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0, 'has-error');
expect(component.find('.help-block')).to.have.length(0, 'help-block');
});
it('the global validation message SHOULD be displayed with an invalid value', () => {
const initialValue = '12345';
const finalValue = '999';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(1, 'Alert');
});
it('the component validation message SHOULD be displayed with an invalid value', () => {
const initialValue = '12345';
const finalValue = '999';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(1, 'has-error');
expect(component.find('.help-block')).to.have.length(1, 'help-block');
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput
should display validation error when required=true and value=blank
should not display validation error when required=true and value=something
should not display validation error when required=false and value=blank
should not display validation error when required=false and value=something
should display validation error when required=true, pattern=regex, and value=blank
should display validation error when required=true, pattern=regex, and value=non-match
should not display validation error when required=true, pattern=regex, and value=match
should not display validation error when required=false, pattern=regex, and value=blank
should display validation error when required=false, pattern=regex, and value=non-match
should not display validation error when required=false, pattern=regex, and value=match
should display validation error when required=true, pattern=function, and value=blank
should display validation error when required=true, pattern=function, and value=non-match
should not display validation error when required=true, pattern=function, and value=match
should not display validation error when required=false, pattern=function, and value=blank
should display validation error when required=false, pattern=function, and value=non-match
should not display validation error when required=false, pattern=function, and value=match
*/
/* *****************************************************************************
when changing (and blurring) the value of a required TextInput with an invalid value
the error message displayed in the form should be the default value when
validationMessage is not set
the error message displayed in the form should be the custom value when
validationMessage is set
the error message displayed in the component should be the default value
when validationMessage is not set
the error message displayed in the component should be the custom value when
validationMessage is set
*/
describe('when changing (and blurring) the value of a required TextInput ' +
'with an invalid value', () => {
const required = true;
const description = 'My awesome component';
const customMessage = 'This is my custom validation error message';
const expectedMessage = `${description} is required`;
it('the error message displayed in the form should be the default value ' +
'when validationMessage is not set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
description={description}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert ul li').text()).to.contain(expectedMessage);
});
it('the error message displayed in the form should be the custom value ' +
'when validationMessage is set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
validationMessage={customMessage}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert ul li').text()).to.contain(customMessage);
});
it('the error message displayed in the component should be the default ' +
'value when validationMessage is not set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
description={description}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.help-block').text()).to.contain(expectedMessage);
});
it('the error message displayed in the component should be the custom ' +
'value when validationMessage is set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
validationMessage={customMessage}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.help-block').text()).to.contain(customMessage);
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput with parent component
should maintain the correct value in the input element
*/
describe('when changing (and blurring) the value of a TextInput with parent component', () => {
const required = true;
const description = 'mumble mumble';
class TestParent extends React.Component {
constructor(props) {
super(props);
this.state = {
testValue: props.testValue || '',
};
this.onChange = this.onChange.bind(this);
}
onChange(testValue) {
this.setState({ testValue });
}
render() {
return (
<Form>
<Form.TextInput
required={required}
value={this.props.testValue}
description={description}
onChange={this.onChange}
/>
</Form>
);
}
}
TestParent.propTypes = {
testValue: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
onChange: React.PropTypes.func,
onValidation: React.PropTypes.func,
};
it('should maintain the correct value in the input element', () => {
const initialValue = 'this is first';
const finalValue = 'this is second';
const component = mount(
<TestParent testValue={initialValue} />
);
expect(component.find('input').props().value)
.to.equal(initialValue, 'input - initialValue');
expect(component.state().testValue).to.equal(initialValue, 'state - initialValue');
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('input').props().value).to.equal(finalValue, 'finalValue');
expect(component.state().testValue).to.equal(finalValue, 'state - finalValue');
});
});
|
src/components/form/TextInput.spec.js
|
// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow, render, mount } from 'enzyme';
import chai from 'chai';
import Form from '../Form';
const expect = chai.expect;
/* eslint-disable no-unused-vars */
const debug = (component) => {
console.info('------------------------------------------------------------');
console.info(component.debug());
console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */
/* *****************************************************************************
a Form component with a TextInput element
should include a <Form.TextInput> as a child
should not include a label if label is omitted
should include a label if the label is set
*/
describe('a Form component with a TextInput element', () => {
it('should include a <Form.TextInput> as a child', () => {
const component = shallow(
<Form>
<Form.TextInput />
</Form>
);
expect(component.find(Form.TextInput)).to.have.length(1);
});
it('should not include a label if label is omitted', () => {
const component = render(
<Form>
<Form.TextInput />
</Form>
);
expect(component.find('label')).to.have.length(0);
});
it('should include a label if the label is set', () => {
const label = 'about this control';
const component = render(
<Form>
<Form.TextInput label={label} />
</Form>
);
expect(component.find('label')).to.have.length(1);
expect(component.find('label').text()).to.equal(label);
});
});
/* *****************************************************************************
when initializing a Form with a required TextInput
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when initializing a Form with a required TextInput', () => {
const required = true;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when initializing a Form with a non-required TextInput
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when initializing a Form with a non-required TextInput', () => {
const required = false;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = '';
const component = render(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when changing the value of a required TextInput (but not blurring)
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when changing the value of a required TextInput (but not blurring)', () => {
const required = true;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when changing the value of a non-required TextInput (but not blurring)
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message should not be displayed with an invalid value
the component validation message should not be displayed with an invalid value
*/
describe('when changing the value of a non-required TextInput (but not blurring)', () => {
const required = false;
it('the validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'something else';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
});
/* *****************************************************************************
when changing (and blurring) the value of a required TextInput
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message SHOULD be displayed with an invalid value
the component validation message SHOULD be displayed with an invalid value
*/
describe('when changing (and blurring) the value of a required TextInput', () => {
const required = true;
it('the global validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'valid';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0);
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'something';
const finalValue = 'valid';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0);
expect(component.find('.help-block')).to.have.length(0);
});
it('the global validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(1, 'Alert');
});
it('the component validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput required={required} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(1, 'has-error');
expect(component.find('.help-block')).to.have.length(1, 'help-block');
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput with a pattern function
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message SHOULD be displayed with an invalid value
the component validation message SHOULD be displayed with an invalid value
*/
describe('when changing (and blurring) the value of a TextInput with a pattern function', () => {
const pattern = (value) => value === 'the only valid value';
it('the global validation message should not be displayed with a valid value', () => {
const initialValue = 'the only valid value';
const finalValue = initialValue;
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0, 'Alert');
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = 'the only valid value';
const finalValue = initialValue;
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0, 'has-error');
expect(component.find('.help-block')).to.have.length(0, 'help-block');
});
it('the global validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'the only valid value';
const finalValue = 'this does not match';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(1, 'Alert');
});
it('the component validation message SHOULD be displayed with an invalid value', () => {
const initialValue = 'the only valid value';
const finalValue = 'not the right value';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(1, 'has-error');
expect(component.find('.help-block')).to.have.length(1, 'help-block');
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput with a pattern regex
the global validation message should not be displayed with a valid value
the component validation message should not be displayed with a valid value
the global validation message SHOULD be displayed with an invalid value
the component validation message SHOULD be displayed with an invalid value
*/
describe('when changing (and blurring) the value of a TextInput with a pattern regex', () => {
// a simple zip code pattern
//
const pattern = /^[0-9]{5}$/;
it('the global validation message should not be displayed with a valid value', () => {
const initialValue = '12345';
const finalValue = '54321';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(0, 'Alert');
});
it('the component validation message should not be displayed with a valid value', () => {
const initialValue = '12345';
const finalValue = '54321';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(0, 'has-error');
expect(component.find('.help-block')).to.have.length(0, 'help-block');
});
it('the global validation message SHOULD be displayed with an invalid value', () => {
const initialValue = '12345';
const finalValue = '999';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert')).to.have.length(1, 'Alert');
});
it('the component validation message SHOULD be displayed with an invalid value', () => {
const initialValue = '12345';
const finalValue = '999';
const component = mount(
<Form>
<Form.TextInput pattern={pattern} value={initialValue} />
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.has-error')).to.have.length(1, 'has-error');
expect(component.find('.help-block')).to.have.length(1, 'help-block');
});
});
/* *****************************************************************************
when changing (and blurring) the value of a required TextInput with an invalid value
the error message displayed in the form should be the default value when
validationMessage is not set
the error message displayed in the form should be the custom value when
validationMessage is set
the error message displayed in the component should be the default value
when validationMessage is not set
the error message displayed in the component should be the custom value when
validationMessage is set
*/
describe('when changing (and blurring) the value of a required TextInput ' +
'with an invalid value', () => {
const required = true;
const description = 'My awesome component';
const customMessage = 'This is my custom validation error message';
const expectedMessage = `${description} is required`;
it('the error message displayed in the form should be the default value ' +
'when validationMessage is not set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
description={description}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert ul li').text()).to.contain(expectedMessage);
});
it('the error message displayed in the form should be the custom value ' +
'when validationMessage is set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
validationMessage={customMessage}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('Alert ul li').text()).to.contain(customMessage);
});
it('the error message displayed in the component should be the default ' +
'value when validationMessage is not set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
description={description}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.help-block').text()).to.contain(expectedMessage);
});
it('the error message displayed in the component should be the custom ' +
'value when validationMessage is set', () => {
const initialValue = 'something';
const finalValue = '';
const component = mount(
<Form>
<Form.TextInput
required={required}
value={initialValue}
validationMessage={customMessage}
/>
</Form>
);
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('.help-block').text()).to.contain(customMessage);
});
});
/* *****************************************************************************
when changing (and blurring) the value of a TextInput with parent component
should maintain the correct value in the input element
*/
describe('when changing (and blurring) the value of a TextInput with parent component', () => {
const required = true;
const description = 'mumble mumble';
class TestParent extends React.Component {
constructor(props) {
super(props);
this.state = {
testValue: props.testValue || '',
};
this.onChange = this.onChange.bind(this);
}
onChange(testValue) {
this.setState({ testValue });
}
render() {
return (
<Form>
<Form.TextInput
required={required}
value={this.props.testValue}
description={description}
onChange={this.onChange}
/>
</Form>
);
}
}
TestParent.propTypes = {
testValue: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
onChange: React.PropTypes.func,
onValidation: React.PropTypes.func,
};
it('should maintain the correct value in the input element', () => {
const initialValue = 'this is first';
const finalValue = 'this is second';
const component = mount(
<TestParent testValue={initialValue} />
);
expect(component.find('input').props().value)
.to.equal(initialValue, 'input - initialValue');
expect(component.state().testValue).to.equal(initialValue, 'state - initialValue');
component.find('input').simulate('change', {
target: { value: finalValue }
});
component.find('input').simulate('blur', {
target: { value: finalValue }
});
expect(component.find('input').props().value).to.equal(finalValue, 'finalValue');
expect(component.state().testValue).to.equal(finalValue, 'state - finalValue');
});
});
|
added notes for complete testing of required & pattern
|
src/components/form/TextInput.spec.js
|
added notes for complete testing of required & pattern
|
<ide><path>rc/components/form/TextInput.spec.js
<ide>
<ide> });
<ide>
<add>
<add>/* *****************************************************************************
<add>when changing (and blurring) the value of a TextInput
<add> should display validation error when required=true and value=blank
<add> should not display validation error when required=true and value=something
<add> should not display validation error when required=false and value=blank
<add> should not display validation error when required=false and value=something
<add>
<add> should display validation error when required=true, pattern=regex, and value=blank
<add> should display validation error when required=true, pattern=regex, and value=non-match
<add> should not display validation error when required=true, pattern=regex, and value=match
<add> should not display validation error when required=false, pattern=regex, and value=blank
<add> should display validation error when required=false, pattern=regex, and value=non-match
<add> should not display validation error when required=false, pattern=regex, and value=match
<add>
<add> should display validation error when required=true, pattern=function, and value=blank
<add> should display validation error when required=true, pattern=function, and value=non-match
<add> should not display validation error when required=true, pattern=function, and value=match
<add> should not display validation error when required=false, pattern=function, and value=blank
<add> should display validation error when required=false, pattern=function, and value=non-match
<add> should not display validation error when required=false, pattern=function, and value=match
<add>*/
<ide>
<ide> /* *****************************************************************************
<ide> when changing (and blurring) the value of a required TextInput with an invalid value
|
|
Java
|
lgpl-2.1
|
16a79ec56af99c286ddaaf39c7ff2e569e1b3127
| 0 |
pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.xar;
import java.beans.Transient;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.xar.internal.model.XarModel;
/**
* An entry (wiki page) in a XAR package.
* <p>
* Reuse LocalDocumentReference equals and hashCode implementation so that the entry can be used as a
* {@link LocalDocumentReference} in a map.
*
* @version $Id$
* @since 5.4RC1
*/
public class XarEntry extends LocalDocumentReference
{
/**
* @see #getEntryName()
*/
private String entryName;
/**
* @see #getDefaultAction()
*/
private int defaultAction;
/**
* @param reference the reference of the document
*/
public XarEntry(LocalDocumentReference reference)
{
this(reference, null);
}
/**
* @param reference the reference of the document
* @param name the name of the entry (ZIP style)
*/
public XarEntry(LocalDocumentReference reference, String name)
{
this(reference, name, XarModel.ACTION_OVERWRITE);
}
/**
* @param reference the reference of the document
* @param defaultAction the default action associated to a XAR entry
* @since 7.2M1
*/
public XarEntry(LocalDocumentReference reference, int defaultAction)
{
this(reference, null, defaultAction);
}
/**
* @param reference the reference of the document
* @param name the name of the entry (ZIP style)
* @param defaultAction the default action associated to a XAR entry
*/
public XarEntry(LocalDocumentReference reference, String name, int defaultAction)
{
super(reference);
this.entryName = name;
}
/**
* @return the name of the entry in the ZIP (XAR) package
*/
public String getEntryName()
{
return this.entryName;
}
/**
* @return the default action associated to the entry
*/
public int getDefaultAction()
{
return this.defaultAction;
}
/**
* @return the space of the document
* @deprecated since 7.2M1, does not make much sense anymore with nested space
*/
@Deprecated
@Transient
public String getSpaceName()
{
return TOSTRING_SERIALIZER.serialize(extractReference(EntityType.SPACE));
}
/**
* @return the name of the document
*/
@Transient
public String getDocumentName()
{
return getName();
}
@Override
public String toString()
{
StringBuilder str = new StringBuilder(super.toString());
if (getEntryName() != null) {
str.append(' ');
str.append('(');
str.append(getEntryName());
str.append(')');
}
return str.toString();
}
}
|
xwiki-platform-core/xwiki-platform-xar/src/main/java/org/xwiki/xar/XarEntry.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.xar;
import java.beans.Transient;
import org.xwiki.model.EntityType;
import org.xwiki.model.internal.reference.LocalStringEntityReferenceSerializer;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.xar.internal.model.XarModel;
/**
* An entry (wiki page) in a XAR package.
* <p>
* Reuse LocalDocumentReference equals and hashCode implementation so that the entry can be used as a
* {@link LocalDocumentReference} in a map.
*
* @version $Id$
* @since 5.4RC1
*/
public class XarEntry extends LocalDocumentReference
{
private static final LocalStringEntityReferenceSerializer TOSTRING_SERIALIZER =
new LocalStringEntityReferenceSerializer();
/**
* @see #getEntryName()
*/
private String entryName;
/**
* @see #getDefaultAction()
*/
private int defaultAction;
/**
* @param reference the reference of the document
*/
public XarEntry(LocalDocumentReference reference)
{
this(reference, null);
}
/**
* @param reference the reference of the document
* @param name the name of the entry (ZIP style)
*/
public XarEntry(LocalDocumentReference reference, String name)
{
this(reference, name, XarModel.ACTION_OVERWRITE);
}
/**
* @param reference the reference of the document
* @param defaultAction the default action associated to a XAR entry
* @since 7.2M1
*/
public XarEntry(LocalDocumentReference reference, int defaultAction)
{
this(reference, null, defaultAction);
}
/**
* @param reference the reference of the document
* @param name the name of the entry (ZIP style)
* @param defaultAction the default action associated to a XAR entry
*/
public XarEntry(LocalDocumentReference reference, String name, int defaultAction)
{
super(reference);
this.entryName = name;
}
/**
* @return the name of the entry in the ZIP (XAR) package
*/
public String getEntryName()
{
return this.entryName;
}
/**
* @return the default action associated to the entry
*/
public int getDefaultAction()
{
return this.defaultAction;
}
/**
* @return the space of the document
* @deprecated since 7.2M1, does not make much sense anymore with nested space
*/
@Deprecated
@Transient
public String getSpaceName()
{
return TOSTRING_SERIALIZER.serialize(extractReference(EntityType.SPACE));
}
/**
* @return the name of the document
*/
@Transient
public String getDocumentName()
{
return getName();
}
@Override
public String toString()
{
StringBuilder str = new StringBuilder(super.toString());
if (getEntryName() != null) {
str.append(' ');
str.append('(');
str.append(getEntryName());
str.append(')');
}
return str.toString();
}
}
|
[misc] Remove unneeded field
|
xwiki-platform-core/xwiki-platform-xar/src/main/java/org/xwiki/xar/XarEntry.java
|
[misc] Remove unneeded field
|
<ide><path>wiki-platform-core/xwiki-platform-xar/src/main/java/org/xwiki/xar/XarEntry.java
<ide> import java.beans.Transient;
<ide>
<ide> import org.xwiki.model.EntityType;
<del>import org.xwiki.model.internal.reference.LocalStringEntityReferenceSerializer;
<ide> import org.xwiki.model.reference.LocalDocumentReference;
<ide> import org.xwiki.xar.internal.model.XarModel;
<ide>
<ide> */
<ide> public class XarEntry extends LocalDocumentReference
<ide> {
<del> private static final LocalStringEntityReferenceSerializer TOSTRING_SERIALIZER =
<del> new LocalStringEntityReferenceSerializer();
<del>
<ide> /**
<ide> * @see #getEntryName()
<ide> */
|
|
JavaScript
|
mit
|
0e26e9bbd7cae3390b45d85002b954c40d746e9e
| 0 |
agroves333/banno
|
/*
* process.env.NODE_ENV - used to determine whether we generate a production or development bundle
*
* webpack --env.browser - used to determine whether to generate a browser or server bundle
*
* NOTE: browser/server is client/server-side rendering respectively in universal/isomorphic javascript
*
*/
const PATHS = require('./paths');
const rules = require('./rules');
const plugins = require('./plugins');
const externals = require('./externals');
const resolve = require('./resolve');
module.exports = (env = {}) => {
const isProduction = process.env.NODE_ENV === 'production';
const isBrowser = env.browser;
console.log(`Running webpack in ${process.env.NODE_ENV} mode on ${isBrowser ? 'browser': 'server'}`);
const hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true';
const node = { __dirname: true, __filename: true };
const prodServerRender = {
devtool: 'eval',
context: PATHS.app,
entry: { server: '../server/index' },
target: 'node',
node,
externals,
output: {
path: PATHS.compiled,
filename: '[name].js',
publicPath: PATHS.public,
libraryTarget: 'commonjs2'
},
module: { rules: rules({ production: true, browser: false }) },
resolve,
plugins: plugins({ production: true, browser: false })
};
const prodBrowserRender = {
devtool: 'eval',
context: PATHS.app,
entry: { app: ['./client'] },
node,
output: {
path: PATHS.assets,
filename: '[chunkhash].js',
chunkFilename: '[name].[chunkhash:6].js', // for code splitting. will work without but useful to set
publicPath: PATHS.public
},
module: { rules: rules({ production: true, browser: true }) },
resolve,
plugins: plugins({ production: true, browser: true })
};
const devBrowserRender = {
devtool: 'eval',
context: PATHS.app,
entry: { app: ['./client', hotMiddlewareScript] },
node,
output: {
path: PATHS.assets,
filename: '[name].js',
publicPath: PATHS.public
},
module: { rules: rules({ production: false, browser: true }) },
resolve,
plugins: plugins({ production: false, browser: true })
};
const devServerRender = {
devtool: 'sourcemap',
context: PATHS.app,
entry: { server: '../server/index' },
target: 'node',
node,
externals,
output: {
path: PATHS.compiled,
filename: '[name].dev.js',
publicPath: PATHS.public,
libraryTarget: 'commonjs2',
},
module: { rules: rules({ production: false, browser: false }) },
resolve,
plugins: plugins({ production: false, browser: false })
};
const prodConfig = isBrowser ? prodBrowserRender : prodServerRender;
const devConfig = isBrowser ? devBrowserRender : devServerRender;
const configuration = isProduction ? prodConfig : devConfig;
return configuration;
};
|
webpack/webpack.config.js
|
/*
* process.env.NODE_ENV - used to determine whether we generate a production or development bundle
*
* webpack --env.browser - used to determine whether to generate a browser or server bundle
*
* NOTE: browser/server is client/server-side rendering respectively in universal/isomorphic javascript
*
*/
const PATHS = require('./paths');
const rules = require('./rules');
const plugins = require('./plugins');
const externals = require('./externals');
const resolve = require('./resolve');
module.exports = (env = {}) => {
const isProduction = process.env.NODE_ENV === 'production';
const isBrowser = env.browser;
console.log(`Running webpack in ${process.env.NODE_ENV} mode on ${isBrowser ? 'browser': 'server'}`);
const hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true';
const node = { __dirname: true, __filename: true };
const prodServerRender = {
devtool: 'source-map',
context: PATHS.app,
entry: { server: '../server/index' },
target: 'node',
node,
externals,
output: {
path: PATHS.compiled,
filename: '[name].js',
publicPath: PATHS.public,
libraryTarget: 'commonjs2'
},
module: { rules: rules({ production: true, browser: false }) },
resolve,
plugins: plugins({ production: true, browser: false })
};
const prodBrowserRender = {
devtool: 'cheap-module-source-map',
context: PATHS.app,
entry: { app: ['./client'] },
node,
output: {
path: PATHS.assets,
filename: '[chunkhash].js',
chunkFilename: '[name].[chunkhash:6].js', // for code splitting. will work without but useful to set
publicPath: PATHS.public
},
module: { rules: rules({ production: true, browser: true }) },
resolve,
plugins: plugins({ production: true, browser: true })
};
const devBrowserRender = {
devtool: 'eval',
context: PATHS.app,
entry: { app: ['./client', hotMiddlewareScript] },
node,
output: {
path: PATHS.assets,
filename: '[name].js',
publicPath: PATHS.public
},
module: { rules: rules({ production: false, browser: true }) },
resolve,
plugins: plugins({ production: false, browser: true })
};
const devServerRender = {
devtool: 'sourcemap',
context: PATHS.app,
entry: { server: '../server/index' },
target: 'node',
node,
externals,
output: {
path: PATHS.compiled,
filename: '[name].dev.js',
publicPath: PATHS.public,
libraryTarget: 'commonjs2',
},
module: { rules: rules({ production: false, browser: false }) },
resolve,
plugins: plugins({ production: false, browser: false })
};
const prodConfig = isBrowser ? prodBrowserRender : prodServerRender;
const devConfig = isBrowser ? devBrowserRender : devServerRender;
const configuration = isProduction ? prodConfig : devConfig;
return configuration;
};
|
devtools = eval
|
webpack/webpack.config.js
|
devtools = eval
|
<ide><path>ebpack/webpack.config.js
<ide> const node = { __dirname: true, __filename: true };
<ide>
<ide> const prodServerRender = {
<del> devtool: 'source-map',
<add> devtool: 'eval',
<ide> context: PATHS.app,
<ide> entry: { server: '../server/index' },
<ide> target: 'node',
<ide> };
<ide>
<ide> const prodBrowserRender = {
<del> devtool: 'cheap-module-source-map',
<add> devtool: 'eval',
<ide> context: PATHS.app,
<ide> entry: { app: ['./client'] },
<ide> node,
|
|
Java
|
apache-2.0
|
1bf93478bb61f4a092967cb38c421fe3c1c9216b
| 0 |
sangramjadhav/testrs
|
20d2d5b2-2ece-11e5-905b-74de2bd44bed
|
hello.java
|
20d24584-2ece-11e5-905b-74de2bd44bed
|
20d2d5b2-2ece-11e5-905b-74de2bd44bed
|
hello.java
|
20d2d5b2-2ece-11e5-905b-74de2bd44bed
|
<ide><path>ello.java
<del>20d24584-2ece-11e5-905b-74de2bd44bed
<add>20d2d5b2-2ece-11e5-905b-74de2bd44bed
|
|
Java
|
mit
|
6ce4d0dde5815c1f1dc0724579fd3367a9958951
| 0 |
telly/groundy,casidiablo/groundy,hamsterksu/groundy,casidiablo/groundy
|
/**
* Copyright Telly, Inc. and other Groundy contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.telly.groundy;
import android.os.Bundle;
import com.telly.groundy.annotations.OnCallback;
import com.telly.groundy.annotations.OnCancel;
import com.telly.groundy.annotations.OnFailure;
import com.telly.groundy.annotations.OnProgress;
import com.telly.groundy.annotations.OnStart;
import com.telly.groundy.annotations.OnSuccess;
import com.telly.groundy.annotations.Param;
import com.telly.groundy.annotations.Traverse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class ReflectProxy implements ResultProxy {
private static final Class<?>[] GROUNDY_CALLBACKS = {
OnStart.class, OnSuccess.class, OnFailure.class, OnCancel.class, OnProgress.class,
OnCallback.class
};
private static final Map<Class<?>, Method[]> METHODS_CACHE = new HashMap<Class<?>, Method[]>();
private final Map<Class<? extends Annotation>, List<MethodSpec>> callbacksMap;
private final Class<? extends GroundyTask> mTaskType;
private final Class<?> mHandlerType;
ReflectProxy(Class<? extends GroundyTask> groundyTaskType, Class<?> handlerType) {
mTaskType = groundyTaskType;
mHandlerType = handlerType;
callbacksMap = new HashMap<Class<? extends Annotation>, List<MethodSpec>>();
fillMethodSpecMap();
}
@Override public void apply(Object target, Class<? extends Annotation> callbackAnnotation,
Bundle resultData) {
List<MethodSpec> methodSpecs = callbacksMap.get(callbackAnnotation);
if (methodSpecs == null || methodSpecs.isEmpty()) {
return;
}
String callbackName = resultData.getString(Groundy.KEY_CALLBACK_NAME);
for (MethodSpec methodSpec : methodSpecs) {
if (callbackName != null && !callbackName.equals(methodSpec.name)) {
// ignore method specs whose callback is not the same that is being applied right now
continue;
}
Object[] values = getResultParams(resultData, methodSpec);
try {
methodSpec.method.invoke(target, values);
} catch (Exception pokemon) {
pokemon.printStackTrace();
}
}
}
private void fillMethodSpecMap() {
Class<?> type = mHandlerType;
while (type != Object.class) {
fillMethodSpecMapWith(type);
if (!mTaskType.isAnnotationPresent(Traverse.class)) {
// traverse class hierarchy when @Traverse annotation is present only
break;
}
type = type.getSuperclass();
}
}
private void fillMethodSpecMapWith(Class<?> type) {
for (Method method : getMethods(type)) {
// register groundy callbacks
for (Class<?> groundyCallback : GROUNDY_CALLBACKS) {
//noinspection unchecked
Class<? extends Annotation> annotation = (Class<? extends Annotation>) groundyCallback;
appendMethodCallback(mTaskType, annotation, method);
}
}
}
private static Method[] getMethods(Class<?> type) {
if (!METHODS_CACHE.containsKey(type)) {
METHODS_CACHE.put(type, type.getMethods());
}
return METHODS_CACHE.get(type);
}
private void appendMethodCallback(Class<? extends GroundyTask> taskType,
Class<? extends Annotation> phaseAnnotation, Method method) {
Annotation methodAnnotation = method.getAnnotation(phaseAnnotation);
if (methodAnnotation == null || !isValid(taskType, methodAnnotation)) {
return;
}
if (!Modifier.isPublic(method.getModifiers())) {
throw new IllegalStateException("Callback methods can only be public");
}
Class<?> returnType = method.getReturnType();
if (returnType != void.class) {
throw new IllegalStateException("Callback methods must return void");
}
List<String> paramNames = new ArrayList<String>();
Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (int i = 0; i < paramAnnotations.length; i++) {
Annotation[] paramAnnotation = paramAnnotations[i];
Param param = null;
for (Annotation annotation : paramAnnotation) {
if (annotation instanceof Param) {
param = (Param) annotation;
break;
}
}
if (param == null) {
throw new IllegalStateException("All parameters must be annotated with @Param. " + method +
", param " + i + " doesn't");
}
paramNames.add(param.value());
}
Class<? extends Annotation> annotationType = methodAnnotation.annotationType();
List<MethodSpec> methodSpecs;
if (callbacksMap.containsKey(annotationType)) {
methodSpecs = callbacksMap.get(annotationType);
} else {
methodSpecs = new ArrayList<MethodSpec>();
callbacksMap.put(annotationType, methodSpecs);
}
String name = null; // used only for @OnCallback annotations
if (methodAnnotation instanceof OnCallback) {
OnCallback onCallback = (OnCallback) methodAnnotation;
name = onCallback.name();
if (name == null) {
throw new NullPointerException("@OnCallback's name cannot be null");
}
}
methodSpecs.add(new MethodSpec(method, paramNames, name));
}
private boolean isValid(Class<? extends GroundyTask> groundyTaskType,
Annotation methodAnnotation) {
if (methodAnnotation instanceof OnSuccess) {
OnSuccess onSuccess = (OnSuccess) methodAnnotation;
return isValid(groundyTaskType, onSuccess.value());
} else if (methodAnnotation instanceof OnFailure) {
OnFailure onFailure = (OnFailure) methodAnnotation;
return isValid(groundyTaskType, onFailure.value());
} else if (methodAnnotation instanceof OnProgress) {
OnProgress onProgress = (OnProgress) methodAnnotation;
return isValid(groundyTaskType, onProgress.value());
} else if (methodAnnotation instanceof OnStart) {
OnStart onStart = (OnStart) methodAnnotation;
return isValid(groundyTaskType, onStart.value());
} else if (methodAnnotation instanceof OnCancel) {
OnCancel onCancel = (OnCancel) methodAnnotation;
return isValid(groundyTaskType, onCancel.value());
} else if (methodAnnotation instanceof OnCallback) {
OnCallback onCallback = (OnCallback) methodAnnotation;
return isValid(groundyTaskType, onCallback.value());
}
return true;
}
private boolean isValid(Class<?> groundyTaskType, Class<? extends GroundyTask>[] tasks) {
for (Class<? extends GroundyTask> task : tasks) {
if (task.isAssignableFrom(groundyTaskType)) return true;
}
return false;
}
private static Object[] getResultParams(Bundle resultData, MethodSpec methodSpec) {
Method method = methodSpec.method;
Object[] values = new Object[methodSpec.paramNames.size()];
Class<?>[] parameterTypes = method.getParameterTypes();
List<String> paramNames = methodSpec.paramNames;
for (int i = 0; i < paramNames.size(); i++) {
Class<?> parameterType = parameterTypes[i];
String paramName = paramNames.get(i);
values[i] = resultData.get(paramName);
if (values[i] == null) {
values[i] = defaultValue(parameterType);
} else {
if (!isTypeValid(parameterType, values[i].getClass())) {
throw new RuntimeException(paramName
+ " parameter is "
+ values[i].getClass().getSimpleName()
+ " but the method ("
+ method
+ ") expects "
+ parameterType.getSimpleName());
}
}
}
return values;
}
private static boolean isTypeValid(Class<?> expected, Class<?> actual) {
if (expected == Double.class || expected == double.class) {
return isAnyOf(actual, long.class, Long.class, int.class, Integer.class, double.class,
Double.class, float.class, Float.class);
} else if (expected == Float.class || expected == float.class) {
return isAnyOf(actual, int.class, Integer.class, float.class, Float.class);
} else if (expected == Long.class || expected == long.class) {
return isAnyOf(actual, int.class, Integer.class, Long.class, long.class);
} else if (expected == Integer.class || expected == int.class) {
return isAnyOf(actual, int.class, Integer.class);
} else if (expected == Boolean.class || expected == boolean.class) {
return isAnyOf(actual, boolean.class, Boolean.class);
}
return expected.isAssignableFrom(actual);
}
private static boolean isAnyOf(Class<?> foo, Class<?>... bars) {
for (Class<?> bar : bars) {
if (foo == bar) {
return true;
}
}
return false;
}
private static Object defaultValue(Class<?> parameterType) {
if (parameterType == int.class
|| parameterType == Integer.class
|| parameterType == float.class
|| parameterType == Float.class
|| parameterType == double.class
|| parameterType == Double.class
|| parameterType == long.class
|| parameterType == Long.class
|| parameterType == byte.class
|| parameterType == Byte.class
|| parameterType == char.class
|| parameterType == Character.class
|| parameterType == short.class
|| parameterType == Short.class) {
return 0;
} else if (parameterType == boolean.class || parameterType == Boolean.class) {
return false;
}
return null;
}
@Override public String toString() {
return "ReflectProxy{" +
"groundyTaskType=" + mTaskType +
", handlerType=" + mHandlerType +
'}';
}
static class MethodSpec {
final Method method;
final List<String> paramNames;
final String name;
MethodSpec(Method m, List<String> methodParams, String customName) {
method = m;
paramNames = methodParams;
name = customName;
}
}
}
|
library/src/main/java/com/telly/groundy/ReflectProxy.java
|
/**
* Copyright Telly, Inc. and other Groundy contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.telly.groundy;
import android.os.Bundle;
import com.telly.groundy.annotations.OnCallback;
import com.telly.groundy.annotations.OnCancel;
import com.telly.groundy.annotations.OnFailure;
import com.telly.groundy.annotations.OnProgress;
import com.telly.groundy.annotations.OnStart;
import com.telly.groundy.annotations.OnSuccess;
import com.telly.groundy.annotations.Param;
import com.telly.groundy.annotations.Traverse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class ReflectProxy implements ResultProxy {
private static final Class<?>[] GROUNDY_CALLBACKS = {
OnStart.class, OnSuccess.class, OnFailure.class, OnCancel.class, OnProgress.class,
OnCallback.class
};
private static final Map<Class<?>, Method[]> METHODS_CACHE = new HashMap<Class<?>, Method[]>();
private final Map<Class<? extends Annotation>, List<MethodSpec>> callbacksMap;
private final Class<? extends GroundyTask> mTaskType;
private final Class<?> mHandlerType;
ReflectProxy(Class<? extends GroundyTask> groundyTaskType, Class<?> handlerType) {
mTaskType = groundyTaskType;
mHandlerType = handlerType;
callbacksMap = new HashMap<Class<? extends Annotation>, List<MethodSpec>>();
fillMethodSpecMap();
}
@Override public void apply(Object target, Class<? extends Annotation> callbackAnnotation,
Bundle resultData) {
List<MethodSpec> methodSpecs = callbacksMap.get(callbackAnnotation);
if (methodSpecs == null || methodSpecs.isEmpty()) {
return;
}
String callbackName = resultData.getString(Groundy.KEY_CALLBACK_NAME);
for (MethodSpec methodSpec : methodSpecs) {
if (callbackName != null && !callbackName.equals(methodSpec.name)) {
// ignore method specs whose callback is not the same that is being applied right now
continue;
}
Object[] values = getResultParams(resultData, methodSpec);
try {
methodSpec.method.invoke(target, values);
} catch (Exception pokemon) {
pokemon.printStackTrace();
}
}
}
private void fillMethodSpecMap() {
Class<?> type = mHandlerType;
while (type != Object.class) {
fillMethodSpecMapWith(type);
if (!mTaskType.isAnnotationPresent(Traverse.class)) {
// traverse class hierarchy when @Traverse annotation is present only
break;
}
type = type.getSuperclass();
}
}
private void fillMethodSpecMapWith(Class<?> type) {
for (Method method : getDeclaredMethods(type)) {
// register groundy callbacks
for (Class<?> groundyCallback : GROUNDY_CALLBACKS) {
//noinspection unchecked
Class<? extends Annotation> annotation = (Class<? extends Annotation>) groundyCallback;
appendMethodCallback(mTaskType, annotation, method);
}
}
}
private static Method[] getDeclaredMethods(Class<?> type) {
if (!METHODS_CACHE.containsKey(type)) {
METHODS_CACHE.put(type, type.getDeclaredMethods());
}
return METHODS_CACHE.get(type);
}
private void appendMethodCallback(Class<? extends GroundyTask> taskType,
Class<? extends Annotation> phaseAnnotation, Method method) {
Annotation methodAnnotation = method.getAnnotation(phaseAnnotation);
if (methodAnnotation == null || !isValid(taskType, methodAnnotation)) {
return;
}
if (!Modifier.isPublic(method.getModifiers())) {
throw new IllegalStateException("Callback methods can only be public");
}
Class<?> returnType = method.getReturnType();
if (returnType != void.class) {
throw new IllegalStateException("Callback methods must return void");
}
List<String> paramNames = new ArrayList<String>();
Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (int i = 0; i < paramAnnotations.length; i++) {
Annotation[] paramAnnotation = paramAnnotations[i];
Param param = null;
for (Annotation annotation : paramAnnotation) {
if (annotation instanceof Param) {
param = (Param) annotation;
break;
}
}
if (param == null) {
throw new IllegalStateException("All parameters must be annotated with @Param. " + method +
", param " + i + " doesn't");
}
paramNames.add(param.value());
}
Class<? extends Annotation> annotationType = methodAnnotation.annotationType();
List<MethodSpec> methodSpecs;
if (callbacksMap.containsKey(annotationType)) {
methodSpecs = callbacksMap.get(annotationType);
} else {
methodSpecs = new ArrayList<MethodSpec>();
callbacksMap.put(annotationType, methodSpecs);
}
String name = null; // used only for @OnCallback annotations
if (methodAnnotation instanceof OnCallback) {
OnCallback onCallback = (OnCallback) methodAnnotation;
name = onCallback.name();
if (name == null) {
throw new NullPointerException("@OnCallback's name cannot be null");
}
}
methodSpecs.add(new MethodSpec(method, paramNames, name));
}
private boolean isValid(Class<? extends GroundyTask> groundyTaskType,
Annotation methodAnnotation) {
if (methodAnnotation instanceof OnSuccess) {
OnSuccess onSuccess = (OnSuccess) methodAnnotation;
return isValid(groundyTaskType, onSuccess.value());
} else if (methodAnnotation instanceof OnFailure) {
OnFailure onFailure = (OnFailure) methodAnnotation;
return isValid(groundyTaskType, onFailure.value());
} else if (methodAnnotation instanceof OnProgress) {
OnProgress onProgress = (OnProgress) methodAnnotation;
return isValid(groundyTaskType, onProgress.value());
} else if (methodAnnotation instanceof OnStart) {
OnStart onStart = (OnStart) methodAnnotation;
return isValid(groundyTaskType, onStart.value());
} else if (methodAnnotation instanceof OnCancel) {
OnCancel onCancel = (OnCancel) methodAnnotation;
return isValid(groundyTaskType, onCancel.value());
} else if (methodAnnotation instanceof OnCallback) {
OnCallback onCallback = (OnCallback) methodAnnotation;
return isValid(groundyTaskType, onCallback.value());
}
return true;
}
private boolean isValid(Class<?> groundyTaskType, Class<? extends GroundyTask>[] tasks) {
for (Class<? extends GroundyTask> task : tasks) {
if (task.isAssignableFrom(groundyTaskType)) return true;
}
return false;
}
private static Object[] getResultParams(Bundle resultData, MethodSpec methodSpec) {
Method method = methodSpec.method;
Object[] values = new Object[methodSpec.paramNames.size()];
Class<?>[] parameterTypes = method.getParameterTypes();
List<String> paramNames = methodSpec.paramNames;
for (int i = 0; i < paramNames.size(); i++) {
Class<?> parameterType = parameterTypes[i];
String paramName = paramNames.get(i);
values[i] = resultData.get(paramName);
if (values[i] == null) {
values[i] = defaultValue(parameterType);
} else {
if (!isTypeValid(parameterType, values[i].getClass())) {
throw new RuntimeException(paramName
+ " parameter is "
+ values[i].getClass().getSimpleName()
+ " but the method ("
+ method
+ ") expects "
+ parameterType.getSimpleName());
}
}
}
return values;
}
private static boolean isTypeValid(Class<?> expected, Class<?> actual) {
if (expected == Double.class || expected == double.class) {
return isAnyOf(actual, long.class, Long.class, int.class, Integer.class, double.class,
Double.class, float.class, Float.class);
} else if (expected == Float.class || expected == float.class) {
return isAnyOf(actual, int.class, Integer.class, float.class, Float.class);
} else if (expected == Long.class || expected == long.class) {
return isAnyOf(actual, int.class, Integer.class, Long.class, long.class);
} else if (expected == Integer.class || expected == int.class) {
return isAnyOf(actual, int.class, Integer.class);
} else if (expected == Boolean.class || expected == boolean.class) {
return isAnyOf(actual, boolean.class, Boolean.class);
}
return expected.isAssignableFrom(actual);
}
private static boolean isAnyOf(Class<?> foo, Class<?>... bars) {
for (Class<?> bar : bars) {
if (foo == bar) {
return true;
}
}
return false;
}
private static Object defaultValue(Class<?> parameterType) {
if (parameterType == int.class
|| parameterType == Integer.class
|| parameterType == float.class
|| parameterType == Float.class
|| parameterType == double.class
|| parameterType == Double.class
|| parameterType == long.class
|| parameterType == Long.class
|| parameterType == byte.class
|| parameterType == Byte.class
|| parameterType == char.class
|| parameterType == Character.class
|| parameterType == short.class
|| parameterType == Short.class) {
return 0;
} else if (parameterType == boolean.class || parameterType == Boolean.class) {
return false;
}
return null;
}
@Override public String toString() {
return "ReflectProxy{" +
"groundyTaskType=" + mTaskType +
", handlerType=" + mHandlerType +
'}';
}
static class MethodSpec {
final Method method;
final List<String> paramNames;
final String name;
MethodSpec(Method m, List<String> methodParams, String customName) {
method = m;
paramNames = methodParams;
name = customName;
}
}
}
|
Used getMethods instead of getDeclaredMethods in ReflectProxy
|
library/src/main/java/com/telly/groundy/ReflectProxy.java
|
Used getMethods instead of getDeclaredMethods in ReflectProxy
|
<ide><path>ibrary/src/main/java/com/telly/groundy/ReflectProxy.java
<ide> }
<ide>
<ide> private void fillMethodSpecMapWith(Class<?> type) {
<del> for (Method method : getDeclaredMethods(type)) {
<add> for (Method method : getMethods(type)) {
<ide> // register groundy callbacks
<ide> for (Class<?> groundyCallback : GROUNDY_CALLBACKS) {
<ide> //noinspection unchecked
<ide> }
<ide> }
<ide>
<del> private static Method[] getDeclaredMethods(Class<?> type) {
<add> private static Method[] getMethods(Class<?> type) {
<ide> if (!METHODS_CACHE.containsKey(type)) {
<del> METHODS_CACHE.put(type, type.getDeclaredMethods());
<add> METHODS_CACHE.put(type, type.getMethods());
<ide> }
<ide> return METHODS_CACHE.get(type);
<ide> }
|
|
JavaScript
|
mit
|
17cadb97220901c8bfebf03c154b15802824e7c6
| 0 |
cheminfo/eln-plugin
|
src/types/sample/cv.js
|
import common from '../common';
export default {
jpath: ['spectra', 'cv'],
find: common.basenameFind,
getProperty: common.getTargetProperty,
process: common.getMetaFromJcamp,
};
|
Revert "feat: add CV"
This reverts commit 13ac5895ea1b9943f9d582010a402c1d8dfcf875.
|
src/types/sample/cv.js
|
Revert "feat: add CV"
|
<ide><path>rc/types/sample/cv.js
<del>import common from '../common';
<del>
<del>export default {
<del> jpath: ['spectra', 'cv'],
<del> find: common.basenameFind,
<del> getProperty: common.getTargetProperty,
<del> process: common.getMetaFromJcamp,
<del>};
|
||
Java
|
mit
|
ac2d53621e3a063c20634de639301c791e5a8546
| 0 |
jhshinn/jabref,sauliusg/jabref,bartsch-dev/jabref,jhshinn/jabref,Mr-DLib/jabref,mairdl/jabref,motokito/jabref,obraliar/jabref,grimes2/jabref,obraliar/jabref,Braunch/jabref,zellerdev/jabref,Siedlerchr/jabref,jhshinn/jabref,jhshinn/jabref,ayanai1/jabref,tschechlovdev/jabref,Siedlerchr/jabref,tobiasdiez/jabref,motokito/jabref,zellerdev/jabref,bartsch-dev/jabref,shitikanth/jabref,obraliar/jabref,obraliar/jabref,Braunch/jabref,JabRef/jabref,mredaelli/jabref,tobiasdiez/jabref,mredaelli/jabref,tobiasdiez/jabref,oscargus/jabref,grimes2/jabref,JabRef/jabref,Braunch/jabref,motokito/jabref,ayanai1/jabref,grimes2/jabref,tobiasdiez/jabref,oscargus/jabref,Braunch/jabref,Braunch/jabref,jhshinn/jabref,ayanai1/jabref,sauliusg/jabref,mairdl/jabref,bartsch-dev/jabref,Mr-DLib/jabref,tschechlovdev/jabref,mredaelli/jabref,shitikanth/jabref,zellerdev/jabref,shitikanth/jabref,bartsch-dev/jabref,mredaelli/jabref,zellerdev/jabref,Mr-DLib/jabref,tschechlovdev/jabref,zellerdev/jabref,shitikanth/jabref,mairdl/jabref,bartsch-dev/jabref,grimes2/jabref,Mr-DLib/jabref,shitikanth/jabref,mairdl/jabref,Siedlerchr/jabref,obraliar/jabref,JabRef/jabref,sauliusg/jabref,motokito/jabref,oscargus/jabref,sauliusg/jabref,Mr-DLib/jabref,ayanai1/jabref,motokito/jabref,tschechlovdev/jabref,ayanai1/jabref,oscargus/jabref,mairdl/jabref,oscargus/jabref,grimes2/jabref,Siedlerchr/jabref,mredaelli/jabref,tschechlovdev/jabref,JabRef/jabref
|
/* Copyright (C) 2012 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.gui;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoableEdit;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import net.sf.jabref.AbstractWorker;
import net.sf.jabref.BasePanel;
import net.sf.jabref.BibtexEntry;
import net.sf.jabref.CheckBoxMessage;
import net.sf.jabref.GUIGlobals;
import net.sf.jabref.Globals;
import net.sf.jabref.ImportSettingsTab;
import net.sf.jabref.JabRefFrame;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.Util;
import net.sf.jabref.external.ExternalFileType;
import net.sf.jabref.undo.NamedCompound;
import net.sf.jabref.undo.UndoableFieldChange;
public class CleanUpAction extends AbstractWorker {
private Logger logger = Logger.getLogger(CleanUpAction.class.getName());
public final static String
AKS_AUTO_NAMING_PDFS_AGAIN = "AskAutoNamingPDFsAgain",
CLEANUP_DOI = "CleanUpDOI",
CLEANUP_MONTH = "CleanUpMonth",
CLEANUP_PAGENUMBERS = "CleanUpPageNumbers",
CLEANUP_MAKEPATHSRELATIVE = "CleanUpMakePathsRelative",
CLEANUP_RENAMEPDF = "CleanUpRenamePDF",
CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS = "CleanUpRenamePDFonlyRelativePaths",
CLEANUP_SUPERSCRIPTS = "CleanUpSuperscripts";
public static void putDefaults(HashMap<String, Object> defaults) {
defaults.put(AKS_AUTO_NAMING_PDFS_AGAIN, Boolean.TRUE);
defaults.put(CLEANUP_SUPERSCRIPTS, Boolean.TRUE);
defaults.put(CLEANUP_DOI, Boolean.TRUE);
defaults.put(CLEANUP_MONTH, Boolean.TRUE);
defaults.put(CLEANUP_PAGENUMBERS, Boolean.TRUE);
defaults.put(CLEANUP_MAKEPATHSRELATIVE, Boolean.TRUE);
defaults.put(CLEANUP_RENAMEPDF, Boolean.TRUE);
defaults.put(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS, Boolean.FALSE);
}
private JCheckBox cleanUpSuperscrips;
private JCheckBox cleanUpDOI;
private JCheckBox cleanUpMonth;
private JCheckBox cleanUpPageNumbers;
private JCheckBox cleanUpMakePathsRelative;
private JCheckBox cleanUpRenamePDF;
private JCheckBox cleanUpRenamePDFonlyRelativePaths;
private JPanel optionsPanel = new JPanel();
private BasePanel panel;
private JabRefFrame frame;
// global variable to count unsucessful Renames
int unsuccesfullRenames = 0;
public CleanUpAction(BasePanel panel) {
this.panel = panel;
this.frame = panel.frame();
initOptionsPanel();
}
private void initOptionsPanel() {
cleanUpSuperscrips = new JCheckBox(Globals.lang("Convert 1st, 2nd, ... to real superscripts"));
cleanUpDOI = new JCheckBox(Globals.lang("Move DOIs from note and URL field to DOI field and remove http prefix"));
cleanUpMonth = new JCheckBox(Globals.lang("Format content of month field to #mon#"));
cleanUpPageNumbers = new JCheckBox(Globals.lang("Ensure that page ranges are of the form num1--num2"));
cleanUpMakePathsRelative = new JCheckBox(Globals.lang("Make paths of linked files relative (if possible)"));
cleanUpRenamePDF = new JCheckBox(Globals.lang("Rename PDFs to given file name format pattern"));
cleanUpRenamePDF.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
cleanUpRenamePDFonlyRelativePaths.setEnabled(cleanUpRenamePDF.isSelected());
}
});
cleanUpRenamePDFonlyRelativePaths = new JCheckBox(Globals.lang("Rename only PDFs having a relative path"));
optionsPanel = new JPanel();
retrieveSettings();
FormLayout layout = new FormLayout("left:15dlu,pref:grow", "pref, pref, pref, pref, pref, pref, pref, pref");
DefaultFormBuilder builder = new DefaultFormBuilder(layout, optionsPanel);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.add(cleanUpSuperscrips, cc.xyw(1,1,2));
builder.add(cleanUpDOI, cc.xyw(1,2,2));
builder.add(cleanUpMonth, cc.xyw(1,3,2));
builder.add(cleanUpPageNumbers, cc.xyw(1,4,2));
builder.add(cleanUpMakePathsRelative, cc.xyw(1,5,2));
builder.add(cleanUpRenamePDF, cc.xyw(1,6,2));
String currentPattern = Globals.lang("File name format pattern").concat(": ").concat(Globals.prefs.get(ImportSettingsTab.PREF_IMPORT_FILENAMEPATTERN));
builder.add(new JLabel(currentPattern), cc.xyw(2,7,1));
builder.add(cleanUpRenamePDFonlyRelativePaths, cc.xyw(2,8,1));
}
private void retrieveSettings() {
cleanUpSuperscrips.setSelected(Globals.prefs.getBoolean(CLEANUP_SUPERSCRIPTS));
cleanUpDOI.setSelected(Globals.prefs.getBoolean(CLEANUP_DOI));
cleanUpMonth.setSelected(Globals.prefs.getBoolean(CLEANUP_MONTH));
cleanUpPageNumbers.setSelected(Globals.prefs.getBoolean(CLEANUP_PAGENUMBERS));
cleanUpMakePathsRelative.setSelected(Globals.prefs.getBoolean(CLEANUP_MAKEPATHSRELATIVE));
cleanUpRenamePDF.setSelected(Globals.prefs.getBoolean(CLEANUP_RENAMEPDF));
cleanUpRenamePDFonlyRelativePaths.setSelected(Globals.prefs.getBoolean(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS));
cleanUpRenamePDFonlyRelativePaths.setEnabled(cleanUpRenamePDF.isSelected());
}
private void storeSettings() {
Globals.prefs.putBoolean(CLEANUP_SUPERSCRIPTS, cleanUpSuperscrips.isSelected());
Globals.prefs.putBoolean(CLEANUP_DOI, cleanUpDOI.isSelected());
Globals.prefs.putBoolean(CLEANUP_MONTH, cleanUpMonth.isSelected());
Globals.prefs.putBoolean(CLEANUP_PAGENUMBERS, cleanUpPageNumbers.isSelected());
Globals.prefs.putBoolean(CLEANUP_MAKEPATHSRELATIVE, cleanUpMakePathsRelative.isSelected());
Globals.prefs.putBoolean(CLEANUP_RENAMEPDF, cleanUpRenamePDF.isSelected());
Globals.prefs.putBoolean(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS, cleanUpRenamePDFonlyRelativePaths.isSelected());
}
private int showCleanUpDialog() {
String dialogTitle = Globals.lang("Cleanup entries");
Object[] messages = {Globals.lang("What would you like to clean up?"), optionsPanel};
return JOptionPane.showConfirmDialog(frame, messages, dialogTitle,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
}
boolean cancelled;
int modifiedEntriesCount;
int numSelected;
public void init() {
cancelled = false;
modifiedEntriesCount = 0;
int numSelected = panel.getSelectedEntries().length;
if (numSelected == 0) { // None selected. Inform the user to select entries first.
JOptionPane.showMessageDialog(frame, Globals.lang("First select entries to clean up."),
Globals.lang("Cleanup entry"), JOptionPane.INFORMATION_MESSAGE);
cancelled = true;
return;
}
frame.block();
panel.output(Globals.lang("Doing a cleanup for %0 entries...", Integer.toString(numSelected)));
}
public void run() {
if (cancelled) return;
int choice = showCleanUpDialog();
if (choice != JOptionPane.OK_OPTION) {
cancelled = true;
return;
}
storeSettings();
boolean
choiceCleanUpSuperscripts = cleanUpSuperscrips.isSelected(),
choiceCleanUpDOI = cleanUpDOI.isSelected(),
choiceCleanUpMonth = cleanUpMonth.isSelected(),
choiceCleanUpPageNumbers = cleanUpPageNumbers.isSelected(),
choiceMakePathsRelative = cleanUpMakePathsRelative.isSelected(),
choiceRenamePDF = cleanUpRenamePDF.isSelected();
if (choiceRenamePDF && Globals.prefs.getBoolean(AKS_AUTO_NAMING_PDFS_AGAIN)) {
CheckBoxMessage cbm = new CheckBoxMessage(Globals.lang("Auto-generating PDF-Names does not support undo. Continue?"),
Globals.lang("Disable this confirmation dialog"), false);
int answer = JOptionPane.showConfirmDialog(frame, cbm, Globals.lang("Autogenerate PDF Names"),
JOptionPane.YES_NO_OPTION);
if (cbm.isSelected())
Globals.prefs.putBoolean(AKS_AUTO_NAMING_PDFS_AGAIN, false);
if (answer == JOptionPane.NO_OPTION) {
cancelled = true;
return;
}
}
for (BibtexEntry entry : panel.getSelectedEntries()) {
// undo granularity is on entry level
NamedCompound ce = new NamedCompound(Globals.lang("Cleanup entry"));
if (choiceCleanUpSuperscripts) doCleanUpSuperscripts(entry, ce);
if (choiceCleanUpDOI) doCleanUpDOI(entry, ce);
if (choiceCleanUpMonth) doCleanUpMonth(entry, ce);
if (choiceCleanUpPageNumbers) doCleanUpPageNumbers(entry, ce);
if (choiceMakePathsRelative) doMakePathsRelative(entry, ce);
if (choiceRenamePDF) doRenamePDFs(entry, ce);
ce.end();
if (ce.hasEdits()) {
modifiedEntriesCount++;
panel.undoManager.addEdit(ce);
}
}
}
public void update() {
if (cancelled) {
frame.unblock();
return;
}
if(unsuccesfullRenames>0) { //Rename failed for at least one entry
JOptionPane.showMessageDialog(frame, Globals.lang("File rename failed for")+" "
+ unsuccesfullRenames
+ " "+Globals.lang("entries") + ".",
Globals.lang("Autogenerate PDF Names"), JOptionPane.INFORMATION_MESSAGE);
}
if (modifiedEntriesCount>0) {
panel.updateEntryEditorIfShowing();
panel.markBaseChanged() ;
}
String message;
switch (modifiedEntriesCount) {
case 0:
message = Globals.lang("No entry needed a clean up");
break;
case 1:
message = Globals.lang("One entry needed a clean up");
break;
default:
message = Globals.lang("%0 entries needed a clean up");
break;
}
panel.output(message);
frame.unblock();
}
/**
* Converts the text in 1st, 2nd, ... to real superscripts by wrapping in \textsuperscript{st}, ...
*/
private void doCleanUpSuperscripts(BibtexEntry entry, NamedCompound ce) {
final String field = "booktitle";
String oldValue = entry.getField(field);
if (oldValue == null) return;
String newValue = oldValue.replaceAll(" (\\d+)(st|nd|rd|th) ", " $1\\\\textsuperscript{$2} ");
if (!oldValue.equals(newValue)) {
entry.setField(field, newValue);
ce.addEdit(new UndoableFieldChange(entry, field, oldValue, newValue));
}
}
/**
* Removes the http://... for each DOI
* Moves DOIs from URL and NOTE filed to DOI field
* @param ce
*/
private void doCleanUpDOI(BibtexEntry bes, NamedCompound ce) {
// fields to check
String[] fields = {"note", "url", "ee"};
// First check if the DOI Field is empty
if (bes.getField("doi") != null) {
String doiFieldValue = bes.getField("doi");
if (Util.checkForDOIwithHTTPprefix(doiFieldValue)) {
String newValue = Util.getDOI(doiFieldValue);
ce.addEdit(new UndoableFieldChange(bes, "doi", doiFieldValue, newValue));
bes.setField("doi", newValue);
};
if (Util.checkForPlainDOI(doiFieldValue)) {
// DOI field seems to contain DOI
// cleanup note, url, ee field
// we do NOT copy values to the DOI field as the DOI field contains a DOI!
for (String field: fields) {
if (Util.checkForPlainDOI(bes.getField(field))){
Util.removeDOIfromBibtexEntryField(bes, field, ce);
}
}
}
} else {
// As the DOI field is empty we now check if note, url, or ee field contains a DOI
for (String field: fields) {
if (Util.checkForPlainDOI(bes.getField(field))){
// update DOI
String oldValue = bes.getField("doi");
String newValue = Util.getDOI(bes.getField(field));
ce.addEdit(new UndoableFieldChange(bes, "doi", oldValue, newValue));
bes.setField("doi", newValue);
Util.removeDOIfromBibtexEntryField(bes, field, ce);
}
}
}
}
private void doCleanUpMonth(BibtexEntry entry, NamedCompound ce) {
// implementation based on patch 3470076 by Mathias Walter
String oldValue = entry.getField("month");
if (oldValue == null) return;
String newValue = oldValue;
try {
int month = Integer.parseInt(newValue);
newValue = new StringBuffer("#").append(Globals.MONTHS[month - 1]).append('#').toString();
} catch (NumberFormatException e) {
// adapt casing of newValue to follow entry in Globals_MONTH_STRINGS
String casedString = newValue.substring(0, 1).toUpperCase().concat(newValue.substring(1).toLowerCase());
if (Globals.MONTH_STRINGS.containsKey(newValue.toLowerCase()) ||
Globals.MONTH_STRINGS.containsValue(casedString)) {
newValue = new StringBuffer("#").append(newValue.substring(0, 3).toLowerCase()).append('#').toString();
}
}
if (!oldValue.equals(newValue)) {
entry.setField("month", newValue);
ce.addEdit(new UndoableFieldChange(entry, "month", oldValue, newValue));
}
}
private void doCleanUpPageNumbers(BibtexEntry entry, NamedCompound ce) {
String oldValue = entry.getField("pages");
if (oldValue == null) return;
String newValue = oldValue.replaceAll("(\\d+) *- *(\\d+)", "$1--$2");
if (!oldValue.equals(newValue)) {
entry.setField("pages", newValue);
ce.addEdit(new UndoableFieldChange(entry, "pages", oldValue, newValue));
}
}
private void doExportToKeywords(BibtexEntry entry, NamedCompound ce) {
}
private void doImportFromKeywords(BibtexEntry entry, NamedCompound ce) {
}
private void doMakePathsRelative(BibtexEntry entry, NamedCompound ce) {
String oldValue = entry.getField(GUIGlobals.FILE_FIELD);
if (oldValue == null) return;
FileListTableModel flModel = new FileListTableModel();
flModel.setContent(oldValue);
if (flModel.getRowCount() == 0) {
return;
}
boolean changed = false;
for (int i = 0; i<flModel.getRowCount(); i++) {
FileListEntry flEntry = flModel.getEntry(i);
String oldFileName = flEntry.getLink();
String newFileName = Util.shortenFileName(new File(oldFileName), panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD)).toString();
if (!oldFileName.equals(newFileName)) {
flEntry.setLink(newFileName);
changed = true;
}
}
if (changed) {
String newValue = flModel.getStringRepresentation();
assert(!oldValue.equals(newValue));
entry.setField(GUIGlobals.FILE_FIELD, newValue);
ce.addEdit(new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue));
}
}
private void doRenamePDFs(BibtexEntry entry, NamedCompound ce) {
//Extract the path
String oldValue = entry.getField(GUIGlobals.FILE_FIELD);
if (oldValue == null) return;
FileListTableModel flModel = new FileListTableModel();
flModel.setContent(oldValue);
if (flModel.getRowCount() == 0) {
return;
}
boolean changed = false;
for (int i=0; i<flModel.getRowCount(); i++) {
String realOldFilename = flModel.getEntry(i).getLink();
if (cleanUpRenamePDFonlyRelativePaths.isSelected() && (new File(realOldFilename).isAbsolute()))
return;
String newFilename = Util.getLinkedFileName(panel.database(), entry);
//String oldFilename = bes.getField(GUIGlobals.FILE_FIELD); // would have to be stored for undoing purposes
//Add extension to newFilename
newFilename = newFilename + "." + flModel.getEntry(i).getType().getExtension();
//get new Filename with path
//Create new Path based on old Path and new filename
File expandedOldFile = Util.expandFilename(realOldFilename, panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD));
String newPath = expandedOldFile.getParent().concat(System.getProperty("file.separator")).concat(newFilename);
if (new File(newPath).exists())
// we do not overwrite files
// TODO: we could check here if the newPath file is linked with the current entry. And if not, we could add a link
return;
//do rename
boolean renameSuccesfull = Util.renameFile(expandedOldFile.toString(), newPath);
if (renameSuccesfull) {
changed = true;
//Change the path for this entry
String description = flModel.getEntry(i).getDescription();
ExternalFileType type = flModel.getEntry(i).getType();
flModel.removeEntry(i);
// we cannot use "newPath" to generate a FileListEntry as newPath is absolute, but we want to keep relative paths whenever possible
File parent = (new File(realOldFilename)).getParentFile();
String newFileEntryFileName;
if (parent == null) {
newFileEntryFileName = newFilename;
} else {
newFileEntryFileName = parent.toString().concat(System.getProperty("file.separator")).concat(newFilename);
}
flModel.addEntry(i, new FileListEntry(description, newFileEntryFileName, type));
}
else {
unsuccesfullRenames++;
}
}
if (changed) {
String newValue = flModel.getStringRepresentation();
assert(!oldValue.equals(newValue));
entry.setField(GUIGlobals.FILE_FIELD, newValue);
//we put an undo of the field content here
//the file is not being renamed back, which leads to inconsostencies
//if we put a null undo object here, the change by "doMakePathsRelative" would overwrite the field value nevertheless.
ce.addEdit(new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue));
}
}
}
|
src/java/net/sf/jabref/gui/CleanUpAction.java
|
/* Copyright (C) 2012 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.gui;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoableEdit;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import net.sf.jabref.AbstractWorker;
import net.sf.jabref.BasePanel;
import net.sf.jabref.BibtexEntry;
import net.sf.jabref.CheckBoxMessage;
import net.sf.jabref.GUIGlobals;
import net.sf.jabref.Globals;
import net.sf.jabref.ImportSettingsTab;
import net.sf.jabref.JabRefFrame;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.Util;
import net.sf.jabref.external.ExternalFileType;
import net.sf.jabref.undo.NamedCompound;
import net.sf.jabref.undo.UndoableFieldChange;
public class CleanUpAction extends AbstractWorker {
private Logger logger = Logger.getLogger(CleanUpAction.class.getName());
public final static String
AKS_AUTO_NAMING_PDFS_AGAIN = "AskAutoNamingPDFsAgain",
CLEANUP_DOI = "CleanUpDOI",
CLEANUP_MONTH = "CleanUpMonth",
CLEANUP_PAGENUMBERS = "CleanUpPageNumbers",
CLEANUP_MAKEPATHSRELATIVE = "CleanUpMakePathsRelative",
CLEANUP_RENAMEPDF = "CleanUpRenamePDF",
CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS = "CleanUpRenamePDFonlyRelativePaths",
CLEANUP_SUPERSCRIPTS = "CleanUpSuperscripts";
public static void putDefaults(HashMap<String, Object> defaults) {
defaults.put(AKS_AUTO_NAMING_PDFS_AGAIN, Boolean.TRUE);
defaults.put(CLEANUP_SUPERSCRIPTS, Boolean.TRUE);
defaults.put(CLEANUP_DOI, Boolean.TRUE);
defaults.put(CLEANUP_MONTH, Boolean.TRUE);
defaults.put(CLEANUP_PAGENUMBERS, Boolean.TRUE);
defaults.put(CLEANUP_MAKEPATHSRELATIVE, Boolean.TRUE);
defaults.put(CLEANUP_RENAMEPDF, Boolean.TRUE);
defaults.put(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS, Boolean.FALSE);
}
private JCheckBox cleanUpSuperscrips;
private JCheckBox cleanUpDOI;
private JCheckBox cleanUpMonth;
private JCheckBox cleanUpPageNumbers;
private JCheckBox cleanUpMakePathsRelative;
private JCheckBox cleanUpRenamePDF;
private JCheckBox cleanUpRenamePDFonlyRelativePaths;
private JPanel optionsPanel = new JPanel();
private BasePanel panel;
private JabRefFrame frame;
// global variable to count unsucessful Renames
int unsuccesfullRenames = 0;
public CleanUpAction(BasePanel panel) {
this.panel = panel;
this.frame = panel.frame();
initOptionsPanel();
}
private void initOptionsPanel() {
cleanUpSuperscrips = new JCheckBox(Globals.lang("Convert 1st, 2nd, ... to real superscripts"));
cleanUpDOI = new JCheckBox(Globals.lang("Move DOIs from note and URL field to DOI field and remove http prefix"));
cleanUpMonth = new JCheckBox(Globals.lang("Format content of month field to #mon#"));
cleanUpPageNumbers = new JCheckBox(Globals.lang("Ensure that page ranges are of the form num1--num2"));
cleanUpMakePathsRelative = new JCheckBox(Globals.lang("Make paths of linked files relative (if possible)"));
cleanUpRenamePDF = new JCheckBox(Globals.lang("Rename PDFs to given file name format pattern"));
cleanUpRenamePDF.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
cleanUpRenamePDFonlyRelativePaths.setEnabled(cleanUpRenamePDF.isSelected());
}
});
cleanUpRenamePDFonlyRelativePaths = new JCheckBox(Globals.lang("Rename only PDFs having a relative path"));
optionsPanel = new JPanel();
retrieveSettings();
FormLayout layout = new FormLayout("left:15dlu,pref", "pref, pref, pref, pref, pref, pref, pref, pref");
DefaultFormBuilder builder = new DefaultFormBuilder(layout, optionsPanel);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.add(cleanUpSuperscrips, cc.xyw(1,1,2));
builder.add(cleanUpDOI, cc.xyw(1,2,2));
builder.add(cleanUpMonth, cc.xyw(1,3,2));
builder.add(cleanUpPageNumbers, cc.xyw(1,4,2));
builder.add(cleanUpMakePathsRelative, cc.xyw(1,5,2));
builder.add(cleanUpRenamePDF, cc.xyw(1,6,2));
String currentPattern = Globals.lang("File name format pattern").concat(": ").concat(Globals.prefs.get(ImportSettingsTab.PREF_IMPORT_FILENAMEPATTERN));
builder.add(new JLabel(currentPattern), cc.xyw(2,7,1));
builder.add(cleanUpRenamePDFonlyRelativePaths, cc.xyw(2,8,1));
}
private void retrieveSettings() {
cleanUpSuperscrips.setSelected(Globals.prefs.getBoolean(CLEANUP_SUPERSCRIPTS));
cleanUpDOI.setSelected(Globals.prefs.getBoolean(CLEANUP_DOI));
cleanUpMonth.setSelected(Globals.prefs.getBoolean(CLEANUP_MONTH));
cleanUpPageNumbers.setSelected(Globals.prefs.getBoolean(CLEANUP_PAGENUMBERS));
cleanUpMakePathsRelative.setSelected(Globals.prefs.getBoolean(CLEANUP_MAKEPATHSRELATIVE));
cleanUpRenamePDF.setSelected(Globals.prefs.getBoolean(CLEANUP_RENAMEPDF));
cleanUpRenamePDFonlyRelativePaths.setSelected(Globals.prefs.getBoolean(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS));
cleanUpRenamePDFonlyRelativePaths.setEnabled(cleanUpRenamePDF.isSelected());
}
private void storeSettings() {
Globals.prefs.putBoolean(CLEANUP_SUPERSCRIPTS, cleanUpSuperscrips.isSelected());
Globals.prefs.putBoolean(CLEANUP_DOI, cleanUpDOI.isSelected());
Globals.prefs.putBoolean(CLEANUP_MONTH, cleanUpMonth.isSelected());
Globals.prefs.putBoolean(CLEANUP_PAGENUMBERS, cleanUpPageNumbers.isSelected());
Globals.prefs.putBoolean(CLEANUP_MAKEPATHSRELATIVE, cleanUpMakePathsRelative.isSelected());
Globals.prefs.putBoolean(CLEANUP_RENAMEPDF, cleanUpRenamePDF.isSelected());
Globals.prefs.putBoolean(CLEANUP_RENAMEPDF_ONLYRELATIVE_PATHS, cleanUpRenamePDFonlyRelativePaths.isSelected());
}
private int showCleanUpDialog() {
String dialogTitle = Globals.lang("Cleanup entries");
Object[] messages = {Globals.lang("What would you like to clean up?"), optionsPanel};
return JOptionPane.showConfirmDialog(frame, messages, dialogTitle,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
}
boolean cancelled;
int modifiedEntriesCount;
int numSelected;
public void init() {
cancelled = false;
modifiedEntriesCount = 0;
int numSelected = panel.getSelectedEntries().length;
if (numSelected == 0) { // None selected. Inform the user to select entries first.
JOptionPane.showMessageDialog(frame, Globals.lang("First select entries to clean up."),
Globals.lang("Cleanup entry"), JOptionPane.INFORMATION_MESSAGE);
cancelled = true;
return;
}
frame.block();
panel.output(Globals.lang("Doing a cleanup for %0 entries...", Integer.toString(numSelected)));
}
public void run() {
if (cancelled) return;
int choice = showCleanUpDialog();
if (choice != JOptionPane.OK_OPTION) {
cancelled = true;
return;
}
storeSettings();
boolean
choiceCleanUpSuperscripts = cleanUpSuperscrips.isSelected(),
choiceCleanUpDOI = cleanUpDOI.isSelected(),
choiceCleanUpMonth = cleanUpMonth.isSelected(),
choiceCleanUpPageNumbers = cleanUpPageNumbers.isSelected(),
choiceMakePathsRelative = cleanUpMakePathsRelative.isSelected(),
choiceRenamePDF = cleanUpRenamePDF.isSelected();
if (choiceRenamePDF && Globals.prefs.getBoolean(AKS_AUTO_NAMING_PDFS_AGAIN)) {
CheckBoxMessage cbm = new CheckBoxMessage(Globals.lang("Auto-generating PDF-Names does not support undo. Continue?"),
Globals.lang("Disable this confirmation dialog"), false);
int answer = JOptionPane.showConfirmDialog(frame, cbm, Globals.lang("Autogenerate PDF Names"),
JOptionPane.YES_NO_OPTION);
if (cbm.isSelected())
Globals.prefs.putBoolean(AKS_AUTO_NAMING_PDFS_AGAIN, false);
if (answer == JOptionPane.NO_OPTION) {
cancelled = true;
return;
}
}
for (BibtexEntry entry : panel.getSelectedEntries()) {
// undo granularity is on entry level
NamedCompound ce = new NamedCompound(Globals.lang("Cleanup entry"));
if (choiceCleanUpSuperscripts) doCleanUpSuperscripts(entry, ce);
if (choiceCleanUpDOI) doCleanUpDOI(entry, ce);
if (choiceCleanUpMonth) doCleanUpMonth(entry, ce);
if (choiceCleanUpPageNumbers) doCleanUpPageNumbers(entry, ce);
if (choiceMakePathsRelative) doMakePathsRelative(entry, ce);
if (choiceRenamePDF) doRenamePDFs(entry, ce);
ce.end();
if (ce.hasEdits()) {
modifiedEntriesCount++;
panel.undoManager.addEdit(ce);
}
}
}
public void update() {
if (cancelled) {
frame.unblock();
return;
}
if(unsuccesfullRenames>0) { //Rename failed for at least one entry
JOptionPane.showMessageDialog(frame, Globals.lang("File rename failed for")+" "
+ unsuccesfullRenames
+ " "+Globals.lang("entries") + ".",
Globals.lang("Autogenerate PDF Names"), JOptionPane.INFORMATION_MESSAGE);
}
if (modifiedEntriesCount>0) {
panel.updateEntryEditorIfShowing();
panel.markBaseChanged() ;
}
String message;
switch (modifiedEntriesCount) {
case 0:
message = Globals.lang("No entry needed a clean up");
break;
case 1:
message = Globals.lang("One entry needed a clean up");
break;
default:
message = Globals.lang("%0 entries needed a clean up");
break;
}
panel.output(message);
frame.unblock();
}
/**
* Converts the text in 1st, 2nd, ... to real superscripts by wrapping in \textsuperscript{st}, ...
*/
private void doCleanUpSuperscripts(BibtexEntry entry, NamedCompound ce) {
final String field = "booktitle";
String oldValue = entry.getField(field);
if (oldValue == null) return;
String newValue = oldValue.replaceAll(" (\\d+)(st|nd|rd|th) ", " $1\\\\textsuperscript{$2} ");
if (!oldValue.equals(newValue)) {
entry.setField(field, newValue);
ce.addEdit(new UndoableFieldChange(entry, field, oldValue, newValue));
}
}
/**
* Removes the http://... for each DOI
* Moves DOIs from URL and NOTE filed to DOI field
* @param ce
*/
private void doCleanUpDOI(BibtexEntry bes, NamedCompound ce) {
// fields to check
String[] fields = {"note", "url", "ee"};
// First check if the DOI Field is empty
if (bes.getField("doi") != null) {
String doiFieldValue = bes.getField("doi");
if (Util.checkForDOIwithHTTPprefix(doiFieldValue)) {
String newValue = Util.getDOI(doiFieldValue);
ce.addEdit(new UndoableFieldChange(bes, "doi", doiFieldValue, newValue));
bes.setField("doi", newValue);
};
if (Util.checkForPlainDOI(doiFieldValue)) {
// DOI field seems to contain DOI
// cleanup note, url, ee field
// we do NOT copy values to the DOI field as the DOI field contains a DOI!
for (String field: fields) {
if (Util.checkForPlainDOI(bes.getField(field))){
Util.removeDOIfromBibtexEntryField(bes, field, ce);
}
}
}
} else {
// As the DOI field is empty we now check if note, url, or ee field contains a DOI
for (String field: fields) {
if (Util.checkForPlainDOI(bes.getField(field))){
// update DOI
String oldValue = bes.getField("doi");
String newValue = Util.getDOI(bes.getField(field));
ce.addEdit(new UndoableFieldChange(bes, "doi", oldValue, newValue));
bes.setField("doi", newValue);
Util.removeDOIfromBibtexEntryField(bes, field, ce);
}
}
}
}
private void doCleanUpMonth(BibtexEntry entry, NamedCompound ce) {
// implementation based on patch 3470076 by Mathias Walter
String oldValue = entry.getField("month");
if (oldValue == null) return;
String newValue = oldValue;
try {
int month = Integer.parseInt(newValue);
newValue = new StringBuffer("#").append(Globals.MONTHS[month - 1]).append('#').toString();
} catch (NumberFormatException e) {
// adapt casing of newValue to follow entry in Globals_MONTH_STRINGS
String casedString = newValue.substring(0, 1).toUpperCase().concat(newValue.substring(1).toLowerCase());
if (Globals.MONTH_STRINGS.containsKey(newValue.toLowerCase()) ||
Globals.MONTH_STRINGS.containsValue(casedString)) {
newValue = new StringBuffer("#").append(newValue.substring(0, 3).toLowerCase()).append('#').toString();
}
}
if (!oldValue.equals(newValue)) {
entry.setField("month", newValue);
ce.addEdit(new UndoableFieldChange(entry, "month", oldValue, newValue));
}
}
private void doCleanUpPageNumbers(BibtexEntry entry, NamedCompound ce) {
String oldValue = entry.getField("pages");
if (oldValue == null) return;
String newValue = oldValue.replaceAll("(\\d+) *- *(\\d+)", "$1--$2");
if (!oldValue.equals(newValue)) {
entry.setField("pages", newValue);
ce.addEdit(new UndoableFieldChange(entry, "pages", oldValue, newValue));
}
}
private void doExportToKeywords(BibtexEntry entry, NamedCompound ce) {
}
private void doImportFromKeywords(BibtexEntry entry, NamedCompound ce) {
}
private void doMakePathsRelative(BibtexEntry entry, NamedCompound ce) {
String oldValue = entry.getField(GUIGlobals.FILE_FIELD);
if (oldValue == null) return;
FileListTableModel flModel = new FileListTableModel();
flModel.setContent(oldValue);
if (flModel.getRowCount() == 0) {
return;
}
boolean changed = false;
for (int i = 0; i<flModel.getRowCount(); i++) {
FileListEntry flEntry = flModel.getEntry(i);
String oldFileName = flEntry.getLink();
String newFileName = Util.shortenFileName(new File(oldFileName), panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD)).toString();
if (!oldFileName.equals(newFileName)) {
flEntry.setLink(newFileName);
changed = true;
}
}
if (changed) {
String newValue = flModel.getStringRepresentation();
assert(!oldValue.equals(newValue));
entry.setField(GUIGlobals.FILE_FIELD, newValue);
ce.addEdit(new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue));
}
}
private void doRenamePDFs(BibtexEntry entry, NamedCompound ce) {
//Extract the path
String oldValue = entry.getField(GUIGlobals.FILE_FIELD);
if (oldValue == null) return;
FileListTableModel flModel = new FileListTableModel();
flModel.setContent(oldValue);
if (flModel.getRowCount() == 0) {
return;
}
boolean changed = false;
for (int i=0; i<flModel.getRowCount(); i++) {
String realOldFilename = flModel.getEntry(i).getLink();
if (cleanUpRenamePDFonlyRelativePaths.isSelected() && (new File(realOldFilename).isAbsolute()))
return;
String newFilename = Util.getLinkedFileName(panel.database(), entry);
//String oldFilename = bes.getField(GUIGlobals.FILE_FIELD); // would have to be stored for undoing purposes
//Add extension to newFilename
newFilename = newFilename + "." + flModel.getEntry(i).getType().getExtension();
//get new Filename with path
//Create new Path based on old Path and new filename
File expandedOldFile = Util.expandFilename(realOldFilename, panel.metaData().getFileDirectory(GUIGlobals.FILE_FIELD));
String newPath = expandedOldFile.getParent().concat(System.getProperty("file.separator")).concat(newFilename);
if (new File(newPath).exists())
// we do not overwrite files
// TODO: we could check here if the newPath file is linked with the current entry. And if not, we could add a link
return;
//do rename
boolean renameSuccesfull = Util.renameFile(expandedOldFile.toString(), newPath);
if (renameSuccesfull) {
changed = true;
//Change the path for this entry
String description = flModel.getEntry(i).getDescription();
ExternalFileType type = flModel.getEntry(i).getType();
flModel.removeEntry(i);
// we cannot use "newPath" to generate a FileListEntry as newPath is absolute, but we want to keep relative paths whenever possible
File parent = (new File(realOldFilename)).getParentFile();
String newFileEntryFileName;
if (parent == null) {
newFileEntryFileName = newFilename;
} else {
newFileEntryFileName = parent.toString().concat(System.getProperty("file.separator")).concat(newFilename);
}
flModel.addEntry(i, new FileListEntry(description, newFileEntryFileName, type));
}
else {
unsuccesfullRenames++;
}
}
if (changed) {
String newValue = flModel.getStringRepresentation();
assert(!oldValue.equals(newValue));
entry.setField(GUIGlobals.FILE_FIELD, newValue);
//we put an undo of the field content here
//the file is not being renamed back, which leads to inconsostencies
//if we put a null undo object here, the change by "doMakePathsRelative" would overwrite the field value nevertheless.
ce.addEdit(new UndoableFieldChange(entry, GUIGlobals.FILE_FIELD, oldValue, newValue));
}
}
}
|
Fixed sizing of Cleanup entries dialog.
|
src/java/net/sf/jabref/gui/CleanUpAction.java
|
Fixed sizing of Cleanup entries dialog.
|
<ide><path>rc/java/net/sf/jabref/gui/CleanUpAction.java
<ide> optionsPanel = new JPanel();
<ide> retrieveSettings();
<ide>
<del> FormLayout layout = new FormLayout("left:15dlu,pref", "pref, pref, pref, pref, pref, pref, pref, pref");
<add> FormLayout layout = new FormLayout("left:15dlu,pref:grow", "pref, pref, pref, pref, pref, pref, pref, pref");
<ide> DefaultFormBuilder builder = new DefaultFormBuilder(layout, optionsPanel);
<ide> builder.setDefaultDialogBorder();
<ide> CellConstraints cc = new CellConstraints();
|
|
Java
|
apache-2.0
|
e86efe14e40990279fd407cd33d8afe59e94d66b
| 0 |
jloisel/elastic-crud
|
package com.jeromeloisel.db.integration.test;
import org.elasticsearch.client.IndicesAdminClient;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
public class ESTest extends SpringElasticSearchTest {
@Test
public void shouldAutowire() {
assertNotNull(client);
final IndicesAdminClient indices = client.admin().indices();
indices.prepareCreate("test").execute().actionGet();
flush("test");
indices.prepareDelete("test").execute().actionGet();
}
@Test
@Override
public void shouldAutowireClient() {
super.shouldAutowireClient();
}
}
|
db-integration-test/src/test/java/com/jeromeloisel/db/integration/test/ESTest.java
|
package com.jeromeloisel.db.integration.test;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertNotNull;
public class ESTest extends SpringElasticSearchTest {
@Autowired
private Client client;
@Test
public void shouldAutowire() {
assertNotNull(client);
final IndicesAdminClient indices = client.admin().indices();
indices.prepareCreate("test").execute().actionGet();
flush("test");
indices.prepareDelete("test").execute().actionGet();
}
}
|
fix junit
|
db-integration-test/src/test/java/com/jeromeloisel/db/integration/test/ESTest.java
|
fix junit
|
<ide><path>b-integration-test/src/test/java/com/jeromeloisel/db/integration/test/ESTest.java
<ide> package com.jeromeloisel.db.integration.test;
<ide>
<del>import org.elasticsearch.client.Client;
<ide> import org.elasticsearch.client.IndicesAdminClient;
<ide> import org.junit.Test;
<del>import org.springframework.beans.factory.annotation.Autowired;
<ide>
<ide> import static org.junit.Assert.assertNotNull;
<ide>
<ide> public class ESTest extends SpringElasticSearchTest {
<ide>
<del> @Autowired
<del> private Client client;
<del>
<ide> @Test
<ide> public void shouldAutowire() {
<ide> assertNotNull(client);
<ide> flush("test");
<ide> indices.prepareDelete("test").execute().actionGet();
<ide> }
<add>
<add> @Test
<add> @Override
<add> public void shouldAutowireClient() {
<add> super.shouldAutowireClient();
<add> }
<ide> }
|
|
JavaScript
|
apache-2.0
|
0218e912ff3df8b6e42bc55944d436c6036ed911
| 0 |
dianwodaMobile/DWeex,Hanks10100/incubator-weex,miomin/incubator-weex,KalicyZhou/incubator-weex,acton393/incubator-weex,leoward/incubator-weex,acton393/incubator-weex,MrRaindrop/incubator-weex,erha19/incubator-weex,miomin/incubator-weex,dianwodaMobile/DWeex,miomin/incubator-weex,erha19/incubator-weex,weexteam/incubator-weex,leoward/incubator-weex,leoward/incubator-weex,weexteam/incubator-weex,leoward/incubator-weex,xiayun200825/weex,miomin/incubator-weex,Hanks10100/incubator-weex,erha19/incubator-weex,cxfeng1/incubator-weex,MrRaindrop/incubator-weex,MrRaindrop/incubator-weex,alibaba/weex,cxfeng1/incubator-weex,KalicyZhou/incubator-weex,erha19/incubator-weex,Hanks10100/incubator-weex,yuguitao/incubator-weex,alibaba/weex,cxfeng1/incubator-weex,MrRaindrop/incubator-weex,Hanks10100/incubator-weex,xiayun200825/weex,weexteam/incubator-weex,xiayun200825/weex,xiayun200825/weex,xiayun200825/weex,Hanks10100/incubator-weex,KalicyZhou/incubator-weex,erha19/incubator-weex,alibaba/weex,KalicyZhou/incubator-weex,erha19/incubator-weex,miomin/incubator-weex,acton393/incubator-weex,cxfeng1/incubator-weex,dianwodaMobile/DWeex,dianwodaMobile/DWeex,Hanks10100/incubator-weex,leoward/incubator-weex,dianwodaMobile/DWeex,acton393/incubator-weex,acton393/incubator-weex,acton393/incubator-weex,yuguitao/incubator-weex,yuguitao/incubator-weex,weexteam/incubator-weex,acton393/incubator-weex,MrRaindrop/incubator-weex,dianwodaMobile/DWeex,miomin/incubator-weex,erha19/incubator-weex,KalicyZhou/incubator-weex,MrRaindrop/incubator-weex,miomin/incubator-weex,weexteam/incubator-weex,xiayun200825/weex,Hanks10100/incubator-weex,acton393/incubator-weex,alibaba/weex,leoward/incubator-weex,yuguitao/incubator-weex,alibaba/weex,KalicyZhou/incubator-weex,alibaba/weex,Hanks10100/incubator-weex,yuguitao/incubator-weex,erha19/incubator-weex,cxfeng1/incubator-weex,miomin/incubator-weex,alibaba/weex,yuguitao/incubator-weex,cxfeng1/incubator-weex,weexteam/incubator-weex
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { schedule, danger, fail, warn, message, markdown } from "danger";
import fs from "fs";
import path from 'path';
import GitHubApi from 'github';
import parseDiff from 'parse-diff';
// Make sure there are changelog entries
const hasChangelog = danger.git.modified_files.includes("changelog.md")
if (!hasChangelog) { warn("No Changelog changes!") }
const jsFiles = danger.git.created_files.filter(path => path.endsWith("js"));
function absolute (relPath) {
return path.resolve(__dirname, relPath)
}
const flowIgnorePaths = [
'node_modules',
'test',
'build',
'examples',
'doc',
'android',
'ios',
'bin',
'dist',
'flow-typed'
].map(function (rel) {
return absolute(rel)
});
// new js files should have `@flow` at the top
const unFlowedFiles = jsFiles.filter(filepath => {
let i = 0
const len = flowIgnorePaths.length
while (i < len) {
const p = flowIgnorePaths[i]
if (absolute(filepath).indexOf(p) > -1) {
// ignore this file because it's in the flow-ignore-paths.
return false;
}
i++
}
const content = fs.readFileSync(filepath);
return !content.includes("@flow");
});
if (unFlowedFiles.length > 0) {
warn(
`These new JS files do not have Flow enabled: ${unFlowedFiles.join(", ")}`
);
}
// Error or Warn when delete public interface
var methion_break_change = false;
for (let c of danger.git.commits) {
// console.log("msg:" + c.message);
if (c.message && c.message.match(/break\s+change/i)) {
methion_break_change = true;
break;
}
}
// File name match any of these patterns will be ignored.
function is_ignored_public_check(file) {
var ignored_break_change_pattern = [
/^android\/sdk\/src\/test\/.+/,
/^android\/playground\/.+/
];
for (let p of ignored_break_change_pattern) {
if (file.match(p)) {
return true;
}
}
return false;
}
async function checkBreakChange(file){
var diff = await danger.git.diffForFile(file);
if (diff && diff.removed && diff.removed.match(/^-\s*?public\s+[\s\S]+$/gm)) {
if (methion_break_change) {
warn("Potential BREAK CHANGE. Modify public in " + file);
} else {
warn(
"Potential BREAK CHANGE. Modify public in " +
file +
" without metion it in commit message. You'd better add 'break change' in your commit log. "
);
}
}
}
var has_app_changes = false;
var has_test_changes = false;
var codefiles = [];
for (let file of danger.git.modified_files) {
if (file.match(/WeexSDK\/Source/)) {
has_app_changes = true;
} else if (file.match(/WeexSDKTests/)) {
has_test_changes = true;
}
if (!is_ignored_public_check(file) && file.endsWith(".java")) {
schedule(async ()=> {
await checkBreakChange(file)
})
}
if (
file.endsWith(".h") ||
file.endsWith(".m") ||
file.endsWith(".mm") ||
file.endsWith(".java") ||
file.endsWith(".js")
) {
codefiles.push(file);
}
}
if(danger.git.added_files){
for (let file of danger.git.added_files) {
if (
file.endsWith(".h") ||
file.endsWith(".m") ||
file.endsWith(".mm") ||
file.endsWith(".java") ||
file.endsWith(".js")
) {
codefiles.push(file);
}
}
}
if (danger.git.lines_of_code > 500) {
warn("Big PR");
}
if (danger.git.lines_of_code > 100 && has_app_changes && !has_test_changes) {
warn("This PR may need tests.");
}
//check ios copyright
//see scripts/rh/header.template
const copyright_header_components = [
"Licensed to the Apache Software Foundation \\(ASF\\) under one",
"or more contributor license agreements. See the NOTICE file",
"distributed with this work for additional information",
"regarding copyright ownership\\. The ASF licenses this file",
'to you under the Apache License, Version 2\\.0 \\(the',
'"License"\\); you may not use this file except in compliance',
'with the License\\. You may obtain a copy of the License at'
];
//path prefix
const ignoreCopyrightVerifyPath = [
'test',
'pre-build',
'android/playground/app/src/main/assets',
'android/sdk/assets',
'ios/playground/bundlejs',
'ios/sdk/WeexSDK/Resources',
'ios/sdk/WeexSDK/Sources/Layout'
]
codefiles.forEach(filepath => {
for(var i=ignoreCopyrightVerifyPath.length-1;i>=0;i--){
if(filepath.startsWith(ignoreCopyrightVerifyPath[i])){
return
}
}
const content = fs.readFileSync(filepath).toString();
for (const line of copyright_header_components) {
if (!content.match(new RegExp(line))) {
fail("Code file "+ filepath +" does not have the copyright header.");
return;
}
}
});
/*
* try to find the appropriate reviewer according to the blame info
* will be seperated to a danger plugin
*/
schedule(new Promise((resolve, reject) => {
try {
findReviewer(resolve, reject)
} catch (e) {
console.log(e)
resolve()
}
}));
function findReviewer(resolve, reject) {
var github = new GitHubApi({
protocol: "https",
host: "api.github.com",
});
var fileToDeletedLinesMap = {}
var fileToNormalLinesMap = {}
var fileToBlamesMap = {}
github.pullRequests.get({
owner: danger.github.pr.base.user.login,
repo: danger.github.pr.base.repo.name,
number: danger.github.pr.number,
headers: {Accept: 'application/vnd.github.diff'}
}, function (err, result) {
if ("undefined" === typeof result || "undefined" === typeof result.data || err) {
reject()
return
}
parseDeleteAndNormalLines(result.data, fileToDeletedLinesMap, fileToNormalLinesMap)
var promises = danger.git.modified_files.map(function(file) {
let repoURL = danger.github.pr.base.repo.html_url
let fileName = file.replace(/^.*[\\\/]/, '')
let blameURL = repoURL + '/blame/' + danger.github.pr.base.ref + '/' + file
// console.log("Getting blame html: " + blameURL)
return getContent(blameURL)
});
Promise.all(promises).then(datas => {
datas.forEach(function(data, index) {
fileToBlamesMap[danger.git.modified_files[index]] = parseBlame(data);
});
findBlameReviewers(fileToDeletedLinesMap, fileToNormalLinesMap, fileToBlamesMap)
resolve()
})
});
}
function getContent(url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
}
function parseDeleteAndNormalLines(diffData, fileToDeletedLinesMap, fileToNormalLinesMap) {
var diffs = parseDiff(diffData)
diffs.forEach(diff => {
fileToDeletedLinesMap[diff.from] = [];
fileToNormalLinesMap[diff.from] = [];
diff.chunks.forEach(chunk => {
chunk.changes.forEach(change => {
if (change.del) {
fileToDeletedLinesMap[diff.from].push(change.ln)
}
if (change.normal) {
fileToNormalLinesMap[diff.from].push(change.ln1)
}
})
})
})
}
function parseBlame(html) {
let regular = /(<img alt="@([^"]+)" class="avatar blame-commit-avatar"|<tr class="blame-line")/g
var match
var currentUser
var lines = []
while ((match = regular.exec(html)) !== null) {
let user = match[2]
if (user) {
currentUser = user
} else {
lines.push(currentUser)
}
}
return lines
}
function findBlameReviewers(fileToDeletedLinesMap, fileToNormalLinesMap, fileToBlamesMap) {
var reviewers = {};
// deleted lines get 3 points, normal line get 1 point
Object.keys(fileToDeletedLinesMap).forEach(function (file) {
let deletedLines = fileToDeletedLinesMap[file]
var blames = fileToBlamesMap[file]
deletedLines.forEach(lineNumber => {
var name = blames[lineNumber]
reviewers[name] = (reviewers[name] || 0) + 3
})
});
Object.keys(fileToNormalLinesMap).forEach(function (file) {
let normalLines = fileToNormalLinesMap[file];
var blames = fileToBlamesMap[file]
normalLines.forEach(lineNumber => {
var name = blames[lineNumber]
reviewers[name] = (reviewers[name] || 0) + 1
})
});
console.log('blame point:', reviewers)
var names = Object.keys(reviewers)
names.sort((name1, name2) => {
return reviewers[name1] > reviewers[name2] ? -1 : 1
})
var prUser = danger.github.pr.user.login
names.splice(names.findIndex(el => {
return el === prUser
}), 1)
if (names.length > 0) {
if (names.length > 2) {
names = names.slice(0, 2)
}
names = names.map(name => {
return '@' + name
})
message("According to the blame info, we recommended " + names.join(' , ') + " to be the reviewers.")
}
}
/*
* find reviewer end
*/
|
dangerfile.js
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { schedule, danger, fail, warn, message, markdown } from "danger";
import fs from "fs";
import path from 'path';
import GitHubApi from 'github';
import parseDiff from 'parse-diff';
// Make sure there are changelog entries
const hasChangelog = danger.git.modified_files.includes("changelog.md")
if (!hasChangelog) { warn("No Changelog changes!") }
const jsFiles = danger.git.created_files.filter(path => path.endsWith("js"));
function absolute (relPath) {
return path.resolve(__dirname, relPath)
}
const flowIgnorePaths = [
'node_modules',
'test',
'build',
'examples',
'doc',
'android',
'ios',
'bin',
'dist',
'flow-typed'
].map(function (rel) {
return absolute(rel)
});
// new js files should have `@flow` at the top
const unFlowedFiles = jsFiles.filter(filepath => {
let i = 0
const len = flowIgnorePaths.length
while (i < len) {
const p = flowIgnorePaths[i]
if (absolute(filepath).indexOf(p) > -1) {
// ignore this file because it's in the flow-ignore-paths.
return false;
}
i++
}
const content = fs.readFileSync(filepath);
return !content.includes("@flow");
});
if (unFlowedFiles.length > 0) {
warn(
`These new JS files do not have Flow enabled: ${unFlowedFiles.join(", ")}`
);
}
// Error or Warn when delete public interface
var methion_break_change = false;
for (let c of danger.git.commits) {
// console.log("msg:" + c.message);
if (c.message && c.message.match(/break\s+change/i)) {
methion_break_change = true;
break;
}
}
// File name match any of these patterns will be ignored.
function is_ignored_public_check(file) {
var ignored_break_change_pattern = [
/^android\/sdk\/src\/test\/.+/,
/^android\/playground\/.+/
];
for (let p of ignored_break_change_pattern) {
if (file.match(p)) {
return true;
}
}
return false;
}
var has_app_changes = false;
var has_test_changes = false;
var codefiles = [];
for (let file of danger.git.modified_files) {
if (file.match(/WeexSDK\/Source/)) {
has_app_changes = true;
} else if (file.match(/WeexSDKTests/)) {
has_test_changes = true;
}
/* diffforFile
* if (!is_ignored_public_check(file) && file.endsWith(".java")) {
var diff = await danger.git.diffForFile(file);
if (diff && diff.removed && diff.removed.match(/^-\s*?public\s+[\s\S]+$/gm)) {
if (methion_break_change) {
warn("Potential BREAK CHANGE. Modify public in " + file);
} else {
warn(
"Potential BREAK CHANGE. Modify public in " +
file +
" without metion it in commit message. You'd better add 'break change' in your commit log. "
);
}
}
}*/
if (
file.endsWith(".h") ||
file.endsWith(".m") ||
file.endsWith(".mm") ||
file.endsWith(".java") ||
file.endsWith(".js")
) {
codefiles.push(file);
}
}
if(danger.git.added_files){
for (let file of danger.git.added_files) {
if (
file.endsWith(".h") ||
file.endsWith(".m") ||
file.endsWith(".mm") ||
file.endsWith(".java") ||
file.endsWith(".js")
) {
codefiles.push(file);
}
}
}
if (danger.git.lines_of_code > 500) {
warn("Big PR");
}
if (danger.git.lines_of_code > 100 && has_app_changes && !has_test_changes) {
warn("This PR may need tests.");
}
//check ios copyright
//see scripts/rh/header.template
const copyright_header_components = [
"Licensed to the Apache Software Foundation \\(ASF\\) under one",
"or more contributor license agreements. See the NOTICE file",
"distributed with this work for additional information",
"regarding copyright ownership\\. The ASF licenses this file",
'to you under the Apache License, Version 2\\.0 \\(the',
'"License"\\); you may not use this file except in compliance',
'with the License\\. You may obtain a copy of the License at'
];
//path prefix
const ignoreCopyrightVerifyPath = [
'test',
'pre-build',
'android/playground/app/src/main/assets',
'android/sdk/assets',
'ios/playground/bundlejs',
'ios/sdk/WeexSDK/Resources',
'ios/sdk/WeexSDK/Sources/Layout'
]
codefiles.forEach(filepath => {
for(var i=ignoreCopyrightVerifyPath.length-1;i>=0;i--){
if(filepath.startsWith(ignoreCopyrightVerifyPath[i])){
return
}
}
const content = fs.readFileSync(filepath).toString();
for (const line of copyright_header_components) {
if (!content.match(new RegExp(line))) {
fail("Code file "+ filepath +" does not have the copyright header.");
return;
}
}
});
/*
* try to find the appropriate reviewer according to the blame info
* will be seperated to a danger plugin
*/
schedule(new Promise((resolve, reject) => {
try {
findReviewer(resolve, reject)
} catch (e) {
console.log(e)
resolve()
}
}));
function findReviewer(resolve, reject) {
var github = new GitHubApi({
protocol: "https",
host: "api.github.com",
});
var fileToDeletedLinesMap = {}
var fileToNormalLinesMap = {}
var fileToBlamesMap = {}
github.pullRequests.get({
owner: danger.github.pr.base.user.login,
repo: danger.github.pr.base.repo.name,
number: danger.github.pr.number,
headers: {Accept: 'application/vnd.github.diff'}
}, function (err, result) {
if ("undefined" === typeof result || "undefined" === typeof result.data || err) {
reject()
return
}
parseDeleteAndNormalLines(result.data, fileToDeletedLinesMap, fileToNormalLinesMap)
var promises = danger.git.modified_files.map(function(file) {
let repoURL = danger.github.pr.base.repo.html_url
let fileName = file.replace(/^.*[\\\/]/, '')
let blameURL = repoURL + '/blame/' + danger.github.pr.base.ref + '/' + file
// console.log("Getting blame html: " + blameURL)
return getContent(blameURL)
});
Promise.all(promises).then(datas => {
datas.forEach(function(data, index) {
fileToBlamesMap[danger.git.modified_files[index]] = parseBlame(data);
});
findBlameReviewers(fileToDeletedLinesMap, fileToNormalLinesMap, fileToBlamesMap)
resolve()
})
});
}
function getContent(url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
}
function parseDeleteAndNormalLines(diffData, fileToDeletedLinesMap, fileToNormalLinesMap) {
var diffs = parseDiff(diffData)
diffs.forEach(diff => {
fileToDeletedLinesMap[diff.from] = [];
fileToNormalLinesMap[diff.from] = [];
diff.chunks.forEach(chunk => {
chunk.changes.forEach(change => {
if (change.del) {
fileToDeletedLinesMap[diff.from].push(change.ln)
}
if (change.normal) {
fileToNormalLinesMap[diff.from].push(change.ln1)
}
})
})
})
}
function parseBlame(html) {
let regular = /(<img alt="@([^"]+)" class="avatar blame-commit-avatar"|<tr class="blame-line")/g
var match
var currentUser
var lines = []
while ((match = regular.exec(html)) !== null) {
let user = match[2]
if (user) {
currentUser = user
} else {
lines.push(currentUser)
}
}
return lines
}
function findBlameReviewers(fileToDeletedLinesMap, fileToNormalLinesMap, fileToBlamesMap) {
var reviewers = {};
// deleted lines get 3 points, normal line get 1 point
Object.keys(fileToDeletedLinesMap).forEach(function (file) {
let deletedLines = fileToDeletedLinesMap[file]
var blames = fileToBlamesMap[file]
deletedLines.forEach(lineNumber => {
var name = blames[lineNumber]
reviewers[name] = (reviewers[name] || 0) + 3
})
});
Object.keys(fileToNormalLinesMap).forEach(function (file) {
let normalLines = fileToNormalLinesMap[file];
var blames = fileToBlamesMap[file]
normalLines.forEach(lineNumber => {
var name = blames[lineNumber]
reviewers[name] = (reviewers[name] || 0) + 1
})
});
console.log('blame point:', reviewers)
var names = Object.keys(reviewers)
names.sort((name1, name2) => {
return reviewers[name1] > reviewers[name2] ? -1 : 1
})
var prUser = danger.github.pr.user.login
names.splice(names.findIndex(el => {
return el === prUser
}), 1)
if (names.length > 0) {
if (names.length > 2) {
names = names.slice(0, 2)
}
names = names.map(name => {
return '@' + name
})
message("According to the blame info, we recommended " + names.join(' , ') + " to be the reviewers.")
}
}
/*
* find reviewer end
*/
|
* [all] fix danger: use schedule to run async
|
dangerfile.js
|
* [all] fix danger: use schedule to run async
|
<ide><path>angerfile.js
<ide> return false;
<ide> }
<ide>
<add>async function checkBreakChange(file){
<add> var diff = await danger.git.diffForFile(file);
<add> if (diff && diff.removed && diff.removed.match(/^-\s*?public\s+[\s\S]+$/gm)) {
<add> if (methion_break_change) {
<add> warn("Potential BREAK CHANGE. Modify public in " + file);
<add> } else {
<add> warn(
<add> "Potential BREAK CHANGE. Modify public in " +
<add> file +
<add> " without metion it in commit message. You'd better add 'break change' in your commit log. "
<add> );
<add> }
<add> }
<add>}
<add>
<ide> var has_app_changes = false;
<ide> var has_test_changes = false;
<ide> var codefiles = [];
<ide> has_test_changes = true;
<ide> }
<ide>
<del> /* diffforFile
<del> * if (!is_ignored_public_check(file) && file.endsWith(".java")) {
<del> var diff = await danger.git.diffForFile(file);
<del> if (diff && diff.removed && diff.removed.match(/^-\s*?public\s+[\s\S]+$/gm)) {
<del> if (methion_break_change) {
<del> warn("Potential BREAK CHANGE. Modify public in " + file);
<del> } else {
<del> warn(
<del> "Potential BREAK CHANGE. Modify public in " +
<del> file +
<del> " without metion it in commit message. You'd better add 'break change' in your commit log. "
<del> );
<del> }
<del> }
<del> }*/
<add> if (!is_ignored_public_check(file) && file.endsWith(".java")) {
<add> schedule(async ()=> {
<add> await checkBreakChange(file)
<add> })
<add> }
<ide>
<ide> if (
<ide> file.endsWith(".h") ||
|
|
Java
|
apache-2.0
|
8b3ecb653d7e05c18bc3b6804493f254e54d3c45
| 0 |
webhejj/webhejj-commons,gnagy/webhejj-commons
|
/*
* Copyright Gergely Nagy <[email protected]>
*
* Licensed under the Apache License, Version 2.0;
* you may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package hu.webhejj.commons.xml;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Stack;
/**
* Simple indented XML Writer that only allows attribute values
*/
public class SimpleXmlWriter implements XmlWriter {
private int indent = 4;
private Stack<String> elements = new Stack<String>();
private boolean isOpen = false;
private boolean isLeaf = false;
private Writer writer;
public SimpleXmlWriter(OutputStream os) throws IOException {
this.writer = new OutputStreamWriter(os, Charset.forName("UTF-8"));
writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
}
public void startElement(String name) throws IOException {
if(isOpen) {
writer.write(">\n");
}
indent();
elements.push(name);
writer.write("<");
writer.write(name);
isOpen = true;
isLeaf = true;
}
public void endElement() throws IOException {
if(elements.size() > 0) {
String element = elements.pop();
if(isOpen) {
if(isLeaf) {
writer.write("/>\n");
} else {
writer.write(">\n");
}
} else {
indent();
writer.write("</");
writer.write(element);
writer.write(">\n");
}
isOpen = false;
isLeaf = false;
}
}
public void writeAttribute(String name, String value) throws IOException {
writer.write(" ");
writeEscaped(name);
writer.write("=\"");
writeEscaped(value);
writer.write("\"");
}
public void writeEscaped(String string) throws IOException {
if(string == null) {
return;
}
for(int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
switch(c) {
case '<': writer.write("<"); break;
case '>': writer.write(">"); break;
case '&': writer.write("&"); break;
case '"': writer.write("""); break;
case '\'': writer.write("'"); break;
default: writer.write(c);
}
}
}
public void close() throws IOException {
while(elements.size() > 0) {
endElement();
}
writer.close();
}
public void flush() throws IOException {
writer.flush();
}
protected void indent() throws IOException {
for(int i = 0; i < elements.size(); i++) {
for(int j = 0; j < indent; j++) {
writer.write(' ');
}
}
}
}
|
src/hu/webhejj/commons/xml/SimpleXmlWriter.java
|
/*
* Copyright Gergely Nagy <[email protected]>
*
* Licensed under the Apache License, Version 2.0;
* you may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package hu.webhejj.commons.xml;
import java.io.IOException;
import java.io.Writer;
import java.util.Stack;
/**
* Simple indented XML Writer that only allows attribute values
*/
public class SimpleXmlWriter implements XmlWriter {
private int indent = 4;
private Stack<String> elements = new Stack<String>();
private boolean isOpen = false;
private boolean isLeaf = false;
private Writer writer;
public SimpleXmlWriter(Writer writer) throws IOException {
this.writer = writer;
writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
}
public void startElement(String name) throws IOException {
if(isOpen) {
writer.write(">\n");
}
indent();
elements.push(name);
writer.write("<");
writer.write(name);
isOpen = true;
isLeaf = true;
}
public void endElement() throws IOException {
if(elements.size() > 0) {
String element = elements.pop();
if(isOpen) {
if(isLeaf) {
writer.write("/>\n");
} else {
writer.write(">\n");
}
} else {
indent();
writer.write("</");
writer.write(element);
writer.write(">\n");
}
isOpen = false;
isLeaf = false;
}
}
public void writeAttribute(String name, String value) throws IOException {
writer.write(" ");
writer.write(name);
writer.write("=\"");
writer.write(value);
writer.write("\"");
}
public void close() throws IOException {
while(elements.size() > 0) {
endElement();
}
writer.close();
}
public void flush() throws IOException {
writer.flush();
}
protected void indent() throws IOException {
for(int i = 0; i < elements.size(); i++) {
for(int j = 0; j < indent; j++) {
writer.write(' ');
}
}
}
}
|
Fix SimpleXMLWriter: make sure output is UTF-8 and properly xml-escaped.
|
src/hu/webhejj/commons/xml/SimpleXmlWriter.java
|
Fix SimpleXMLWriter: make sure output is UTF-8 and properly xml-escaped.
|
<ide><path>rc/hu/webhejj/commons/xml/SimpleXmlWriter.java
<ide> package hu.webhejj.commons.xml;
<ide>
<ide> import java.io.IOException;
<add>import java.io.OutputStream;
<add>import java.io.OutputStreamWriter;
<ide> import java.io.Writer;
<add>import java.nio.charset.Charset;
<ide> import java.util.Stack;
<ide>
<ide> /**
<ide>
<ide> private Writer writer;
<ide>
<del> public SimpleXmlWriter(Writer writer) throws IOException {
<del> this.writer = writer;
<add> public SimpleXmlWriter(OutputStream os) throws IOException {
<add> this.writer = new OutputStreamWriter(os, Charset.forName("UTF-8"));
<ide>
<ide> writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
<ide> }
<ide>
<ide> public void writeAttribute(String name, String value) throws IOException {
<ide> writer.write(" ");
<del> writer.write(name);
<add> writeEscaped(name);
<ide> writer.write("=\"");
<del> writer.write(value);
<add> writeEscaped(value);
<ide> writer.write("\"");
<add> }
<add>
<add> public void writeEscaped(String string) throws IOException {
<add> if(string == null) {
<add> return;
<add> }
<add> for(int i = 0; i < string.length(); i++) {
<add> char c = string.charAt(i);
<add> switch(c) {
<add> case '<': writer.write("<"); break;
<add> case '>': writer.write(">"); break;
<add> case '&': writer.write("&"); break;
<add> case '"': writer.write("""); break;
<add> case '\'': writer.write("'"); break;
<add> default: writer.write(c);
<add> }
<add> }
<ide> }
<ide>
<ide> public void close() throws IOException {
|
|
Java
|
apache-2.0
|
error: pathspec 'helianto/domain/src/main/java/org/helianto/core/type/IdentityType1.java' did not match any file(s) known to git
|
789f83a541ce035552d45c25f9c4d534671c8baa
| 1 |
iservport/helianto,iservport/helianto
|
/* Copyright 2005 I Serv Consultoria Empresarial Ltda.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.helianto.core.type;
/**
* An enumeration to supply char types for
* {@link Identity#identityType}.
*
* @author Mauricio Fernandes de Castro
* @version $Id: $
*/
public enum IdentityType1 {
GROUP('G'),
NOT_ADDRESSABLE('N'),
ORGANIZATIONAL_EMAIL('O'),
PERSONAL_EMAIL('P');
private char value;
private IdentityType1(char value) {
this.value = value;
}
public char getValue() {
return this.value;
}
}
|
helianto/domain/src/main/java/org/helianto/core/type/IdentityType1.java
|
moved to a new package
git-svn-id: 8e38db1cf16c4a277275c2a31413431bbf4974e4@253 d46e4f78-7810-0410-b419-9f95c2a9a517
|
helianto/domain/src/main/java/org/helianto/core/type/IdentityType1.java
|
moved to a new package
|
<ide><path>elianto/domain/src/main/java/org/helianto/core/type/IdentityType1.java
<add>/* Copyright 2005 I Serv Consultoria Empresarial Ltda.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.helianto.core.type;
<add>
<add>/**
<add> * An enumeration to supply char types for
<add> * {@link Identity#identityType}.
<add> *
<add> * @author Mauricio Fernandes de Castro
<add> * @version $Id: $
<add> */
<add>public enum IdentityType1 {
<add>
<add> GROUP('G'),
<add> NOT_ADDRESSABLE('N'),
<add> ORGANIZATIONAL_EMAIL('O'),
<add> PERSONAL_EMAIL('P');
<add>
<add> private char value;
<add>
<add> private IdentityType1(char value) {
<add> this.value = value;
<add> }
<add> public char getValue() {
<add> return this.value;
<add> }
<add>
<add>}
|
|
Java
|
mit
|
f86e45c714d369ba977eeaf589573ca1255d653e
| 0 |
syedhaziqhamdani/Projects,syedhaziqhamdani/Projects
|
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextField;
import com.sun.org.apache.xpath.internal.operations.Equals;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
private static JPanel contentPane;
private static JTextField[][] grid = new JTextField[6][7];
private static int[][] scoreBoard = new int[6][7];
private static boolean firstMove = false;
// private JTextField b00;
// private JTextField b01;
// private JTextField b02;
// private JTextField b03;
// private JTextField b05;
// private JTextField b06;
// private JTextField b04;
// private JTextField b10;
// private JTextField b11;
// private JTextField b12;
// private JTextField b13;
// private JTextField b14;
// private JTextField b15;
// private JTextField b16;
// private JTextField b30;
// private JTextField b31;
// private JTextField b32;
// private JTextField b33;
// private JTextField b34;
// private JTextField b35;
// private JTextField b36;
// private JTextField b20;
// private JTextField b21;
// private JTextField b22;
// private JTextField b23;
// private JTextField b24;
// private JTextField b25;
// private JTextField b26;
// private JTextField b50;
// private JTextField b51;
// private JTextField b52;
// private JTextField b53;
// private JTextField b54;
// private JTextField b55;
// private JTextField b56;
// private JTextField b40;
// private JTextField b41;
// private JTextField b42;
// private JTextField b43;
// private JTextField b44;
// private JTextField b45;
// private JTextField b46;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
scoreBoard[0][0] = -1;
scoreBoard[0][1] = -1;
scoreBoard[0][2] = -1;
scoreBoard[0][3] = -1;
scoreBoard[0][4] = -1;
scoreBoard[0][5] = -1;
scoreBoard[0][6] = -1;
scoreBoard[1][0] = -1;
scoreBoard[1][1] = -1;
scoreBoard[1][2] = -1;
scoreBoard[1][3] = -1;
scoreBoard[1][4] = -1;
scoreBoard[1][5] = -1;
scoreBoard[1][6] = -1;
scoreBoard[2][0] = -1;
scoreBoard[2][1] = -1;
scoreBoard[2][2] = -1;
scoreBoard[2][3] = -1;
scoreBoard[2][4] = -1;
scoreBoard[2][5] = -1;
scoreBoard[2][6] = -1;
scoreBoard[3][0] = -1;
scoreBoard[3][1] = -1;
scoreBoard[3][2] = -1;
scoreBoard[3][3] = -1;
scoreBoard[3][4] = -1;
scoreBoard[3][5] = -1;
scoreBoard[3][6] = -1;
scoreBoard[4][0] = -1;
scoreBoard[4][1] = -1;
scoreBoard[4][2] = -1;
scoreBoard[4][3] = -1;
scoreBoard[4][4] = -1;
scoreBoard[4][5] = -1;
scoreBoard[4][6] = -1;
scoreBoard[5][0] = -1;
scoreBoard[5][1] = -1;
scoreBoard[5][2] = -1;
scoreBoard[5][3] = -1;
scoreBoard[5][4] = -1;
scoreBoard[5][5] = -1;
scoreBoard[5][6] = -1;
grid[0][0] = new JTextField();
grid[0][1] = new JTextField();
grid[0][2] = new JTextField();
grid[0][3] = new JTextField();
grid[0][4] = new JTextField();
grid[0][5] = new JTextField();
grid[0][6] = new JTextField();
grid[1][0] = new JTextField();
grid[1][1] = new JTextField();
grid[1][2] = new JTextField();
grid[1][3] = new JTextField();
grid[1][4] = new JTextField();
grid[1][5] = new JTextField();
grid[1][6] = new JTextField();
grid[2][0] = new JTextField();
grid[2][1] = new JTextField();
grid[2][2] = new JTextField();
grid[2][3] = new JTextField();
grid[2][4] = new JTextField();
grid[2][5] = new JTextField();
grid[2][6] = new JTextField();
grid[3][0] = new JTextField();
grid[3][1] = new JTextField();
grid[3][2] = new JTextField();
grid[3][3] = new JTextField();
grid[3][4] = new JTextField();
grid[3][5] = new JTextField();
grid[3][6] = new JTextField();
grid[4][0] = new JTextField();
grid[4][1] = new JTextField();
grid[4][2] = new JTextField();
grid[4][3] = new JTextField();
grid[4][4] = new JTextField();
grid[4][5] = new JTextField();
grid[4][6] = new JTextField();
grid[5][0] = new JTextField();
grid[5][1] = new JTextField();
grid[5][2] = new JTextField();
grid[5][3] = new JTextField();
grid[5][4] = new JTextField();
grid[5][5] = new JTextField();
grid[5][6] = new JTextField();
setTitle("Four In a Row - AI Project");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 720, 267);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton columnOneButton = new JButton("Drop");
columnOneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// JOptionPane.showConfirmDialog(contentPane, "Clicked");
humanMove(0);
}
});
columnOneButton.setBounds(10, 11, 89, 23);
contentPane.add(columnOneButton);
JButton columnTwoButton = new JButton("Drop");
columnTwoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
humanMove(1);
}
});
columnTwoButton.setBounds(109, 11, 89, 23);
contentPane.add(columnTwoButton);
JButton columnThreeButton = new JButton("Drop");
columnThreeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(2);
}
});
columnThreeButton.setBounds(208, 11, 89, 23);
contentPane.add(columnThreeButton);
JButton columnFourButton = new JButton("Drop");
columnFourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(3);
}
});
columnFourButton.setBounds(307, 11, 89, 23);
contentPane.add(columnFourButton);
JButton columnFiveButton = new JButton("Drop");
columnFiveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(4);
}
});
columnFiveButton.setBounds(406, 11, 89, 23);
contentPane.add(columnFiveButton);
JButton columnSixButton = new JButton("Drop");
columnSixButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(5);
}
});
columnSixButton.setBounds(505, 11, 89, 23);
contentPane.add(columnSixButton);
JButton columnSevenButton = new JButton("Drop");
columnSevenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humanMove(6);
}
});
columnSevenButton.setBounds(604, 11, 89, 23);
contentPane.add(columnSevenButton);
// grid[0][0] = new JTextField();
grid[0][0].setEnabled(false);
grid[0][0].setBounds(10, 45, 86, 20);
contentPane.add(grid[0][0]);
grid[0][0].setColumns(10);
// grid[0][1] = new JTextField();
grid[0][1].setEnabled(false);
grid[0][1].setColumns(10);
grid[0][1].setBounds(109, 45, 86, 20);
contentPane.add(grid[0][1]);
// grid[0][2] = new JTextField();
grid[0][2].setEnabled(false);
grid[0][2].setColumns(10);
grid[0][2].setBounds(211, 45, 86, 20);
contentPane.add(grid[0][2]);
// grid[0][3] = new JTextField();
grid[0][3].setEnabled(false);
grid[0][3].setColumns(10);
grid[0][3].setBounds(310, 45, 86, 20);
contentPane.add(grid[0][3]);
// grid[0][4] = new JTextField();
grid[0][4].setEnabled(false);
grid[0][4].setColumns(10);
grid[0][4].setBounds(406, 45, 86, 20);
contentPane.add(grid[0][4]);
// grid[0][5] = new JTextField();
grid[0][5].setEnabled(false);
grid[0][5].setColumns(10);
grid[0][5].setBounds(508, 45, 86, 20);
contentPane.add(grid[0][5]);
// grid[0][6] = new JTextField(" ");
grid[0][6].setEnabled(false);
grid[0][6].setColumns(10);
grid[0][6].setBounds(607, 45, 86, 20);
contentPane.add(grid[0][6]);
// grid[1][0] = new JTextField();
grid[1][0].setEnabled(false);
grid[1][0].setColumns(10);
grid[1][0].setBounds(10, 76, 86, 20);
contentPane.add(grid[1][0]);
// grid[1][1] = new JTextField();
grid[1][1].setEnabled(false);
grid[1][1].setColumns(10);
grid[1][1].setBounds(109, 76, 86, 20);
contentPane.add(grid[1][1]);
// grid[1][2] = new JTextField();
grid[1][2].setEnabled(false);
grid[1][2].setColumns(10);
grid[1][2].setBounds(211, 76, 86, 20);
contentPane.add(grid[1][2]);
// grid[1][3] = new JTextField();
grid[1][3].setEnabled(false);
grid[1][3].setColumns(10);
grid[1][3].setBounds(310, 76, 86, 20);
contentPane.add(grid[1][3]);
// grid[1][4] = new JTextField();
grid[1][4].setEnabled(false);
grid[1][4].setColumns(10);
grid[1][4].setBounds(406, 76, 86, 20);
contentPane.add(grid[1][4]);
// grid[1][5] = new JTextField();
grid[1][5].setEnabled(false);
grid[1][5].setColumns(10);
grid[1][5].setBounds(508, 76, 86, 20);
contentPane.add(grid[1][5]);
// grid[1][6] = new JTextField();
grid[1][6].setEnabled(false);
grid[1][6].setColumns(10);
grid[1][6].setBounds(607, 76, 86, 20);
contentPane.add(grid[1][6]);
// grid[2][0] = new JTextField();
grid[2][0].setEnabled(false);
grid[2][0].setColumns(10);
grid[2][0].setBounds(10, 107, 86, 20);
contentPane.add(grid[2][0]);
// grid[2][1] = new JTextField();
grid[2][1].setEnabled(false);
grid[2][1].setColumns(10);
grid[2][1].setBounds(109, 107, 86, 20);
contentPane.add(grid[2][1]);
// grid[2][2] = new JTextField();
grid[2][2].setEnabled(false);
grid[2][2].setColumns(10);
grid[2][2].setBounds(211, 107, 86, 20);
contentPane.add(grid[2][2]);
// grid[2][3] = new JTextField();
grid[2][3].setEnabled(false);
grid[2][3].setColumns(10);
grid[2][3].setBounds(310, 107, 86, 20);
contentPane.add(grid[2][3]);
// grid[2][4] = new JTextField();
grid[2][4].setEnabled(false);
grid[2][4].setColumns(10);
grid[2][4].setBounds(406, 107, 86, 20);
contentPane.add(grid[2][4]);
// grid[2][5] = new JTextField();
grid[2][5].setEnabled(false);
grid[2][5].setColumns(10);
grid[2][5].setBounds(508, 107, 86, 20);
contentPane.add(grid[2][5]);
// grid[2][6] = new JTextField();
grid[2][6].setEnabled(false);
grid[2][6].setColumns(10);
grid[2][6].setBounds(607, 107, 86, 20);
contentPane.add(grid[2][6]);
// grid[3][0] = new JTextField();
grid[3][0].setEnabled(false);
grid[3][0].setColumns(10);
grid[3][0].setBounds(10, 138, 86, 20);
contentPane.add(grid[3][0]);
// grid[3][1] = new JTextField();
grid[3][1].setEnabled(false);
grid[3][1].setColumns(10);
grid[3][1].setBounds(109, 138, 86, 20);
contentPane.add(grid[3][1]);
// grid[3][2] = new JTextField();
grid[3][2].setEnabled(false);
grid[3][2].setColumns(10);
grid[3][2].setBounds(211, 138, 86, 20);
contentPane.add(grid[3][2]);
// grid[3][3] = new JTextField();
grid[3][3].setEnabled(false);
grid[3][3].setColumns(10);
grid[3][3].setBounds(310, 138, 86, 20);
contentPane.add(grid[3][3]);
// grid[3][4] = new JTextField();
grid[3][4].setEnabled(false);
grid[3][4].setColumns(10);
grid[3][4].setBounds(406, 138, 86, 20);
contentPane.add(grid[3][4]);
// grid[3][5] = new JTextField();
grid[3][5].setEnabled(false);
grid[3][5].setColumns(10);
grid[3][5].setBounds(508, 138, 86, 20);
contentPane.add(grid[3][5]);
// grid[3][6] = new JTextField();
grid[3][6].setEnabled(false);
grid[3][6].setColumns(10);
grid[3][6].setBounds(607, 138, 86, 20);
contentPane.add(grid[3][6]);
// grid[4][0] = new JTextField();
grid[4][0].setEnabled(false);
grid[4][0].setColumns(10);
grid[4][0].setBounds(10, 169, 86, 20);
contentPane.add(grid[4][0]);
// grid[4][1] = new JTextField();
grid[4][1].setEnabled(false);
grid[4][1].setColumns(10);
grid[4][1].setBounds(109, 169, 86, 20);
contentPane.add(grid[4][1]);
// grid[4][2] = new JTextField();
grid[4][2].setEnabled(false);
grid[4][2].setColumns(10);
grid[4][2].setBounds(211, 169, 86, 20);
contentPane.add(grid[4][2]);
// grid[4][3] = new JTextField();
grid[4][3].setEnabled(false);
grid[4][3].setColumns(10);
grid[4][3].setBounds(310, 169, 86, 20);
contentPane.add(grid[4][3]);
// grid[4][4] = new JTextField();
grid[4][4].setEnabled(false);
grid[4][4].setColumns(10);
grid[4][4].setBounds(406, 169, 86, 20);
contentPane.add(grid[4][4]);
// grid[4][5] = new JTextField();
grid[4][5].setEnabled(false);
grid[4][5].setColumns(10);
grid[4][5].setBounds(508, 169, 86, 20);
contentPane.add(grid[4][5]);
// grid[4][6] = new JTextField();
grid[4][6].setEnabled(false);
grid[4][6].setColumns(10);
grid[4][6].setBounds(607, 169, 86, 20);
contentPane.add(grid[4][6]);
// grid[5][0] = new JTextField();
grid[5][0].setEnabled(false);
grid[5][0].setColumns(10);
grid[5][0].setBounds(10, 200, 86, 20);
contentPane.add(grid[5][0]);
// grid[5][1] = new JTextField();
grid[5][1].setEnabled(false);
grid[5][1].setColumns(10);
grid[5][1].setBounds(109, 200, 86, 20);
contentPane.add(grid[5][1]);
// grid[5][2] = new JTextField();
grid[5][2].setEnabled(false);
grid[5][2].setColumns(10);
grid[5][2].setBounds(211, 200, 86, 20);
contentPane.add(grid[5][2]);
// grid[5][3] = new JTextField();
grid[5][3].setEnabled(false);
grid[5][3].setColumns(10);
grid[5][3].setBounds(310, 200, 86, 20);
contentPane.add(grid[5][3]);
// grid[5][4] = new JTextField();
grid[5][4].setEnabled(false);
grid[5][4].setColumns(10);
grid[5][4].setBounds(406, 200, 86, 20);
contentPane.add(grid[5][4]);
// grid[5][5] = new JTextField();
grid[5][5].setEnabled(false);
grid[5][5].setColumns(10);
grid[5][5].setBounds(508, 200, 86, 20);
contentPane.add(grid[5][5]);
// grid[5][6] = new JTextField();
grid[5][6].setEnabled(false);
grid[5][6].setColumns(10);
grid[5][6].setBounds(607, 200, 86, 20);
contentPane.add(grid[5][6]);
// Error Checking Code
// for (int i = 0; i < 6; i++) {
// for (int j = 0; j < 7; j++) {
// grid[i][j].setText("Test.");
// }
// }
}
static void isFirstMove() {
for (int i = 0; i < scoreBoard.length; i++) {
for (int j = 0; j < scoreBoard.length; j++) {
if (scoreBoard[i][j] == -1) {
firstMove = true;
} else {
firstMove = false;
}
}
}
}
static void humanMove(int columnNumber) {
int emptyCell = 0;
for (int i = 0; i < 6; i++) {
if (grid[i][columnNumber].getText().isEmpty()) {
emptyCell = i;
}
// if (grid.length - 6 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 5 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 4 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 3 == i && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 2 == i && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 1 == i && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
}
grid[emptyCell][columnNumber].setBackground(Color.BLUE);
grid[emptyCell][columnNumber].setText(" ");
scoreBoard[emptyCell][columnNumber] = 1;
computerMove(columnNumber);
// boolean flag = true;
// isFirstMove();
// while (flag) {
// for (int i = 0; i <= 5; i++) {
// if (grid.length - 1 == i && grid[i][columnNumber].getText().isEmpty()
// && firstMove) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// flag = false;
// } else if ((grid.length - 1 != i) && !firstMove) {
// if (grid[i + 1][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// flag = false;
// }
// }
//
// }
// }
}
static void computerMove(int columnNumber){
int emptyCell = 0;
for (int i = 0; i < 6; i++) {
if (grid[i][columnNumber].getText().isEmpty()) {
emptyCell = i;
}
}
grid[emptyCell][columnNumber].setBackground(Color.RED);
grid[emptyCell][columnNumber].setText(" ");
scoreBoard[emptyCell][columnNumber] = 2;
}
}
|
ArtificialIntelligenceProject/src/Main.java
|
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextField;
import com.sun.org.apache.xpath.internal.operations.Equals;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
private static JPanel contentPane;
private static JTextField[][] grid = new JTextField[6][7];
private static int[][] scoreBoard = new int[6][7];
private static boolean firstMove = false;
// private JTextField b00;
// private JTextField b01;
// private JTextField b02;
// private JTextField b03;
// private JTextField b05;
// private JTextField b06;
// private JTextField b04;
// private JTextField b10;
// private JTextField b11;
// private JTextField b12;
// private JTextField b13;
// private JTextField b14;
// private JTextField b15;
// private JTextField b16;
// private JTextField b30;
// private JTextField b31;
// private JTextField b32;
// private JTextField b33;
// private JTextField b34;
// private JTextField b35;
// private JTextField b36;
// private JTextField b20;
// private JTextField b21;
// private JTextField b22;
// private JTextField b23;
// private JTextField b24;
// private JTextField b25;
// private JTextField b26;
// private JTextField b50;
// private JTextField b51;
// private JTextField b52;
// private JTextField b53;
// private JTextField b54;
// private JTextField b55;
// private JTextField b56;
// private JTextField b40;
// private JTextField b41;
// private JTextField b42;
// private JTextField b43;
// private JTextField b44;
// private JTextField b45;
// private JTextField b46;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
scoreBoard[0][0] = -1;
scoreBoard[0][1] = -1;
scoreBoard[0][2] = -1;
scoreBoard[0][3] = -1;
scoreBoard[0][4] = -1;
scoreBoard[0][5] = -1;
scoreBoard[0][6] = -1;
scoreBoard[1][0] = -1;
scoreBoard[1][1] = -1;
scoreBoard[1][2] = -1;
scoreBoard[1][3] = -1;
scoreBoard[1][4] = -1;
scoreBoard[1][5] = -1;
scoreBoard[1][6] = -1;
scoreBoard[2][0] = -1;
scoreBoard[2][1] = -1;
scoreBoard[2][2] = -1;
scoreBoard[2][3] = -1;
scoreBoard[2][4] = -1;
scoreBoard[2][5] = -1;
scoreBoard[2][6] = -1;
scoreBoard[3][0] = -1;
scoreBoard[3][1] = -1;
scoreBoard[3][2] = -1;
scoreBoard[3][3] = -1;
scoreBoard[3][4] = -1;
scoreBoard[3][5] = -1;
scoreBoard[3][6] = -1;
scoreBoard[4][0] = -1;
scoreBoard[4][1] = -1;
scoreBoard[4][2] = -1;
scoreBoard[4][3] = -1;
scoreBoard[4][4] = -1;
scoreBoard[4][5] = -1;
scoreBoard[4][6] = -1;
scoreBoard[5][0] = -1;
scoreBoard[5][1] = -1;
scoreBoard[5][2] = -1;
scoreBoard[5][3] = -1;
scoreBoard[5][4] = -1;
scoreBoard[5][5] = -1;
scoreBoard[5][6] = -1;
grid[0][0] = new JTextField();
grid[0][1] = new JTextField();
grid[0][2] = new JTextField();
grid[0][3] = new JTextField();
grid[0][4] = new JTextField();
grid[0][5] = new JTextField();
grid[0][6] = new JTextField();
grid[1][0] = new JTextField();
grid[1][1] = new JTextField();
grid[1][2] = new JTextField();
grid[1][3] = new JTextField();
grid[1][4] = new JTextField();
grid[1][5] = new JTextField();
grid[1][6] = new JTextField();
grid[2][0] = new JTextField();
grid[2][1] = new JTextField();
grid[2][2] = new JTextField();
grid[2][3] = new JTextField();
grid[2][4] = new JTextField();
grid[2][5] = new JTextField();
grid[2][6] = new JTextField();
grid[3][0] = new JTextField();
grid[3][1] = new JTextField();
grid[3][2] = new JTextField();
grid[3][3] = new JTextField();
grid[3][4] = new JTextField();
grid[3][5] = new JTextField();
grid[3][6] = new JTextField();
grid[4][0] = new JTextField();
grid[4][1] = new JTextField();
grid[4][2] = new JTextField();
grid[4][3] = new JTextField();
grid[4][4] = new JTextField();
grid[4][5] = new JTextField();
grid[4][6] = new JTextField();
grid[5][0] = new JTextField();
grid[5][1] = new JTextField();
grid[5][2] = new JTextField();
grid[5][3] = new JTextField();
grid[5][4] = new JTextField();
grid[5][5] = new JTextField();
grid[5][6] = new JTextField();
setTitle("Four In a Row - AI Project");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 720, 267);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton columnOneButton = new JButton("Drop");
columnOneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// JOptionPane.showConfirmDialog(contentPane, "Clicked");
humanMove(0);
}
});
columnOneButton.setBounds(10, 11, 89, 23);
contentPane.add(columnOneButton);
JButton columnTwoButton = new JButton("Drop");
columnTwoButton.setBounds(109, 11, 89, 23);
contentPane.add(columnTwoButton);
JButton columnThreeButton = new JButton("Drop");
columnThreeButton.setBounds(208, 11, 89, 23);
contentPane.add(columnThreeButton);
JButton columnFourButton = new JButton("Drop");
columnFourButton.setBounds(307, 11, 89, 23);
contentPane.add(columnFourButton);
JButton columnFiveButton = new JButton("Drop");
columnFiveButton.setBounds(406, 11, 89, 23);
contentPane.add(columnFiveButton);
JButton columnSixButton = new JButton("Drop");
columnSixButton.setBounds(505, 11, 89, 23);
contentPane.add(columnSixButton);
JButton columnSevenButton = new JButton("Drop");
columnSevenButton.setBounds(604, 11, 89, 23);
contentPane.add(columnSevenButton);
// grid[0][0] = new JTextField();
grid[0][0].setEnabled(false);
grid[0][0].setBounds(10, 45, 86, 20);
contentPane.add(grid[0][0]);
grid[0][0].setColumns(10);
// grid[0][1] = new JTextField();
grid[0][1].setEnabled(false);
grid[0][1].setColumns(10);
grid[0][1].setBounds(109, 45, 86, 20);
contentPane.add(grid[0][1]);
// grid[0][2] = new JTextField();
grid[0][2].setEnabled(false);
grid[0][2].setColumns(10);
grid[0][2].setBounds(211, 45, 86, 20);
contentPane.add(grid[0][2]);
// grid[0][3] = new JTextField();
grid[0][3].setEnabled(false);
grid[0][3].setColumns(10);
grid[0][3].setBounds(310, 45, 86, 20);
contentPane.add(grid[0][3]);
// grid[0][4] = new JTextField();
grid[0][4].setEnabled(false);
grid[0][4].setColumns(10);
grid[0][4].setBounds(406, 45, 86, 20);
contentPane.add(grid[0][4]);
// grid[0][5] = new JTextField();
grid[0][5].setEnabled(false);
grid[0][5].setColumns(10);
grid[0][5].setBounds(508, 45, 86, 20);
contentPane.add(grid[0][5]);
// grid[0][6] = new JTextField(" ");
grid[0][6].setEnabled(false);
grid[0][6].setColumns(10);
grid[0][6].setBounds(607, 45, 86, 20);
contentPane.add(grid[0][6]);
// grid[1][0] = new JTextField();
grid[1][0].setEnabled(false);
grid[1][0].setColumns(10);
grid[1][0].setBounds(10, 76, 86, 20);
contentPane.add(grid[1][0]);
// grid[1][1] = new JTextField();
grid[1][1].setEnabled(false);
grid[1][1].setColumns(10);
grid[1][1].setBounds(109, 76, 86, 20);
contentPane.add(grid[1][1]);
// grid[1][2] = new JTextField();
grid[1][2].setEnabled(false);
grid[1][2].setColumns(10);
grid[1][2].setBounds(211, 76, 86, 20);
contentPane.add(grid[1][2]);
// grid[1][3] = new JTextField();
grid[1][3].setEnabled(false);
grid[1][3].setColumns(10);
grid[1][3].setBounds(310, 76, 86, 20);
contentPane.add(grid[1][3]);
// grid[1][4] = new JTextField();
grid[1][4].setEnabled(false);
grid[1][4].setColumns(10);
grid[1][4].setBounds(406, 76, 86, 20);
contentPane.add(grid[1][4]);
// grid[1][5] = new JTextField();
grid[1][5].setEnabled(false);
grid[1][5].setColumns(10);
grid[1][5].setBounds(508, 76, 86, 20);
contentPane.add(grid[1][5]);
// grid[1][6] = new JTextField();
grid[1][6].setEnabled(false);
grid[1][6].setColumns(10);
grid[1][6].setBounds(607, 76, 86, 20);
contentPane.add(grid[1][6]);
// grid[2][0] = new JTextField();
grid[2][0].setEnabled(false);
grid[2][0].setColumns(10);
grid[2][0].setBounds(10, 107, 86, 20);
contentPane.add(grid[2][0]);
// grid[2][1] = new JTextField();
grid[2][1].setEnabled(false);
grid[2][1].setColumns(10);
grid[2][1].setBounds(109, 107, 86, 20);
contentPane.add(grid[2][1]);
// grid[2][2] = new JTextField();
grid[2][2].setEnabled(false);
grid[2][2].setColumns(10);
grid[2][2].setBounds(211, 107, 86, 20);
contentPane.add(grid[2][2]);
// grid[2][3] = new JTextField();
grid[2][3].setEnabled(false);
grid[2][3].setColumns(10);
grid[2][3].setBounds(310, 107, 86, 20);
contentPane.add(grid[2][3]);
// grid[2][4] = new JTextField();
grid[2][4].setEnabled(false);
grid[2][4].setColumns(10);
grid[2][4].setBounds(406, 107, 86, 20);
contentPane.add(grid[2][4]);
// grid[2][5] = new JTextField();
grid[2][5].setEnabled(false);
grid[2][5].setColumns(10);
grid[2][5].setBounds(508, 107, 86, 20);
contentPane.add(grid[2][5]);
// grid[2][6] = new JTextField();
grid[2][6].setEnabled(false);
grid[2][6].setColumns(10);
grid[2][6].setBounds(607, 107, 86, 20);
contentPane.add(grid[2][6]);
// grid[3][0] = new JTextField();
grid[3][0].setEnabled(false);
grid[3][0].setColumns(10);
grid[3][0].setBounds(10, 138, 86, 20);
contentPane.add(grid[3][0]);
// grid[3][1] = new JTextField();
grid[3][1].setEnabled(false);
grid[3][1].setColumns(10);
grid[3][1].setBounds(109, 138, 86, 20);
contentPane.add(grid[3][1]);
// grid[3][2] = new JTextField();
grid[3][2].setEnabled(false);
grid[3][2].setColumns(10);
grid[3][2].setBounds(211, 138, 86, 20);
contentPane.add(grid[3][2]);
// grid[3][3] = new JTextField();
grid[3][3].setEnabled(false);
grid[3][3].setColumns(10);
grid[3][3].setBounds(310, 138, 86, 20);
contentPane.add(grid[3][3]);
// grid[3][4] = new JTextField();
grid[3][4].setEnabled(false);
grid[3][4].setColumns(10);
grid[3][4].setBounds(406, 138, 86, 20);
contentPane.add(grid[3][4]);
// grid[3][5] = new JTextField();
grid[3][5].setEnabled(false);
grid[3][5].setColumns(10);
grid[3][5].setBounds(508, 138, 86, 20);
contentPane.add(grid[3][5]);
// grid[3][6] = new JTextField();
grid[3][6].setEnabled(false);
grid[3][6].setColumns(10);
grid[3][6].setBounds(607, 138, 86, 20);
contentPane.add(grid[3][6]);
// grid[4][0] = new JTextField();
grid[4][0].setEnabled(false);
grid[4][0].setColumns(10);
grid[4][0].setBounds(10, 169, 86, 20);
contentPane.add(grid[4][0]);
// grid[4][1] = new JTextField();
grid[4][1].setEnabled(false);
grid[4][1].setColumns(10);
grid[4][1].setBounds(109, 169, 86, 20);
contentPane.add(grid[4][1]);
// grid[4][2] = new JTextField();
grid[4][2].setEnabled(false);
grid[4][2].setColumns(10);
grid[4][2].setBounds(211, 169, 86, 20);
contentPane.add(grid[4][2]);
// grid[4][3] = new JTextField();
grid[4][3].setEnabled(false);
grid[4][3].setColumns(10);
grid[4][3].setBounds(310, 169, 86, 20);
contentPane.add(grid[4][3]);
// grid[4][4] = new JTextField();
grid[4][4].setEnabled(false);
grid[4][4].setColumns(10);
grid[4][4].setBounds(406, 169, 86, 20);
contentPane.add(grid[4][4]);
// grid[4][5] = new JTextField();
grid[4][5].setEnabled(false);
grid[4][5].setColumns(10);
grid[4][5].setBounds(508, 169, 86, 20);
contentPane.add(grid[4][5]);
// grid[4][6] = new JTextField();
grid[4][6].setEnabled(false);
grid[4][6].setColumns(10);
grid[4][6].setBounds(607, 169, 86, 20);
contentPane.add(grid[4][6]);
// grid[5][0] = new JTextField();
grid[5][0].setEnabled(false);
grid[5][0].setColumns(10);
grid[5][0].setBounds(10, 200, 86, 20);
contentPane.add(grid[5][0]);
// grid[5][1] = new JTextField();
grid[5][1].setEnabled(false);
grid[5][1].setColumns(10);
grid[5][1].setBounds(109, 200, 86, 20);
contentPane.add(grid[5][1]);
// grid[5][2] = new JTextField();
grid[5][2].setEnabled(false);
grid[5][2].setColumns(10);
grid[5][2].setBounds(211, 200, 86, 20);
contentPane.add(grid[5][2]);
// grid[5][3] = new JTextField();
grid[5][3].setEnabled(false);
grid[5][3].setColumns(10);
grid[5][3].setBounds(310, 200, 86, 20);
contentPane.add(grid[5][3]);
// grid[5][4] = new JTextField();
grid[5][4].setEnabled(false);
grid[5][4].setColumns(10);
grid[5][4].setBounds(406, 200, 86, 20);
contentPane.add(grid[5][4]);
// grid[5][5] = new JTextField();
grid[5][5].setEnabled(false);
grid[5][5].setColumns(10);
grid[5][5].setBounds(508, 200, 86, 20);
contentPane.add(grid[5][5]);
// grid[5][6] = new JTextField();
grid[5][6].setEnabled(false);
grid[5][6].setColumns(10);
grid[5][6].setBounds(607, 200, 86, 20);
contentPane.add(grid[5][6]);
// Error Checking Code
// for (int i = 0; i < 6; i++) {
// for (int j = 0; j < 7; j++) {
// grid[i][j].setText("Test.");
// }
// }
}
static void isFirstMove() {
for (int i = 0; i < scoreBoard.length; i++) {
for (int j = 0; j < scoreBoard.length; j++) {
if (scoreBoard[i][j] == -1) {
firstMove = true;
} else {
firstMove = false;
}
}
}
}
static void humanMove(int columnNumber) {
int emptyCell = 0;
for (int i = 0; i < 6; i++) {
if (grid[i][columnNumber].getText().isEmpty()) {
emptyCell = i;
}
// if (grid.length - 6 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 5 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 4 == i
// && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 3 == i && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 2 == i && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
// if (grid.length - 1 == i && grid[i][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// break;
// }
}
grid[emptyCell][columnNumber].setBackground(Color.BLUE);
grid[emptyCell][columnNumber].setText(" ");
// boolean flag = true;
// isFirstMove();
// while (flag) {
// for (int i = 0; i <= 5; i++) {
// if (grid.length - 1 == i && grid[i][columnNumber].getText().isEmpty()
// && firstMove) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// flag = false;
// } else if ((grid.length - 1 != i) && !firstMove) {
// if (grid[i + 1][columnNumber].getText().isEmpty()) {
// grid[i][columnNumber].setBackground(Color.BLUE);
// grid[i][columnNumber].setText(" ");
// flag = false;
// }
// }
//
// }
// }
}
}
|
computerMove Method implemented.
|
ArtificialIntelligenceProject/src/Main.java
|
computerMove Method implemented.
|
<ide><path>rtificialIntelligenceProject/src/Main.java
<ide> contentPane.add(columnOneButton);
<ide>
<ide> JButton columnTwoButton = new JButton("Drop");
<add> columnTwoButton.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent arg0) {
<add> humanMove(1);
<add> }
<add> });
<ide> columnTwoButton.setBounds(109, 11, 89, 23);
<ide> contentPane.add(columnTwoButton);
<ide>
<ide> JButton columnThreeButton = new JButton("Drop");
<add> columnThreeButton.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> humanMove(2);
<add> }
<add> });
<ide> columnThreeButton.setBounds(208, 11, 89, 23);
<ide> contentPane.add(columnThreeButton);
<ide>
<ide> JButton columnFourButton = new JButton("Drop");
<add> columnFourButton.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> humanMove(3);
<add> }
<add> });
<ide> columnFourButton.setBounds(307, 11, 89, 23);
<ide> contentPane.add(columnFourButton);
<ide>
<ide> JButton columnFiveButton = new JButton("Drop");
<add> columnFiveButton.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> humanMove(4);
<add> }
<add> });
<ide> columnFiveButton.setBounds(406, 11, 89, 23);
<ide> contentPane.add(columnFiveButton);
<ide>
<ide> JButton columnSixButton = new JButton("Drop");
<add> columnSixButton.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> humanMove(5);
<add> }
<add> });
<ide> columnSixButton.setBounds(505, 11, 89, 23);
<ide> contentPane.add(columnSixButton);
<ide>
<ide> JButton columnSevenButton = new JButton("Drop");
<add> columnSevenButton.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> humanMove(6);
<add> }
<add> });
<ide> columnSevenButton.setBounds(604, 11, 89, 23);
<ide> contentPane.add(columnSevenButton);
<ide>
<ide> }
<ide> grid[emptyCell][columnNumber].setBackground(Color.BLUE);
<ide> grid[emptyCell][columnNumber].setText(" ");
<add> scoreBoard[emptyCell][columnNumber] = 1;
<add> computerMove(columnNumber);
<ide> // boolean flag = true;
<ide> // isFirstMove();
<ide> // while (flag) {
<ide> // }
<ide> // }
<ide> }
<add> static void computerMove(int columnNumber){
<add> int emptyCell = 0;
<add> for (int i = 0; i < 6; i++) {
<add> if (grid[i][columnNumber].getText().isEmpty()) {
<add> emptyCell = i;
<add> }
<add> }
<add> grid[emptyCell][columnNumber].setBackground(Color.RED);
<add> grid[emptyCell][columnNumber].setText(" ");
<add> scoreBoard[emptyCell][columnNumber] = 2;
<add> }
<ide> }
|
|
Java
|
apache-2.0
|
e903351add53d9c018378b3f64da13e48a26b487
| 0 |
stome/stomev1,stome/stomev1,stome/stomev1,stome/stomev1,stome/stomev1
|
/*
STOME - Taking the Wold Wide Web by Stome
VERSION 2.0
TODO 1: 1.0 double-click views tag links
TODO 2: 4.0 PAUSE/RESUME FETCHING
TODO 3: 8.0 add search box and Find button for searching within selected Results
TODO 4: 2.0 implement Open Links: open muliple links at once (popup menu)
TODO 5: 8.0 export selection to database
TODO 6: 8.0 export selection to spreadsheet
TODO 7: 2.0 implement Refresh Shares (popup menu)
TODO 8: 8.0 add links to local filesystem files
TODO 8: 8.0 need to allow users to edit shares to make this useful
TODO 9: 8.0 add bing as backup search in case google dies
VERSION 3.0
TODO 20: 40.0 implement Feed tab (twitter user updates)
TODO 21: 40.0 implement Feed tab (youtube channel updates)
TODO 22: 40.0 implement Feed tab (rss)
COMPLETE
Implemented Add Tag. Add tag to multiple links at once (popup menu)
Import links from Google Chrome feature added
Import links from Firefox feature added
*/
import net.miginfocom.swing.MigLayout;
import java.util.ArrayList;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.commons.validator.routines.UrlValidator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JFrame;
import javax.swing.DefaultCellEditor;
import javax.swing.ListSelectionModel;
import javax.swing.UIDefaults;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class Stome
{
public static final String APP_NAME = "STOME";
public static final String APP_VERSION = "1.0";
public static final String APP_TITLE = APP_NAME + " " + APP_VERSION;
public static final int SHARE_COUNT = 1;
public static final int TITLE = 2;
private static JFrame frame = new JFrame( "Search - " + Stome.APP_TITLE );
private static ResultsModel resultsModel = null;
private static JTextArea linksInput = new JTextArea( 20, 40 );
private static JTextField keywordsInput = new JTextField();
private static JButton linksImportButton = new JButton( "Import" );
private static JButton linksImportFromChromeButton =
new JButton( "Import Chrome Bookmarks" );
private static JButton linksImportFromFirefoxButton =
new JButton( "Import Firefox Bookmarks" );
private static JButton keywordsSearchButton = new JButton( "Search" );
private static JButton tagsViewButton = new JButton( "View" );
private static JButton clearLinksButton = new JButton( "Clear Links" );
private static JTable resultsTable = null;
private static JTabbedPane tabbedPane = null;
private static TagsPanel tagsPanel = null;
private static String ip = null;
private static String dbFile = null;
private static String openTag = null;
private static Color evenColor = new Color( 250, 250, 250 );
private static Color selectedColor = null;
public static void main( String[] args )
{
String workingDir = Stome.class.getProtectionDomain().
getCodeSource().getLocation().getPath();
try
{
workingDir = URLDecoder.decode( workingDir, "utf-8" );
}
catch( UnsupportedEncodingException ex ) {}
File baseDir = new File( workingDir );
File dbf = null;
if( baseDir.getAbsolutePath().matches( ".*\\.jar$" ) )
dbf = new File( baseDir.getParent(), "Stome.db" );
else
dbf = new File( baseDir, "Stome.db" );
if( dbf != null )
dbFile = dbf.getAbsolutePath();
Options options = new Options();
options.addOption( "d", "database", true,
"Use database file (default: " + dbFile + ")" );
options.addOption( "t", "tag", true, "Load tag on opening" );
options.addOption( "h", "help", false, "Print this help menu" );
boolean showHelp = false;
CommandLineParser parser = new BasicParser();
try
{
CommandLine line = parser.parse( options, args );
if( line.hasOption( "d" ) )
dbFile = line.getOptionValue( "d" );
if( line.hasOption( "t" ) )
openTag = line.getOptionValue( "t" );
if( line.hasOption( "h" ) )
showHelp = true;
}
catch( org.apache.commons.cli.ParseException ex ) { ex.printStackTrace(); }
if( showHelp )
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( Stome.APP_NAME, options );
System.exit( 0 );
}
UIDefaults defaults = javax.swing.UIManager.getDefaults();
selectedColor = defaults.getColor( "List.selectionBackground" );
ip = getClientIpAddr();
guiInit();
wireButtons();
if( openTag != null )
{
tabbedPane.setSelectedIndex( 2 );
String[] openTags = openTag.split( "," );
tagsPanel.select( openTags );
tagsViewButton.doClick();
}
}
public static void scrollToVisible( JTable table, int rowIndex, int colIndex )
{
if( ! ( table.getParent() instanceof JViewport ) )
return;
JViewport viewport = (JViewport) table.getParent();
// This rectangle is relative to the table where the
// northwest corner of cell (0,0) is always (0,0).
Rectangle rect = table.getCellRect( rowIndex, colIndex, true );
// The location of the viewport relative to the table
Point pt = viewport.getViewPosition();
// Translate the cell location so that it is relative
// to the view, assuming the northwest corner of the
// view is (0,0)
rect.setLocation( rect.x-pt.x, rect.y-pt.y );
table.scrollRectToVisible( rect );
}
// Called by LinkProcessor to disable query buttons during fetching and
// reenable them when it's done
public static void buttonsSetEnabled( boolean enabled )
{
linksImportButton.setEnabled( enabled );
linksImportFromFirefoxButton.setEnabled( enabled );
linksImportFromChromeButton.setEnabled( enabled );
keywordsSearchButton.setEnabled( enabled );
tagsViewButton.setEnabled( enabled );
}
private static void wireButtons()
{
keywordsSearchButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
String query = keywordsInput.getText().replace( " ", "+" );
// Only 64 results can be fetched using this method
// (8 pages of 8 results per page)
ArrayList <String> urlArrayList = doSearchJava( query );
// ArrayList <String> urlArrayList = doSearchLocalPython( query );
// ArrayList <String> urlArrayList = doSearchRemotePython( query );
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
} );
linksImportButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
String[] links = linksInput.getText().split( "\n" );
addLinks( links );
}
} );
linksImportFromChromeButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
// Determine the Chrome bookmarks file
String os = System.getProperty( "os.name" );
String userHome = System.getProperty( "user.home" );
File bookmarksFile = null;
if( os.startsWith( "Linux" ) )
bookmarksFile = new File(
userHome + "/.config/chromium/Default/Bookmarks" );
else if( os.startsWith( "Windows" ) )
bookmarksFile = new File(
userHome + "\\Local Settings\\Application Data\\" +
"\\Google\\Chrome\\User Data\\Default\\Bookmarks" );
// Scan bookmarks file for urls
if( bookmarksFile != null )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
String content = readFile(
bookmarksFile.getPath(), StandardCharsets.UTF_8 );
String regex = "\"url\": \"(.*)\"";
Pattern pattern = Pattern.compile( regex );
Matcher matcher = pattern.matcher( content );
while( matcher.find() )
urlArrayList.add( matcher.group( 1 ) );
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
}
} );
linksImportFromFirefoxButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
// Determine the Firefox bookmarks file
String os = System.getProperty( "os.name" );
String userHome = System.getProperty( "user.home" );
DirectoryScanner scanner = new DirectoryScanner();
scanner.setCaseSensitive( false );
String baseDir = null;
if( os.startsWith( "Linux" ) )
{
baseDir = userHome + "/.mozilla/firefox/";
scanner.setIncludes( new String[] { "*.default/places.sqlite" } );
scanner.setBasedir( baseDir );
}
else if( os.startsWith( "Windows" ) )
{
if( os.equals( "Windows XP" ) )
baseDir = userHome +
"\\Application Data\\Mozilla\\Firefox\\Profiles\\";
else
baseDir = userHome +
"\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\";
System.out.println( baseDir );
scanner.setIncludes(
new String[] { "*.default\\places.sqlite" } );
scanner.setBasedir( baseDir );
}
// Scan bookmarks files for urls
if( baseDir != null )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
scanner.scan();
String[] files = scanner.getIncludedFiles();
for( String f : files )
{
String ffDbFile = baseDir + f;
System.out.println( ffDbFile );
addUrlsFromDbToArray( ffDbFile, urlArrayList );
}
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
}
} );
tagsViewButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
Tags selectedTags = tagsPanel.getSelectedTags();
ArrayList<String> urlArrayList =
resultsModel.getTagLinks( selectedTags );
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
} );
}
public static void addUrlsFromDbToArray(
String ffDbFile, ArrayList<String> urlArrayList )
{
Connection dbh = null;
try
{
Class.forName( "org.sqlite.JDBC" );
dbh = DriverManager.getConnection( "jdbc:sqlite:" + ffDbFile );
}
catch( Exception ex ) { ex.printStackTrace(); }
if( dbh != null )
{
String query = "SELECT url FROM moz_places " +
"WHERE id IN ( SELECT fk FROM moz_bookmarks ) " +
"AND url LIKE 'http%'";
Statement stmt = null;
try
{
stmt = dbh.createStatement();
ResultSet rs = stmt.executeQuery( query );
while( rs.next() )
urlArrayList.add( rs.getString( 1 ) );
}
catch( Exception ex ) { ex.printStackTrace(); }
}
}
public static String readFile( String path, Charset encoding )
{
String content = null;
try
{
byte[] encoded = Files.readAllBytes( Paths.get( path ) );
content = encoding.decode( ByteBuffer.wrap( encoded ) ).toString();
}
catch( IOException ex ) {}
return content;
}
/*
private static ArrayList<String> doSearchLocalPython( String query )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
String cmd = "/home/john/stome/google_search2.py";
ProcessBuilder builder = new ProcessBuilder( cmd, query, "1", ip );
try
{
Process process = builder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader( process.getInputStream () ) );
String line = null;
while( ( line = reader.readLine () ) != null )
{
urlArrayList.add( line );
}
}
catch( java.io.IOException ex ) {}
return urlArrayList;
}
private static ArrayList<String> doSearchRemotePython( String query )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
String searchUrl =
"http://ec2-54-234-73-91.compute-1.amazonaws.com/" +
"cgi-bin/do_search.py?user_id=1&query=" +
query + "&page=1&ip=" + ip;
String content = getHTMLContent( searchUrl, 5000, ip );
String[] urls = content.split( "\n" );
for( int i = 0; i < urls.length; i++ )
urlArrayList.add( urls[ i ] );
return urlArrayList;
}
*/
private static ArrayList<String> doSearchJava( String query )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
for( int page = 1; page <= 9; page++ )
{
int start = ( page - 1 ) * 8;
String searchUrl =
"https://ajax.googleapis.com/ajax/services/search/web" +
"?v=1.0&safe=active&rsz=large&start=" + start + "&q=" +
query + "&userip=" + ip;
String content = getHTMLContent( searchUrl, 5000, ip );
try
{
JSONParser parser = new JSONParser();
if( parser != null && content != null )
{
JSONObject json = (JSONObject) parser.parse( content );
JSONObject jdata = (JSONObject) json.get( "responseData" );
if( jdata != null )
{
JSONArray jresults = (JSONArray) jdata.get( "results" );
for( int i = 0; i < jresults.size(); i++ )
{
JSONObject jresult = (JSONObject) jresults.get( i );
String url = (String) jresult.get( "unescapedUrl" );
urlArrayList.add( url );
}
}
else
{
//System.err.println( json );
//System.err.println( searchUrl );
break;
}
}
}
catch( org.json.simple.parser.ParseException ex ) {}
// try { Thread.sleep( 200 ); } catch( InterruptedException ex ) {}
}
return urlArrayList;
}
public static String getClientIpAddr()
{
String ip = null;
try
{
ip = new BufferedReader( new InputStreamReader(
new URL( "http://agentgatech.appspot.com" ).
openStream() ) ).readLine();
}
catch( java.net.MalformedURLException ex ) {}
catch( java.io.IOException ex ) {}
return ip;
}
private static void addLinks( String[] links )
{
if( links != null && links.length > 0 )
{
buttonsSetEnabled( false );
resultsModel.startUrls();
int added = 0;
for( int i = 0; i < links.length; i++ )
{
if( urlIsValid( links[ i ] ) )
{
if( resultsModel.addUrl( links[ i ] ) )
added++;
}
}
resultsModel.stopUrls();
if( added == 0 )
buttonsSetEnabled( true );
}
}
private static void guiInit()
{
MigLayout buttonLayout = new MigLayout(
"", "[100%,align left][100%,align right]", ""
);
JLabel fetchStatusLabel = new JLabel();
resultsModel = new ResultsModel( fetchStatusLabel, dbFile );
Tags tags = resultsModel.getAllTags();
tags.add( 0, "" );
tagsPanel = new TagsPanel( resultsModel, tagsViewButton );
resultsModel.setTagsPanel( tagsPanel );
Java2sAutoComboBox newTagInput = new Java2sAutoComboBox( tags );
newTagInput.setStrict( false );
resultsModel.addNewTagInput( newTagInput );
// Links
JScrollPane linksInputScrollPane = new JScrollPane( linksInput );
JButton linksClearButton = new JButton( "Clear" );
linksClearButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
linksInput.setText( "" );
linksInput.requestFocus();
}
} );
JPanel linksPanel = new JPanel(
new MigLayout( "", "[grow]", "[][grow][][]" ) );
linksPanel.add( new JLabel( "Links" ), "span,wrap" );
linksPanel.add( linksInputScrollPane, "span,grow,wrap" );
linksPanel.add( linksClearButton, "align left" );
linksPanel.add( linksImportFromChromeButton, "align center" );
linksPanel.add( linksImportFromFirefoxButton, "align center" );
linksPanel.add( linksImportButton, "align right" );
// Keywords
keywordsInput.setPreferredSize(
new Dimension( keywordsInput.getMaximumSize().width,
keywordsInput.getPreferredSize().height ) );
keywordsInput.addKeyListener( new KeyListener() {
public void keyPressed( KeyEvent e )
{
if( e.getKeyCode() == KeyEvent.VK_ENTER )
keywordsSearchButton.doClick();
}
public void keyReleased( KeyEvent e ) {}
public void keyTyped( KeyEvent e ) {}
} );
JButton keywordsClearButton = new JButton( "Clear" );
keywordsClearButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
keywordsInput.setText( "" );
keywordsInput.requestFocus();
}
} );
JPanel keywordsPanel = new JPanel( new MigLayout() );
keywordsPanel.add( new JLabel( "Keywords" ), "span,wrap" );
keywordsPanel.add( keywordsInput, "span,wrap" );
keywordsPanel.add( keywordsClearButton, "align left" );
keywordsPanel.add( keywordsSearchButton, "align right" );
// Tags: managed by TagsPanel
tabbedPane = new JTabbedPane();
tabbedPane.add( "Search", keywordsPanel );
tabbedPane.add( "Import", linksPanel );
tabbedPane.add( "Tags", tagsPanel );
tabbedPane.addChangeListener( new ChangeListener() {
public void stateChanged( ChangeEvent e )
{
int selectedIndex = tabbedPane.getSelectedIndex();
if( selectedIndex == 0 )
{
keywordsInput.requestFocus();
frame.setTitle( "Search - " + Stome.APP_TITLE );
}
else if( selectedIndex == 1 )
{
linksInput.requestFocus();
frame.setTitle( "Import - " + Stome.APP_TITLE );
}
else if( selectedIndex == 2 )
{
frame.setTitle( "Tags - " + Stome.APP_TITLE );
}
}
} );
// Results
JLabel hoverUrlLabel = new JLabel();
Font font = hoverUrlLabel.getFont().deriveFont( Font.PLAIN );
hoverUrlLabel.setFont( font );
setLabelSize( fetchStatusLabel );
setLabelSize( hoverUrlLabel );
resultsTable = new JTable( resultsModel )
{
private static final long serialVersionUID = 105;
@Override public Component prepareRenderer(
TableCellRenderer tcr, int row, int column )
{
if( tcr == null )
return null;
try
{
Component c = super.prepareRenderer( tcr, row, column );
c.setForeground( getForeground() );
if( resultsTable.isRowSelected( row ) )
c.setBackground( selectedColor );
else
c.setBackground( ( row % 2 == 0 ) ?
evenColor : getBackground() );
return c;
}
catch( java.lang.NullPointerException ex ) {}
return null;
}
};
resultsTable.addMouseListener( new MouseAdapter()
{
public void mousePressed( MouseEvent e )
{
if( e.isPopupTrigger() )
openPopup( e );
}
public void mouseReleased( MouseEvent e )
{
if( e.isPopupTrigger() )
openPopup( e );
}
private void openPopup( MouseEvent e )
{
PopupMenu menu = new PopupMenu( frame, resultsTable );
// menu.show( e.getComponent(), e.getX(), e.getY() );
menu.show( resultsTable, e.getX(), e.getY() );
}
} );
resultsTable.setIntercellSpacing( new Dimension() );
resultsTable.setShowGrid( false );
resultsTable.putClientProperty( "terminateEditOnFocusLost", Boolean.TRUE );
HyperlinkRenderer renderer = new HyperlinkRenderer( hoverUrlLabel );
resultsTable.setDefaultRenderer( Hyperlink.class, renderer );
resultsTable.addMouseListener( renderer );
resultsTable.addMouseMotionListener( renderer );
TagRenderer tagRenderer = new TagRenderer();
resultsTable.setDefaultRenderer( Tags.class, tagRenderer );
TableColumnModel resultsColModel = resultsTable.getColumnModel();
DefaultCellEditor cellEditor = new DefaultCellEditor( newTagInput );
cellEditor.setClickCountToStart( 1 );
resultsColModel.getColumn(
ResultsModel.NEW_TAG_COL ).setCellEditor( cellEditor );
setColumnWidth( resultsColModel, ResultsModel.SHARES_COL, 70, 70, 120 );
setColumnWidth( resultsColModel, ResultsModel.DOMAIN_COL, 60, 150, 250 );
setColumnWidth( resultsColModel, ResultsModel.NEW_TAG_COL, 60, 150, 250 );
setColumnWidth( resultsColModel, ResultsModel.TAGS_COL, 60, 200, -1 );
setColumnWidth( resultsColModel, ResultsModel.LINK_COL, 200, 400, -1 );
resultsTable.setAutoCreateRowSorter( true );
resultsTable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
resultsTable.setRowSelectionAllowed( true );
resultsTable.setFillsViewportHeight( true );
JScrollPane resultsScrollPane = new JScrollPane( resultsTable );
clearLinksButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
ResultsModel model = ( ResultsModel ) resultsTable.getModel();
model.clearLinks();
}
} );
JPanel resultsPane =
new JPanel( new MigLayout( "", "[grow]", "[][grow][]" ) );
resultsPane.add( clearLinksButton, "align left" );
resultsPane.add( fetchStatusLabel, "align right,wrap" );
resultsPane.add( resultsScrollPane, "span,grow,wrap" );
resultsPane.add( hoverUrlLabel, "span,grow" );
JSplitPane sp = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
sp.add( tabbedPane );
sp.add( resultsPane );
sp.setResizeWeight( 0.33d );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( sp );
frame.pack();
frame.setSize( new Dimension( 640, 480 ) );
frame.setVisible( true );
keywordsInput.requestFocus();
}
private static boolean urlIsValid( String url )
{
String[] schemes = { "http", "https" };
UrlValidator urlValidator = new UrlValidator( schemes );
if( urlValidator.isValid( url ) )
{
if( url.matches( "https?://webcache.googleusercontent.com/.*" ) ||
url.matches( "https?://www.google.com/search\\?.*" ) )
return false;
return true;
}
return false;
}
private static void setLabelSize( JLabel label )
{
FontMetrics fm = label.getFontMetrics( label.getFont() );
int fontHeight = fm.getAscent() + fm.getDescent() + fm.getLeading();
label.setMinimumSize(
new Dimension( label.getPreferredSize().width, fontHeight ) );
}
public static void setColumnWidth(
TableColumnModel colModel, int column,
int minWidth, int preferredWidth, int maxWidth )
{
if( minWidth >= 0 )
colModel.getColumn( column ).setMinWidth( minWidth );
if( preferredWidth >= 0 )
colModel.getColumn( column ).setPreferredWidth( preferredWidth );
if( maxWidth >= 0 )
colModel.getColumn( column ).setMaxWidth( maxWidth );
}
public static String getHTMLContent(
String url, int timeoutMilliseconds, String referer )
{
String content = "";
try
{
URL urlObj = new URL( url );
URLConnection conn = urlObj.openConnection();
conn.setRequestProperty( "Referer", referer );
conn.setConnectTimeout( timeoutMilliseconds );
BufferedReader in =
new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
String inputLine;
while( ( inputLine = in.readLine() ) != null )
content += inputLine;
in.close();
}
catch( IOException ex ) {}
return content;
}
}
|
Stome.java
|
/*
STOME - Taking the Wold Wide Web by Stome
VERSION 2.0
TODO 1: 1.0 double-click views tag links
TODO 2: 4.0 PAUSE/RESUME FETCHING
TODO 3: 8.0 add search box and Find button for searching within selected Results
TODO 4: 2.0 implement Open Links: open muliple links at once (popup menu)
TODO 5: 8.0 export selection to database
TODO 6: 8.0 export selection to spreadsheet
TODO 7: 2.0 implement Refresh Shares (popup menu)
TODO 8: 8.0 add links to local filesystem files
TODO 8: 8.0 need to allow users to edit shares to make this useful
TODO 9: 8.0 add bing as backup search in case google dies
VERSION 3.0
TODO 20: 40.0 implement Feed tab (twitter user updates)
TODO 21: 40.0 implement Feed tab (youtube channel updates)
TODO 22: 40.0 implement Feed tab (rss)
COMPLETE
Implemented Add Tag. Add tag to multiple links at once (popup menu)
Import links from Google Chrome feature added
Import links from Firefox feature added
*/
import net.miginfocom.swing.MigLayout;
import java.util.ArrayList;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.commons.validator.routines.UrlValidator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JFrame;
import javax.swing.DefaultCellEditor;
import javax.swing.ListSelectionModel;
import javax.swing.UIDefaults;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class Stome
{
public static final String APP_NAME = "STOME";
public static final String APP_VERSION = "1.0";
public static final String APP_TITLE = APP_NAME + " " + APP_VERSION;
public static final int SHARE_COUNT = 1;
public static final int TITLE = 2;
private static JFrame frame = new JFrame( "Search - " + Stome.APP_TITLE );
private static ResultsModel resultsModel = null;
private static JTextArea linksInput = new JTextArea( 20, 40 );
private static JTextField keywordsInput = new JTextField();
private static JButton linksImportButton = new JButton( "Import" );
private static JButton linksImportFromChromeButton =
new JButton( "Import Chrome Bookmarks" );
private static JButton linksImportFromFirefoxButton =
new JButton( "Import Firefox Bookmarks" );
private static JButton keywordsSearchButton = new JButton( "Search" );
private static JButton tagsViewButton = new JButton( "View" );
private static JButton clearLinksButton = new JButton( "Clear Links" );
private static JTable resultsTable = null;
private static JTabbedPane tabbedPane = null;
private static TagsPanel tagsPanel = null;
private static String ip = null;
private static String dbFile = null;
private static String openTag = null;
private static Color evenColor = new Color( 250, 250, 250 );
private static Color selectedColor = null;
public static void main( String[] args )
{
String workingDir = Stome.class.getProtectionDomain().
getCodeSource().getLocation().getPath();
try
{
workingDir = URLDecoder.decode( workingDir, "utf-8" );
}
catch( UnsupportedEncodingException ex ) {}
File baseDir = new File( workingDir );
File dbf = null;
if( baseDir.getAbsolutePath().matches( ".*\\.jar$" ) )
dbf = new File( baseDir.getParent(), "Stome.db" );
else
dbf = new File( baseDir, "Stome.db" );
if( dbf != null )
dbFile = dbf.getAbsolutePath();
Options options = new Options();
options.addOption( "d", "database", true,
"Use database file (default: " + dbFile + ")" );
options.addOption( "t", "tag", true, "Load tag on opening" );
options.addOption( "h", "help", false, "Print this help menu" );
boolean showHelp = false;
CommandLineParser parser = new BasicParser();
try
{
CommandLine line = parser.parse( options, args );
if( line.hasOption( "d" ) )
dbFile = line.getOptionValue( "d" );
if( line.hasOption( "t" ) )
openTag = line.getOptionValue( "t" );
if( line.hasOption( "h" ) )
showHelp = true;
}
catch( org.apache.commons.cli.ParseException ex ) { ex.printStackTrace(); }
if( showHelp )
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( Stome.APP_NAME, options );
System.exit( 0 );
}
UIDefaults defaults = javax.swing.UIManager.getDefaults();
selectedColor = defaults.getColor( "List.selectionBackground" );
ip = getClientIpAddr();
guiInit();
wireButtons();
if( openTag != null )
{
tabbedPane.setSelectedIndex( 2 );
String[] openTags = openTag.split( "," );
tagsPanel.select( openTags );
tagsViewButton.doClick();
}
}
public static void scrollToVisible( JTable table, int rowIndex, int colIndex )
{
if( ! ( table.getParent() instanceof JViewport ) )
return;
JViewport viewport = (JViewport) table.getParent();
// This rectangle is relative to the table where the
// northwest corner of cell (0,0) is always (0,0).
Rectangle rect = table.getCellRect( rowIndex, colIndex, true );
// The location of the viewport relative to the table
Point pt = viewport.getViewPosition();
// Translate the cell location so that it is relative
// to the view, assuming the northwest corner of the
// view is (0,0)
rect.setLocation( rect.x-pt.x, rect.y-pt.y );
table.scrollRectToVisible( rect );
}
// Called by LinkProcessor to disable query buttons during fetching and
// reenable them when it's done
public static void buttonsSetEnabled( boolean enabled )
{
linksImportButton.setEnabled( enabled );
linksImportFromFirefoxButton.setEnabled( enabled );
linksImportFromChromeButton.setEnabled( enabled );
keywordsSearchButton.setEnabled( enabled );
tagsViewButton.setEnabled( enabled );
}
private static void wireButtons()
{
keywordsSearchButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
String query = keywordsInput.getText().replace( " ", "+" );
// Only 64 results can be fetched using this method
// (8 pages of 8 results per page)
ArrayList <String> urlArrayList = doSearchJava( query );
// ArrayList <String> urlArrayList = doSearchLocalPython( query );
// ArrayList <String> urlArrayList = doSearchRemotePython( query );
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
} );
linksImportButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
String[] links = linksInput.getText().split( "\n" );
addLinks( links );
}
} );
linksImportFromChromeButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
// Determine the Chrome bookmarks file
String os = System.getProperty( "os.name" );
String userHome = System.getProperty( "user.home" );
File bookmarksFile = null;
if( os.startsWith( "Linux" ) )
bookmarksFile = new File(
userHome + "/.config/chromium/Default/Bookmarks" );
else if( os.startsWith( "Windows" ) )
bookmarksFile = new File(
userHome + "\\Local Settings\\Application Data\\" +
"\\Google\\Chrome\\User Data\\Default\\Bookmarks" );
// Scan bookmarks file for urls
if( bookmarksFile != null )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
String content = readFile(
bookmarksFile.getPath(), StandardCharsets.UTF_8 );
String regex = "\"url\": \"(.*)\"";
Pattern pattern = Pattern.compile( regex );
Matcher matcher = pattern.matcher( content );
while( matcher.find() )
urlArrayList.add( matcher.group( 1 ) );
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
}
} );
linksImportFromFirefoxButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
// Determine the Firefox bookmarks file
String os = System.getProperty( "os.name" );
String userHome = System.getProperty( "user.home" );
DirectoryScanner scanner = new DirectoryScanner();
scanner.setCaseSensitive( false );
String baseDir = null;
if( os.startsWith( "Linux" ) )
{
baseDir = userHome + "/.mozilla/firefox/";
scanner.setIncludes( new String[] { "*.default/places.sqlite" } );
scanner.setBasedir( baseDir );
}
else if( os.startsWith( "Windows" ) )
{
if( os.equals( "Windows XP" ) )
baseDir = userHome +
"\\Application Data\\Mozilla\\Firefox\\Profiles\\";
else
baseDir = userHome +
"\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\";
System.out.println( baseDir );
scanner.setIncludes(
new String[] { "*.default\\places.sqlite" } );
scanner.setBasedir( baseDir );
}
// Scan bookmarks files for urls
if( baseDir != null )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
scanner.scan();
String[] files = scanner.getIncludedFiles();
for( String f : files )
{
String ffDbFile = baseDir + f;
System.out.println( ffDbFile );
addUrlsFromDbToArray( ffDbFile, urlArrayList );
}
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
}
} );
tagsViewButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
Tags selectedTags = tagsPanel.getSelectedTags();
ArrayList<String> urlArrayList =
resultsModel.getTagLinks( selectedTags );
String[] links = urlArrayList.toArray(
new String[ urlArrayList.size() ] );
addLinks( links );
}
} );
}
public static void addUrlsFromDbToArray(
String ffDbFile, ArrayList<String> urlArrayList )
{
Connection dbh = null;
try
{
Class.forName( "org.sqlite.JDBC" );
dbh = DriverManager.getConnection( "jdbc:sqlite:" + ffDbFile );
}
catch( Exception ex ) { ex.printStackTrace(); }
if( dbh != null )
{
String query = "SELECT url FROM moz_places " +
"WHERE id IN ( SELECT fk FROM moz_bookmarks ) " +
"AND url LIKE 'http%'";
Statement stmt = null;
try
{
stmt = dbh.createStatement();
ResultSet rs = stmt.executeQuery( query );
while( rs.next() )
urlArrayList.add( rs.getString( 1 ) );
}
catch( Exception ex ) { ex.printStackTrace(); }
}
}
public static String readFile( String path, Charset encoding )
{
String content = null;
try
{
byte[] encoded = Files.readAllBytes( Paths.get( path ) );
content = encoding.decode( ByteBuffer.wrap( encoded ) ).toString();
}
catch( IOException ex ) {}
return content;
}
/*
private static ArrayList<String> doSearchLocalPython( String query )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
String cmd = "/home/john/stome/google_search2.py";
ProcessBuilder builder = new ProcessBuilder( cmd, query, "1", ip );
try
{
Process process = builder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader( process.getInputStream () ) );
String line = null;
while( ( line = reader.readLine () ) != null )
{
urlArrayList.add( line );
}
}
catch( java.io.IOException ex ) {}
return urlArrayList;
}
private static ArrayList<String> doSearchRemotePython( String query )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
String searchUrl =
"http://ec2-54-234-73-91.compute-1.amazonaws.com/" +
"cgi-bin/do_search.py?user_id=1&query=" +
query + "&page=1&ip=" + ip;
String content = getHTMLContent( searchUrl, 5000, ip );
String[] urls = content.split( "\n" );
for( int i = 0; i < urls.length; i++ )
urlArrayList.add( urls[ i ] );
return urlArrayList;
}
*/
private static ArrayList<String> doSearchJava( String query )
{
ArrayList<String> urlArrayList = new ArrayList<String>();
for( int page = 1; page <= 9; page++ )
{
int start = ( page - 1 ) * 8;
String searchUrl =
"https://ajax.googleapis.com/ajax/services/search/web" +
"?v=1.0&safe=active&rsz=large&start=" + start + "&q=" +
query + "&userip=" + ip;
String content = getHTMLContent( searchUrl, 5000, ip );
try
{
JSONParser parser = new JSONParser();
if( parser != null && content != null )
{
JSONObject json = (JSONObject) parser.parse( content );
JSONObject jdata = (JSONObject) json.get( "responseData" );
if( jdata != null )
{
JSONArray jresults = (JSONArray) jdata.get( "results" );
for( int i = 0; i < jresults.size(); i++ )
{
JSONObject jresult = (JSONObject) jresults.get( i );
String url = (String) jresult.get( "unescapedUrl" );
urlArrayList.add( url );
}
}
else
{
//System.err.println( json );
//System.err.println( searchUrl );
break;
}
}
}
catch( org.json.simple.parser.ParseException ex ) {}
// try { Thread.sleep( 200 ); } catch( InterruptedException ex ) {}
}
return urlArrayList;
}
public static String getClientIpAddr()
{
String ip = null;
try
{
ip = new BufferedReader( new InputStreamReader(
new URL( "http://agentgatech.appspot.com" ).
openStream() ) ).readLine();
}
catch( java.net.MalformedURLException ex ) {}
catch( java.io.IOException ex ) {}
return ip;
}
private static void addLinks( String[] links )
{
if( links != null && links.length > 0 )
{
buttonsSetEnabled( false );
resultsModel.startUrls();
int added = 0;
for( int i = 0; i < links.length; i++ )
{
if( urlIsValid( links[ i ] ) )
{
if( resultsModel.addUrl( links[ i ] ) )
added++;
}
}
resultsModel.stopUrls();
if( added == 0 )
buttonsSetEnabled( true );
}
}
private static void guiInit()
{
MigLayout buttonLayout = new MigLayout(
"", "[100%,align left][100%,align right]", ""
);
JLabel fetchStatusLabel = new JLabel();
resultsModel = new ResultsModel( fetchStatusLabel, dbFile );
Tags tags = resultsModel.getAllTags();
tags.add( 0, "" );
tagsPanel = new TagsPanel( resultsModel, tagsViewButton );
resultsModel.setTagsPanel( tagsPanel );
Java2sAutoComboBox newTagInput = new Java2sAutoComboBox( tags );
newTagInput.setStrict( false );
resultsModel.addNewTagInput( newTagInput );
// Links
JScrollPane linksInputScrollPane = new JScrollPane( linksInput );
JButton linksClearButton = new JButton( "Clear" );
linksClearButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
linksInput.setText( "" );
linksInput.requestFocus();
}
} );
JPanel linksPanel = new JPanel(
new MigLayout( "", "[grow]", "[][grow][][]" ) );
linksPanel.add( new JLabel( "Links" ), "span,wrap" );
linksPanel.add( linksInputScrollPane, "span,grow,wrap" );
linksPanel.add( linksClearButton, "align left" );
linksPanel.add( linksImportFromChromeButton, "align center" );
linksPanel.add( linksImportFromFirefoxButton, "align center" );
linksPanel.add( linksImportButton, "align right" );
// Keywords
keywordsInput.setPreferredSize(
new Dimension( keywordsInput.getMaximumSize().width,
keywordsInput.getPreferredSize().height ) );
keywordsInput.addKeyListener( new KeyListener() {
public void keyPressed( KeyEvent e )
{
if( e.getKeyCode() == KeyEvent.VK_ENTER )
keywordsSearchButton.doClick();
}
public void keyReleased( KeyEvent e ) {}
public void keyTyped( KeyEvent e ) {}
} );
JButton keywordsClearButton = new JButton( "Clear" );
keywordsClearButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
keywordsInput.setText( "" );
keywordsInput.requestFocus();
}
} );
JPanel keywordsPanel = new JPanel( new MigLayout() );
keywordsPanel.add( new JLabel( "Keywords" ), "span,wrap" );
keywordsPanel.add( keywordsInput, "span,wrap" );
keywordsPanel.add( keywordsClearButton, "align left" );
keywordsPanel.add( keywordsSearchButton, "align right" );
// Tags: managed by TagsPanel
tabbedPane = new JTabbedPane();
tabbedPane.add( "Search", keywordsPanel );
tabbedPane.add( "Import", linksPanel );
tabbedPane.add( "Tags", tagsPanel );
tabbedPane.addChangeListener( new ChangeListener() {
public void stateChanged( ChangeEvent e )
{
int selectedIndex = tabbedPane.getSelectedIndex();
if( selectedIndex == 0 )
{
keywordsInput.requestFocus();
frame.setTitle( "Search - " + Stome.APP_TITLE );
}
else if( selectedIndex == 1 )
{
linksInput.requestFocus();
frame.setTitle( "Import - " + Stome.APP_TITLE );
}
else if( selectedIndex == 2 )
{
frame.setTitle( "Tags - " + Stome.APP_TITLE );
}
}
} );
// Results
JLabel hoverUrlLabel = new JLabel();
Font font = hoverUrlLabel.getFont().deriveFont( Font.PLAIN );
hoverUrlLabel.setFont( font );
setLabelSize( fetchStatusLabel );
setLabelSize( hoverUrlLabel );
resultsTable = new JTable( resultsModel )
{
private static final long serialVersionUID = 105;
@Override public Component prepareRenderer(
TableCellRenderer tcr, int row, int column )
{
if( tcr == null )
return null;
try
{
Component c = super.prepareRenderer( tcr, row, column );
c.setForeground( getForeground() );
if( resultsTable.isRowSelected( row ) )
c.setBackground( selectedColor );
else
c.setBackground( ( row % 2 == 0 ) ?
evenColor : getBackground() );
return c;
}
catch( java.lang.NullPointerException ex ) {}
return null;
}
};
resultsTable.addMouseListener( new MouseAdapter()
{
public void mousePressed( MouseEvent e )
{
if( e.isPopupTrigger() )
openPopup( e );
}
public void mouseReleased( MouseEvent e )
{
if( e.isPopupTrigger() )
openPopup( e );
}
private void openPopup( MouseEvent e )
{
PopupMenu menu = new PopupMenu( frame, resultsTable );
menu.show( e.getComponent(), e.getX(), e.getY() );
}
} );
resultsTable.setIntercellSpacing( new Dimension() );
resultsTable.setShowGrid( false );
resultsTable.putClientProperty( "terminateEditOnFocusLost", Boolean.TRUE );
HyperlinkRenderer renderer = new HyperlinkRenderer( hoverUrlLabel );
resultsTable.setDefaultRenderer( Hyperlink.class, renderer );
resultsTable.addMouseListener( renderer );
resultsTable.addMouseMotionListener( renderer );
TagRenderer tagRenderer = new TagRenderer();
resultsTable.setDefaultRenderer( Tags.class, tagRenderer );
TableColumnModel resultsColModel = resultsTable.getColumnModel();
DefaultCellEditor cellEditor = new DefaultCellEditor( newTagInput );
cellEditor.setClickCountToStart( 1 );
resultsColModel.getColumn(
ResultsModel.NEW_TAG_COL ).setCellEditor( cellEditor );
setColumnWidth( resultsColModel, ResultsModel.SHARES_COL, 70, 70, 120 );
setColumnWidth( resultsColModel, ResultsModel.DOMAIN_COL, 60, 150, 250 );
setColumnWidth( resultsColModel, ResultsModel.NEW_TAG_COL, 60, 150, 250 );
setColumnWidth( resultsColModel, ResultsModel.TAGS_COL, 60, 200, -1 );
setColumnWidth( resultsColModel, ResultsModel.LINK_COL, 200, 400, -1 );
resultsTable.setAutoCreateRowSorter( true );
resultsTable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
resultsTable.setRowSelectionAllowed( true );
resultsTable.setFillsViewportHeight( true );
JScrollPane resultsScrollPane = new JScrollPane( resultsTable );
clearLinksButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
ResultsModel model = ( ResultsModel ) resultsTable.getModel();
model.clearLinks();
}
} );
JPanel resultsPane =
new JPanel( new MigLayout( "", "[grow]", "[][grow][]" ) );
resultsPane.add( clearLinksButton, "align left" );
resultsPane.add( fetchStatusLabel, "align right,wrap" );
resultsPane.add( resultsScrollPane, "span,grow,wrap" );
resultsPane.add( hoverUrlLabel, "span,grow" );
JSplitPane sp = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
sp.add( tabbedPane );
sp.add( resultsPane );
sp.setResizeWeight( 0.33d );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( sp );
frame.pack();
frame.setSize( new Dimension( 640, 480 ) );
frame.setVisible( true );
keywordsInput.requestFocus();
}
private static boolean urlIsValid( String url )
{
String[] schemes = { "http", "https" };
UrlValidator urlValidator = new UrlValidator( schemes );
if( urlValidator.isValid( url ) )
{
if( url.matches( "https?://webcache.googleusercontent.com/.*" ) ||
url.matches( "https?://www.google.com/search\\?.*" ) )
return false;
return true;
}
return false;
}
private static void setLabelSize( JLabel label )
{
FontMetrics fm = label.getFontMetrics( label.getFont() );
int fontHeight = fm.getAscent() + fm.getDescent() + fm.getLeading();
label.setMinimumSize(
new Dimension( label.getPreferredSize().width, fontHeight ) );
}
public static void setColumnWidth(
TableColumnModel colModel, int column,
int minWidth, int preferredWidth, int maxWidth )
{
if( minWidth >= 0 )
colModel.getColumn( column ).setMinWidth( minWidth );
if( preferredWidth >= 0 )
colModel.getColumn( column ).setPreferredWidth( preferredWidth );
if( maxWidth >= 0 )
colModel.getColumn( column ).setMaxWidth( maxWidth );
}
public static String getHTMLContent(
String url, int timeoutMilliseconds, String referer )
{
String content = "";
try
{
URL urlObj = new URL( url );
URLConnection conn = urlObj.openConnection();
conn.setRequestProperty( "Referer", referer );
conn.setConnectTimeout( timeoutMilliseconds );
BufferedReader in =
new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
String inputLine;
while( ( inputLine = in.readLine() ) != null )
content += inputLine;
in.close();
}
catch( IOException ex ) {}
return content;
}
}
|
Fixed popumenu mouseover location bug
|
Stome.java
|
Fixed popumenu mouseover location bug
|
<ide><path>tome.java
<ide> private void openPopup( MouseEvent e )
<ide> {
<ide> PopupMenu menu = new PopupMenu( frame, resultsTable );
<del> menu.show( e.getComponent(), e.getX(), e.getY() );
<add>// menu.show( e.getComponent(), e.getX(), e.getY() );
<add> menu.show( resultsTable, e.getX(), e.getY() );
<ide> }
<ide> } );
<ide>
|
|
Java
|
bsd-3-clause
|
f801d09fb328103df9d41005ebaedb49e22e78d4
| 0 |
Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java
|
/*
* Created by JFormDesigner on Thu Oct 04 18:36:31 MDT 2012
*/
package ucar.nc2.ui.geoloc;
import java.awt.*;
import java.awt.event.*;
import java.util.Collection;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.border.*;
import ucar.unidata.geoloc.ProjectionRect;
import ucar.unidata.util.Format;
import ucar.util.prefs.ui.*;
/**
* @author John Caron
*/
public class NewProjectionDialog extends JDialog {
public NewProjectionDialog(Frame owner) {
super(owner);
initComponents();
wire();
}
public NewProjectionDialog(Dialog owner) {
super(owner);
initComponents();
wire();
}
public void setProjectionManager(ProjectionManager pm, Collection<Object> types) {
this.pm = pm;
cbProjectionType.setItemList(types);
}
public NPController getNPController() {
return navPanel;
}
private static final int min_sigfig = 6;
private ProjectionManager pm;
private void wire() {
NavigatedPanel mapEditPanel = navPanel.getNavigatedPanel();
mapEditPanel.addNewMapAreaListener(new NewMapAreaListener() {
// nav panel moved
public void actionPerformed(NewMapAreaEvent e) {
ProjectionRect rect = e.getMapArea();
//System.out.printf("%s%n", rect.toString2());
minx.setText(Format.d(rect.getMinX(), min_sigfig));
maxx.setText(Format.d(rect.getMaxX(), min_sigfig));
miny.setText(Format.d(rect.getMinY(), min_sigfig));
maxy.setText(Format.d(rect.getMaxY(), min_sigfig));
}
});
// projection class was chosen
cbProjectionType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectionManager.ProjectionClass pc = (ProjectionManager.ProjectionClass) cbProjectionType.getSelectedItem();
projectionParamPanel1.setProjection(pc);
pc.makeDefaultProjection();
pc.putParamIntoDialog(pc.projInstance);
navPanel.setProjection(pc.projInstance);
invalidate();
validate();
}
});
// apply button was pressed
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectionManager.ProjectionClass pc = (ProjectionManager.ProjectionClass) cbProjectionType.getSelectedItem();
pc.setProjFromDialog(pc.projInstance);
System.out.printf("Projection = %s%n", pc.projInstance);
ProjectionRect mapArea = getMapAreaFromDialog();
if (mapArea != null) {
pc.projInstance.setDefaultMapArea(mapArea);
System.out.printf("mapArea = %s%n", mapArea.toString2());
}
projectionParamPanel1.setProjection(pc);
pc.putParamIntoDialog(pc.projInstance);
navPanel.setProjection(pc.projInstance);
if (mapArea != null)
navPanel.getNavigatedPanel().setMapArea(mapArea);
invalidate();
validate();
}
});
}
ProjectionRect getMapAreaFromDialog() {
try {
double minxv = Double.parseDouble(minx.getText());
double maxxv = Double.parseDouble(maxx.getText());
double minyv = Double.parseDouble(miny.getText());
double maxyv = Double.parseDouble(maxy.getText());
return new ProjectionRect(minxv, minyv, maxxv, maxyv);
} catch (Exception e) {
System.out.printf("Illegal value %s%n", e);
return null;
}
}
private void comboBox1ItemStateChanged(ItemEvent e) {
System.out.printf("%s%n", e);
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
dialogPane = new JPanel();
contentPanel = new JPanel();
panel1 = new JPanel();
cancelButton = new JButton();
okButton = new JButton();
applyButton = new JButton();
MapArePanel = new JPanel();
maxy = new JTextField();
label3 = new JLabel();
minx = new JTextField();
maxx = new JTextField();
miny = new JTextField();
label4 = new JLabel();
label5 = new JLabel();
label6 = new JLabel();
ProjPanel = new JPanel();
cbProjectionType = new ComboBox();
projectionParamPanel1 = new ProjectionParamPanel();
navPanel = new NPController();
buttonBar = new JPanel();
//======== this ========
setTitle("Projection Manager");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== dialogPane ========
{
dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));
dialogPane.setLayout(new BorderLayout());
//======== contentPanel ========
{
contentPanel.setLayout(new BorderLayout());
//======== panel1 ========
{
//---- cancelButton ----
cancelButton.setText("Cancel");
//---- okButton ----
okButton.setText("Save");
//---- applyButton ----
applyButton.setText("Apply");
//======== MapArePanel ========
{
MapArePanel.setBorder(new TitledBorder(null, "Map Area", TitledBorder.CENTER, TitledBorder.TOP));
//---- label3 ----
label3.setText("max y");
//---- label4 ----
label4.setText("min y");
//---- label5 ----
label5.setText("min x");
//---- label6 ----
label6.setText("max x");
GroupLayout MapArePanelLayout = new GroupLayout(MapArePanel);
MapArePanel.setLayout(MapArePanelLayout);
MapArePanelLayout.setHorizontalGroup(
MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addComponent(minx, GroupLayout.PREFERRED_SIZE, 109, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(maxx))
.addGroup(MapArePanelLayout.createSequentialGroup()
.addGroup(MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(label3))
.addGroup(MapArePanelLayout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(label4)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(MapArePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addComponent(label5)
.addGap(18, 18, 18)
.addComponent(maxy)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(label6)
.addContainerGap())
.addGroup(GroupLayout.Alignment.TRAILING, MapArePanelLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(miny, GroupLayout.PREFERRED_SIZE, 121, GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44))))
);
MapArePanelLayout.setVerticalGroup(
MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(MapArePanelLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addGroup(MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addComponent(label3)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(maxy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(label6, GroupLayout.Alignment.TRAILING))
.addComponent(label5))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(MapArePanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(maxx, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(minx, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(miny, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(label4)
.addContainerGap(14, Short.MAX_VALUE))
);
}
//======== ProjPanel ========
{
ProjPanel.setBorder(new TitledBorder(null, "Projection Class", TitledBorder.CENTER, TitledBorder.TOP));
ProjPanel.setLayout(new BoxLayout(ProjPanel, BoxLayout.X_AXIS));
//---- cbProjectionType ----
cbProjectionType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
comboBox1ItemStateChanged(e);
}
});
ProjPanel.add(cbProjectionType);
}
//---- projectionParamPanel1 ----
projectionParamPanel1.setBorder(new TitledBorder(null, "Parameters", TitledBorder.CENTER, TitledBorder.TOP));
GroupLayout panel1Layout = new GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(applyButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton))
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(panel1Layout.createParallelGroup()
.addComponent(ProjPanel, GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
.addComponent(MapArePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(projectionParamPanel1, GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup()
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(ProjPanel, GroupLayout.PREFERRED_SIZE, 44, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(projectionParamPanel1, GroupLayout.PREFERRED_SIZE, 252, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(MapArePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addGroup(panel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(okButton)
.addComponent(applyButton))
.addContainerGap())
);
}
contentPanel.add(panel1, BorderLayout.EAST);
//---- navPanel ----
navPanel.setPreferredSize(new Dimension(500, 250));
contentPanel.add(navPanel, BorderLayout.CENTER);
}
dialogPane.add(contentPanel, BorderLayout.CENTER);
//======== buttonBar ========
{
buttonBar.setBorder(new EmptyBorder(12, 0, 0, 0));
buttonBar.setLayout(new FlowLayout());
}
dialogPane.add(buttonBar, BorderLayout.SOUTH);
}
contentPane.add(dialogPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner non-commercial license
private JPanel dialogPane;
private JPanel contentPanel;
private JPanel panel1;
private JButton cancelButton;
private JButton okButton;
private JButton applyButton;
private JPanel MapArePanel;
private JTextField maxy;
private JLabel label3;
private JTextField minx;
private JTextField maxx;
private JTextField miny;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JPanel ProjPanel;
private ComboBox cbProjectionType;
private ProjectionParamPanel projectionParamPanel1;
private NPController navPanel;
private JPanel buttonBar;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
|
ui/src/main/java/ucar/nc2/ui/geoloc/NewProjectionDialog.java
|
/*
* Created by JFormDesigner on Thu Oct 04 18:36:31 MDT 2012
*/
package ucar.nc2.ui.geoloc;
import java.awt.*;
import java.awt.event.*;
import java.util.Collection;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.border.*;
import ucar.unidata.geoloc.ProjectionRect;
import ucar.unidata.util.Format;
import ucar.util.prefs.ui.*;
/**
* @author John Caron
*/
public class NewProjectionDialog extends JDialog {
public NewProjectionDialog(Frame owner) {
super(owner);
initComponents();
wire();
}
public NewProjectionDialog(Dialog owner) {
super(owner);
initComponents();
wire();
}
public void setProjectionManager(ProjectionManager pm, Collection<Object> types) {
this.pm = pm;
cbProjectionType.setItemList(types);
}
public NPController getNPController() {
return navPanel;
}
private static final int min_sigfig = 6;
private ProjectionManager pm;
private void wire() {
NavigatedPanel mapEditPanel = navPanel.getNavigatedPanel();
mapEditPanel.addNewMapAreaListener(new NewMapAreaListener() {
// nav panel moved
public void actionPerformed(NewMapAreaEvent e) {
ProjectionRect rect = e.getMapArea();
//System.out.printf("%s%n", rect.toString2());
minx.setText(Format.d(rect.getMinX(), min_sigfig));
maxx.setText(Format.d(rect.getMaxX(), min_sigfig));
miny.setText(Format.d(rect.getMinY(), min_sigfig));
maxy.setText(Format.d(rect.getMaxY(), min_sigfig));
}
});
// projection class was chosen
cbProjectionType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectionManager.ProjectionClass pc = (ProjectionManager.ProjectionClass) cbProjectionType.getSelectedItem();
projectionParamPanel1.setProjection(pc);
pc.makeDefaultProjection();
pc.putParamIntoDialog(pc.projInstance);
navPanel.setProjection(pc.projInstance);
revalidate();
}
});
// apply button was pressed
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectionManager.ProjectionClass pc = (ProjectionManager.ProjectionClass) cbProjectionType.getSelectedItem();
pc.setProjFromDialog(pc.projInstance);
System.out.printf("Projection = %s%n", pc.projInstance);
ProjectionRect mapArea = getMapAreaFromDialog();
if (mapArea != null) {
pc.projInstance.setDefaultMapArea(mapArea);
System.out.printf("mapArea = %s%n", mapArea.toString2());
}
projectionParamPanel1.setProjection(pc);
pc.putParamIntoDialog(pc.projInstance);
navPanel.setProjection(pc.projInstance);
if (mapArea != null)
navPanel.getNavigatedPanel().setMapArea(mapArea);
revalidate();
}
});
}
ProjectionRect getMapAreaFromDialog() {
try {
double minxv = Double.parseDouble(minx.getText());
double maxxv = Double.parseDouble(maxx.getText());
double minyv = Double.parseDouble(miny.getText());
double maxyv = Double.parseDouble(maxy.getText());
return new ProjectionRect(minxv, minyv, maxxv, maxyv);
} catch (Exception e) {
System.out.printf("Illegal value %s%n", e);
return null;
}
}
private void comboBox1ItemStateChanged(ItemEvent e) {
System.out.printf("%s%n", e);
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner non-commercial license
dialogPane = new JPanel();
contentPanel = new JPanel();
panel1 = new JPanel();
cancelButton = new JButton();
okButton = new JButton();
applyButton = new JButton();
MapArePanel = new JPanel();
maxy = new JTextField();
label3 = new JLabel();
minx = new JTextField();
maxx = new JTextField();
miny = new JTextField();
label4 = new JLabel();
label5 = new JLabel();
label6 = new JLabel();
ProjPanel = new JPanel();
cbProjectionType = new ComboBox();
projectionParamPanel1 = new ProjectionParamPanel();
navPanel = new NPController();
buttonBar = new JPanel();
//======== this ========
setTitle("Projection Manager");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
//======== dialogPane ========
{
dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));
dialogPane.setLayout(new BorderLayout());
//======== contentPanel ========
{
contentPanel.setLayout(new BorderLayout());
//======== panel1 ========
{
//---- cancelButton ----
cancelButton.setText("Cancel");
//---- okButton ----
okButton.setText("Save");
//---- applyButton ----
applyButton.setText("Apply");
//======== MapArePanel ========
{
MapArePanel.setBorder(new TitledBorder(null, "Map Area", TitledBorder.CENTER, TitledBorder.TOP));
//---- label3 ----
label3.setText("max y");
//---- label4 ----
label4.setText("min y");
//---- label5 ----
label5.setText("min x");
//---- label6 ----
label6.setText("max x");
GroupLayout MapArePanelLayout = new GroupLayout(MapArePanel);
MapArePanel.setLayout(MapArePanelLayout);
MapArePanelLayout.setHorizontalGroup(
MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addComponent(minx, GroupLayout.PREFERRED_SIZE, 109, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(maxx))
.addGroup(MapArePanelLayout.createSequentialGroup()
.addGroup(MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(label3))
.addGroup(MapArePanelLayout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(label4)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(MapArePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addComponent(label5)
.addGap(18, 18, 18)
.addComponent(maxy)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(label6)
.addContainerGap())
.addGroup(GroupLayout.Alignment.TRAILING, MapArePanelLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(miny, GroupLayout.PREFERRED_SIZE, 121, GroupLayout.PREFERRED_SIZE)
.addGap(44, 44, 44))))
);
MapArePanelLayout.setVerticalGroup(
MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(MapArePanelLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addGroup(MapArePanelLayout.createParallelGroup()
.addGroup(MapArePanelLayout.createSequentialGroup()
.addComponent(label3)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(maxy, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(label6, GroupLayout.Alignment.TRAILING))
.addComponent(label5))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(MapArePanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(maxx, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(minx, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(miny, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(label4)
.addContainerGap(14, Short.MAX_VALUE))
);
}
//======== ProjPanel ========
{
ProjPanel.setBorder(new TitledBorder(null, "Projection Class", TitledBorder.CENTER, TitledBorder.TOP));
ProjPanel.setLayout(new BoxLayout(ProjPanel, BoxLayout.X_AXIS));
//---- cbProjectionType ----
cbProjectionType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
comboBox1ItemStateChanged(e);
}
});
ProjPanel.add(cbProjectionType);
}
//---- projectionParamPanel1 ----
projectionParamPanel1.setBorder(new TitledBorder(null, "Parameters", TitledBorder.CENTER, TitledBorder.TOP));
GroupLayout panel1Layout = new GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(applyButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton))
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(panel1Layout.createParallelGroup()
.addComponent(ProjPanel, GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
.addComponent(MapArePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(projectionParamPanel1, GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup()
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(ProjPanel, GroupLayout.PREFERRED_SIZE, 44, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(projectionParamPanel1, GroupLayout.PREFERRED_SIZE, 252, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(MapArePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addGroup(panel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(okButton)
.addComponent(applyButton))
.addContainerGap())
);
}
contentPanel.add(panel1, BorderLayout.EAST);
//---- navPanel ----
navPanel.setPreferredSize(new Dimension(500, 250));
contentPanel.add(navPanel, BorderLayout.CENTER);
}
dialogPane.add(contentPanel, BorderLayout.CENTER);
//======== buttonBar ========
{
buttonBar.setBorder(new EmptyBorder(12, 0, 0, 0));
buttonBar.setLayout(new FlowLayout());
}
dialogPane.add(buttonBar, BorderLayout.SOUTH);
}
contentPane.add(dialogPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner non-commercial license
private JPanel dialogPane;
private JPanel contentPanel;
private JPanel panel1;
private JButton cancelButton;
private JButton okButton;
private JButton applyButton;
private JPanel MapArePanel;
private JTextField maxy;
private JLabel label3;
private JTextField minx;
private JTextField maxx;
private JTextField miny;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JPanel ProjPanel;
private ComboBox cbProjectionType;
private ProjectionParamPanel projectionParamPanel1;
private NPController navPanel;
private JPanel buttonBar;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
|
updated calls to revalidate() to work with Mac, as Apple java does not fully implement the revalidate method
|
ui/src/main/java/ucar/nc2/ui/geoloc/NewProjectionDialog.java
|
updated calls to revalidate() to work with Mac, as Apple java does not fully implement the revalidate method
|
<ide><path>i/src/main/java/ucar/nc2/ui/geoloc/NewProjectionDialog.java
<ide> pc.makeDefaultProjection();
<ide> pc.putParamIntoDialog(pc.projInstance);
<ide> navPanel.setProjection(pc.projInstance);
<del> revalidate();
<add> invalidate();
<add> validate();
<ide> }
<ide> });
<ide>
<ide> if (mapArea != null)
<ide> navPanel.getNavigatedPanel().setMapArea(mapArea);
<ide>
<del> revalidate();
<add> invalidate();
<add> validate();
<ide> }
<ide> });
<ide>
|
|
JavaScript
|
mit
|
2d3a6da46f82960864d480b023ce46f6a259d00e
| 0 |
Cryogen-Networks/Cryoventure,Cryogen-Networks/Cryoventure
|
main.min.js
|
function Character(){this.name=prompt("Choose a name for your character."),this.inventory=[],this.outfit={helm:null,body:null,legs:null,feet:null}}function play(){var o=new Character;console.log("Welcome to Cryogen, "+o.name+"! You are now starting on your adventure..\n"),console.log("thx 4 playin', pls rate on da app store")}play()
|
Remove minfied version. (Uneeded ATM)
|
main.min.js
|
Remove minfied version. (Uneeded ATM)
|
<ide><path>ain.min.js
<del>function Character(){this.name=prompt("Choose a name for your character."),this.inventory=[],this.outfit={helm:null,body:null,legs:null,feet:null}}function play(){var o=new Character;console.log("Welcome to Cryogen, "+o.name+"! You are now starting on your adventure..\n"),console.log("thx 4 playin', pls rate on da app store")}play()
|
||
Java
|
apache-2.0
|
37ae5ec3e55daea194dde89a6fb835aed71668d5
| 0 |
juancabreraIT/jUnit
|
package com.java.exe;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import com.java.junit.TestJunit;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for(Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println("Test result: " + result.wasSuccessful());
}
}
|
src/com/java/exe/TestRunner.java
|
package com.java.exe;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import com.java.junit.TestJunit;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for(Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
|
Minor fix
|
src/com/java/exe/TestRunner.java
|
Minor fix
|
<ide><path>rc/com/java/exe/TestRunner.java
<ide> System.out.println(failure.toString());
<ide> }
<ide>
<del> System.out.println(result.wasSuccessful());
<add> System.out.println("Test result: " + result.wasSuccessful());
<ide> }
<ide>
<ide> }
|
|
Java
|
apache-2.0
|
4e0692378e919fe2bfbefc147ba45a649e3a7dd1
| 0 |
Gueust/DTA-PC,Gueust/DTA-PC
|
package dta_solver;
import io.InputOutput;
import java.util.Iterator;
import java.util.Map.Entry;
import generalLWRNetwork.Cell;
import generalLWRNetwork.Destination;
import generalLWRNetwork.Junction;
import generalLWRNetwork.Origin;
import generalNetwork.state.CellInfo;
import generalNetwork.state.JunctionInfo;
import generalNetwork.state.Profile;
import generalNetwork.state.State;
import generalNetwork.state.externalSplitRatios.IntertemporalOriginsSplitRatios;
import generalNetwork.state.internalSplitRatios.IntertemporalJunctionSplitRatios;
import generalNetwork.state.internalSplitRatios.IntertemporalSplitRatios;
import generalNetwork.state.internalSplitRatios.JunctionSplitRatios;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import cern.colt.matrix.tdouble.impl.SparseCCDoubleMatrix2D;
import cern.colt.matrix.tdouble.impl.SparseDoubleMatrix1D;
import cern.colt.matrix.tdouble.DoubleFactory1D;
import dataStructures.Numerical;
import dataStructures.Triplet;
import dta_solver.adjointMethod.Adjoint;
public class SO_Optimizer extends Adjoint<State> {
private Simulator simulator;
private double epsilon = 0.001;
/* Share of the compliant commodities */
private double alpha;
/* Total number of time steps */
private int T;
/* Number of compliant commodities */
private int C;
private Cell[] cells;
private Junction[] junctions;
private Origin[] sources;
private Destination[] destinations;
/* Number of origins */
private int O;
/* Number of destinations */
private int S;
/* Control Vector U */
/* Total size of a block for one time step of the control */
private int temporal_control_block_size;
/* State Vector X */
/* Size of a block describing all the densities for a given time step */
private int size_density_block;
/* Size of a block describing all the supply/demand at one time step */
private int size_demand_suply_block;
/* Size of the block describing all the Aggregate SR at one time sate */
private int size_aggregate_split_ratios;
/* Size of a block describing out-flows */
private int size_f_out_block;
/* Total size of the description of a profile for a given time step */
private int x_block_size;
private int demand_supply_position;
private int aggregate_split_ratios_position;
private int f_out_position;
private int f_in_position;
/* Constraints Vector H */
/* Size of a block describing the Mass Conversation constraints */
// size_density_block;
/* Size of a block describing the Flow Propagation constraints */
private int flow_propagation_size;
/* Size of the block describing the Aggregate SR constraints */
// size_aggregate_split_ratios;
/* Size of the block describing the out-flows constraints : */
// mass_conservation_size
/* Size of the block describing the in-flows constraints : */
// mass_conservation_size
/* Total size of a block of constraints for a given time step */
// x_block_size
public SO_Optimizer(int maxIter, Simulator simu) {
super(maxIter);
simulator = simu;
alpha = simu.getAlpha();
T = simulator.time_discretization.getNb_steps();
C = simulator.lwr_network.getNb_compliantCommodities();
cells = simulator.lwr_network.getCells();
sources = simulator.lwr_network.getSources();
O = sources.length;
destinations = simulator.lwr_network.getSinks();
S = destinations.length;
junctions = simulator.lwr_network.getJunctions();
/* For every time steps there are C compliant flows, and O non compliant */
temporal_control_block_size = C;
/* State Vector X */
/* Size of a block describing all the densities for a given time step */
size_density_block = cells.length * (C + 1);
/* Size of a block describing all the supply/demand at one time step */
size_demand_suply_block = 2 * cells.length;
/* Size of the block describing all the Aggregate SR at one time sate */
Junction junction;
int tmp_nb_aggregate_split_ratios = 0;
for (int j = 0; j < junctions.length; j++) {
junction = junctions[j];
tmp_nb_aggregate_split_ratios +=
junction.getPrev().length * junction.getNext().length;
}
size_aggregate_split_ratios = tmp_nb_aggregate_split_ratios;
/* Size of a block describing out-flows or in-flows */
size_f_out_block = size_density_block;
/* Total size of the description of a profile for a given time step */
x_block_size = (3 * (C + 1) + 2) * cells.length
+ size_aggregate_split_ratios;
demand_supply_position = size_density_block;
aggregate_split_ratios_position =
demand_supply_position + size_demand_suply_block;
f_out_position =
aggregate_split_ratios_position + size_aggregate_split_ratios;
f_in_position = f_out_position + size_f_out_block;
/* Constraints Vector H */
/* Size of a block describing the Mass Conversation constraints */
// size_density_block;
/* Size of a block describing the Flow Propagation constraints */
flow_propagation_size = size_demand_suply_block;
/* Size of the block describing the Aggregate SR constraints */
// size_aggregate_split_ratios;
/* Size of the block describing the out-flows constraints : */
// mass_conservation_size
/* Size of the block describing the in-flows constraints : */
// mass_conservation_size
/* Total size of a block of constraints for a given time step */
int H_block_size = 3 * size_density_block + flow_propagation_size
+ size_aggregate_split_ratios;
assert (H_block_size == x_block_size);
/* Initialization of the split ratios for the Optimizer */
simulator.initializeSplitRatiosForOptimizer();
}
public void printSizes() {
System.out.println("Total size of X: " + T * x_block_size);
System.out.println("Details: \n" +
"- time steps: " + T + "\n" +
"- density_block: " + size_density_block +
" : (1 NC + " + C + "compliant commodities )* " + cells.length
+ " cells\n" +
"- demand_supply: " + size_demand_suply_block +
" : 2 (for demand, supply) * " + cells.length + " cells)\n" +
"- aggregate SR: " + size_aggregate_split_ratios +
"(is the sum of the in.size() * out.size() at all junctions\n" +
"- f_out: " + size_density_block +
" : (same as the density block)\n" +
"- f_ in: " + size_density_block +
" : (same as the density block)");
System.out.println("Total size of H: " + T * x_block_size);
System.out.println("Details: " + T + " time steps, " +
"(Mass Cons: " + size_density_block +
", Flow prog: " + flow_propagation_size +
", aggregate SR: " + size_aggregate_split_ratios +
", f_in and out: " + 2 * size_density_block);
}
/**
* @brief Return the 1x(C*T) matrix representing the control where
* C is the number of compliant commodities
* @details There are T blocks of size C. The i-th block contains the
* controls at time step i.
*/
public double[] getControl() {
assert alpha != 0 : "The share of the compliant commodities is zero. No optimization possible";
IntertemporalOriginsSplitRatios splits = simulator.splits;
/* For every time steps there are C compliant flows */
double[] control = new double[T * temporal_control_block_size];
int index_in_control = 0;
int commodity;
Double split_ratio;
for (int orig = 0; orig < O; orig++) {
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
/*
* Mapping between splits.get(sources[orig], k).get(commodity) and
* U[k*(C + sources.length) + index_in_control]
*/
split_ratio = splits.get(sources[orig], k).get(commodity);
if (split_ratio != null)
// The sum of the split ratios at the control should be equal to 1
// for a given origin
control[k * temporal_control_block_size + index_in_control] = split_ratio
/ alpha;
}
index_in_control++;
}
}
return control;
}
/**
* @brief Return the 1x(C+O)*T= matrix representing the compliant and
* non-compliant commodities where C is the number of compliant
* commodities and 0 the number of origins
* @details There are T blocks of size (C+O). The i-th block contains the
* controls at time step i.
*/
private double[] getFullControl() {
IntertemporalOriginsSplitRatios splits = simulator.splits;
/* For every time steps there are C compliant flows, and O non compliant */
double[] control = new double[T * (C + 1)];
int index_in_control = 0;
int commodity;
Double split_ratio;
for (int orig = 0; orig < O; orig++) {
for (int k = 0; k < T; k++) {
split_ratio = splits.get(sources[orig], k).get(0);
if (split_ratio != null) {
control[k * temporal_control_block_size + index_in_control] = split_ratio;
}
}
index_in_control++;
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
split_ratio = splits.get(sources[orig], k).get(commodity);
if (split_ratio != null) {
control[k * temporal_control_block_size + index_in_control] = split_ratio
* alpha;
}
}
index_in_control++;
}
}
return control;
}
public void printFullControl() {
InputOutput.printControl(getFullControl(), C + 1);
}
private void parseStateVector(Profile p) {
int block_id, sub_block_id;
int commodity;
int index_in_state = 0;
double value;
CellInfo cell_info;
for (int k = 0; k < T; k++) {
/* Id of the first data of time step k */
block_id = k * x_block_size;
for (int cell_id = 0; cell_id < cells.length; cell_id++) {
cell_info = p.getCell(cells[cell_id]);
/* Id of the first index containing data from cells[cell_id] */
sub_block_id = block_id + cell_id * C;
// Operations on densities
Iterator<Entry<Integer, Double>> it =
cell_info.partial_densities.entrySet().iterator();
Entry<Integer, Double> entry;
while (it.hasNext()) {
entry = it.next();
commodity = entry.getKey();
// density (cell_id, commodity)(k)
index_in_state = sub_block_id + commodity;
value = entry.getValue();
}
// Operations on demand and supply
index_in_state = sub_block_id + size_density_block;
value = cell_info.demand;
index_in_state++;
value = cell_info.supply;
// Operations on aggregate split ratios
index_in_state += size_demand_suply_block;
JunctionInfo junction_info;
Junction junction;
for (int j = 0; j < junctions.length; j++) {
junction = junctions[j];
junction_info = p.getJunction(j);
for (int in = 0; in < junction.getPrev().length; in++) {
for (int out = 0; out < junction.getNext().length; out++) {
// Mapping between junctions_info.get(new PairCell(in, out));
index_in_state++;
}
}
}
// Operation on out-flows
sub_block_id += size_aggregate_split_ratios;
it = cell_info.out_flows.entrySet().iterator();
while (it.hasNext()) {
entry = it.next();
commodity = entry.getKey();
// flow_out (cell_id, commodity)(k)
index_in_state = sub_block_id + commodity;
value = entry.getValue();
}
// Operations on in-flows
index_in_state += size_f_out_block;
it = cell_info.in_flows.entrySet().iterator();
while (it.hasNext()) {
entry = it.next();
commodity = entry.getKey();
// flow_in (cell_id, commodity)(k)
index_in_state = sub_block_id + commodity;
value = entry.getValue();
}
}
}
}
/**
* @brief Computes the dH/dU matrix.
* @details
*/
@Override
public SparseCCDoubleMatrix2D dhdu(State state, double[] control) {
SparseCCDoubleMatrix2D result = new SparseCCDoubleMatrix2D(
x_block_size * T,
temporal_control_block_size * T);
int i, j, index_in_control = 0;
int commodity;
double[] origin_demands;
for (int orig = 0; orig < O; orig++) {
origin_demands = simulator.origin_demands.get(sources[orig]);
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
i = k * x_block_size + sources[orig].getUniqueId() * (C + 1)
+ commodity;
j = k * temporal_control_block_size + index_in_control;
result.setQuick(i, j, origin_demands[k] * alpha);
}
index_in_control++;
}
}
return result;
}
@Override
public SparseCCDoubleMatrix2D dhdx(State state, double[] control) {
IntertemporalSplitRatios internal_SR =
simulator.lwr_network.getInternal_split_ratios();
SparseCCDoubleMatrix2D result = new SparseCCDoubleMatrix2D(
x_block_size * T,
x_block_size * T);
double delta_t = simulator.time_discretization.getDelta_t();
/* The diagonal terms are done at the end */
/*********************************************************
* Derivative terms for the Mass Conservation constraints
*********************************************************/
// System.out.print("Mass conservation : ");
// long startTime = System.currentTimeMillis();
// Position of a block of constraints in H indexed by k
int block_upper_position;
// Position of a block in the Mass Conservation block indexed by the cell_id
int sub_block_position;
double delta_t_over_l;
int i, j;
for (int k = 1; k < T; k++) {
block_upper_position = k * x_block_size;
for (int cell_id = 0; cell_id < cells.length; cell_id++) {
sub_block_position = (C + 1) * cell_id;
for (int c = 0; c < C + 1; c++) {
// Line of interest in the H matrix
i = block_upper_position + sub_block_position + c;
// Column of interest in the H matrix
j = x_block_size * (k - 1) + sub_block_position + c;
/*
* We put 1 for the derivative terms of the mass conversation
* equations (i,c,k) with respect to density(i,c,k-1) for k \in [1, T]
*/
result.setQuick(i, j, 1.0);
/*
* Derivative terms with respect to flow-out(i,c,k-1) and
* flow-in(i,c,k-1)
*/
delta_t_over_l = delta_t /
simulator.lwr_network.getCell(cell_id).getLength();
assert Numerical.validNumber(delta_t_over_l);
// d \density(i, k) / d f_out(i,k-1) = - delta_t / l
result.setQuick(i, j + f_out_position, -delta_t_over_l);
// d \density(i, k) / d f_in(i,k-1) = delta_t / l
result.setQuick(i, j + f_in_position, delta_t_over_l);
}
}
// For the buffers and sinks we have put a derivative term that should
// have been zero
for (int o = 0; o < O; o++) {
for (int c = 0; c < C + 1; c++) {
i = block_upper_position + (C + 1) * sources[o].getUniqueId() + c;
j = x_block_size * (k - 1) + (C + 1) * sources[o].getUniqueId() + c;
// flow-in
result.setQuick(i, j + f_in_position, 0.0);
}
}
for (int s = 0; s < S; s++) {
for (int c = 0; c < C + 1; c++) {
i = block_upper_position + (C + 1) * destinations[s].getUniqueId()
+ c;
j = x_block_size * (k - 1) + (C + 1) * destinations[s].getUniqueId()
+ c;
// flow-out
result.setQuick(i, j + f_out_position, 0.0);
}
}
}
// long endTime = System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the Flow propagation (demand/supply)
*********************************************************/
// System.out.print("Flow propagation: ");
// startTime= System.currentTimeMillis();
double total_density;
for (int k = 0; k < T; k++) {
// Position of the first constraint in H dealing with supply/demand at
// time step k
block_upper_position = k * x_block_size + demand_supply_position;
for (int cell_id = 0; cell_id < cells.length; cell_id++) {
sub_block_position = cell_id * 2;
i = block_upper_position + sub_block_position;
total_density = state.profiles[k].getCell(cell_id).total_density;
for (int c = 0; c < C + 1; c++) {
// Demand first
result.setQuick(i,
x_block_size * k + cell_id * (C + 1) + c,
cells[cell_id].getDerivativeDemand(total_density, delta_t));
// Then supply
result.setQuick(i + 1,
x_block_size * k + cell_id * (C + 1) + c,
cells[cell_id].getDerivativeSupply(total_density));
}
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the Aggregate Split Ratios
*********************************************************/
// System.out.print("Aggregate SR: ");
// startTime= System.currentTimeMillis();
/*
* This part is not efficient because we have to do
* Nb_Aggregate_SR * T * (C+1) computation of derivative terms
*/
Junction junction;
/* Used to know the position of the current SR under study */
int aggregate_SR_index = 0;
Double partial_density;
/* Used to store beta(i,j,c)(k) */
Double i_j_c_SR;
/* Store the split ratios at a junction. Is null when Nx1 junction */
JunctionSplitRatios junction_SR;
CellInfo in_cell_info;
int prev_length, next_length;
for (int j_id = 0; j_id < junctions.length; j_id++) {
junction = junctions[j_id];
IntertemporalJunctionSplitRatios intert_junction_SR =
internal_SR.get(j_id);
prev_length = junction.getPrev().length;
for (int in = 0; in < prev_length; in++) {
Cell in_cell = junction.getPrev()[in];
next_length = junction.getNext().length;
for (int out = 0; out < next_length; out++) {
Cell out_cell = junction.getNext()[out];
for (int k = 0; k < T; k++) {
/* Here we study beta(in, out) (k) */
block_upper_position = k * x_block_size
+ aggregate_split_ratios_position;
/*
* There are no inter-temporal split ratios for Nx1 junctions.
* More precisely for all i \in Incoming link and j the unique
* outgoing link
* we have all the split ratio from i to j that is 1 and constant
*/
if (intert_junction_SR == null)
junction_SR = null;
else {
junction_SR = intert_junction_SR.get(k);
assert junction_SR != null;
}
in_cell_info = state.profiles[k].getCell(in_cell);
i = block_upper_position + aggregate_SR_index;
j = k * x_block_size + (C + 1) * in_cell.getUniqueId();
for (int c = 0; c < C + 1; c++) {
/*
* If there are no intertemporal_split ratios this means we are at
* a Nx1 junction and we always have beta = 1. However for the 1x1
* junction, the aggregate spit ratio has absolutely no influence
* on the flows and we can do without computing it
* TODO: Optimization possible
*/
if (junction_SR == null) {
if (prev_length == 1 && next_length == 1)
continue;
i_j_c_SR = 1.0;
} else
i_j_c_SR = junction_SR.get(in_cell.getUniqueId(),
out_cell.getUniqueId(), c);
/*
* If the split ratio for this commodity is zero, then the
* aggregate split ratio is independent of this split ratio
*/
// if (i_j_c_SR == null || i_j_c_SR == 0)
// continue;
if (i_j_c_SR == null) {
continue;
// i_j_c_SR = 0.0;
}
partial_density = in_cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
total_density = in_cell_info.total_density;
if (total_density != 0) {
double derivative_term = i_j_c_SR
* (total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(derivative_term);
if (derivative_term != 0)
result.setQuick(i, j + c, derivative_term);
}
}
}
aggregate_SR_index++;
}
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the out-flows
*********************************************************/
// System.out.print("Out-flows: ");
// startTime= System.currentTimeMillis();
int nb_prev, nb_next;
double value;
for (int j_id = 0; j_id < junctions.length; j_id++) {
junction = junctions[j_id];
nb_prev = junction.getPrev().length;
nb_next = junction.getNext().length;
// Derivative terms for 1x1 junctions
if (nb_prev == 1 && nb_next == 1) {
double demand, supply, f_out;
CellInfo cell_info;
int prev_id = junction.getPrev()[0].getUniqueId();
int next_id = junction.getNext()[0].getUniqueId();
for (int k = 0; k < T; k++) {
cell_info = state.profiles[k].getCell(prev_id);
total_density = cell_info.total_density;
if (total_density == 0)
continue;
demand = cell_info.demand;
supply = state.profiles[k].getCell(next_id).supply;
f_out = Math.min(demand, supply);
for (int c = 0; c < C + 1; c++) {
partial_density = cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
i = x_block_size * k + f_out_position + (C + 1) * prev_id + c;
/*
* Derivative terms with respect to the partial densities.
* There are 3 cases but the use of f_out = min (supply,demand)
* makes a factorization possible
*/
j = x_block_size * k + (C + 1) * prev_id + c;
value = f_out * (total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
/* Derivative terms with respect to supply/demand */
if (partial_density == 0)
continue;
if (demand < supply) {
j = x_block_size * k + demand_supply_position + 2 * prev_id;
} else if (supply < demand) {
j = x_block_size * k + demand_supply_position + 2 * prev_id + 1;
}
value = partial_density / total_density;
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
}
}
// Derivative terms for 1x2 junctions
} else if (nb_prev == 2 && nb_next == 1) {
int in_1 = junction.getPrev()[0].getUniqueId();
int in_2 = junction.getPrev()[1].getUniqueId();
int out = junction.getNext()[0].getUniqueId();
double P1 = junction.getPriority(in_1);
double P2 = junction.getPriority(in_2);
double demand1, demand2, supply, f_in;
for (int k = 0; k < T; k++) {
demand1 = state.profiles[k].getCell(in_1).demand;
demand2 = state.profiles[k].getCell(in_2).demand;
supply = state.profiles[k].getCell(out).supply;
f_in = Math.min(demand1 + demand2, supply);
double total_density1 = state.profiles[k].getCell(in_1).total_density;
double total_density2 = state.profiles[k].getCell(in_2).total_density;
for (int c = 0; c < C + 1; c++) {
double Df_inDdemand1 = 0, Df_inDdemand2 = 0, Df_inDsupply = 0;
if (demand1 + demand2 < supply) {
Df_inDdemand1 = 1;
Df_inDdemand2 = 1;
}
if (supply < demand1 + demand2) {
Df_inDsupply = 1;
}
/* For the first incoming road in_1 */
/* Derivative terms with respect to the partial densities */
partial_density = state.profiles[k].getCell(in_1).partial_densities
.get(c);
if (partial_density == null)
partial_density = 0.0;
if (total_density1 != 0) {
double f_in_1_out;
double DfDdemand1 = 0, DfDdemand2 = 0, DfDsupply = 0;
if (P1 * (f_in - demand1) > P2 * demand1) {
f_in_1_out = demand1;
DfDdemand1 = 1;
} else if (P1 * demand2 < P2 * (f_in - demand2)) {
f_in_1_out = f_in - demand2;
DfDdemand1 = Df_inDdemand1;
DfDdemand2 = Df_inDdemand2 - 1;
DfDsupply = Df_inDsupply;
} else {
f_in_1_out = P1 * f_in;
DfDdemand1 = P1 * Df_inDdemand1;
DfDdemand2 = P1 * Df_inDdemand2;
DfDsupply = P1 * Df_inDsupply;
}
i = x_block_size * k + f_out_position + in_1
* (C + 1) + c;
j = x_block_size * k + in_1 * (C + 1) + c;
value = f_in_1_out * (total_density1 - partial_density)
/ (total_density1 * total_density1);
result.setQuick(i, j, value);
/* Derivative terms with respect to supply/demand */
if (partial_density != 0) {
if (DfDdemand1 != 0) {
j = x_block_size * k + demand_supply_position + in_1 * 2;
assert Numerical.validNumber(DfDdemand1);
result.setQuick(i, j, DfDdemand1);
}
if (DfDdemand2 != 0) {
j = x_block_size * k + demand_supply_position + in_2 * 2;
assert Numerical.validNumber(DfDdemand2);
result.setQuick(i, j, DfDdemand2);
}
if (DfDsupply != 0) {
j = x_block_size * k + demand_supply_position + out * 2 + 1;
assert Numerical.validNumber(DfDsupply);
result.setQuick(i, j, DfDsupply);
}
}
}
/* For the second incoming road in_2 */
/* Derivative terms with respect to the partial densities */
partial_density = state.profiles[k].getCell(in_2).partial_densities
.get(c);
if (partial_density == null)
partial_density = 0.0;
if (total_density2 != 0) {
double f_in_2_out;
double DfDdemand1 = 0, DfDdemand2 = 0, DfDsupply = 0;
if (P2 * (f_in - demand2) > P1 * demand2) {
f_in_2_out = demand1;
DfDdemand2 = 1;
} else if (P2 * demand2 < P1 * (f_in - demand1)) {
f_in_2_out = f_in - demand1;
DfDdemand2 = Df_inDdemand2;
DfDdemand1 = Df_inDdemand1 - 1;
DfDsupply = Df_inDsupply;
} else {
f_in_2_out = P2 * f_in;
DfDdemand2 = P2 * Df_inDdemand2;
DfDdemand1 = P2 * Df_inDdemand1;
DfDsupply = P2 * Df_inDsupply;
}
i = x_block_size * k + f_out_position + in_2
* (C + 1) + c;
j = x_block_size * k + in_2 * (C + 1) + c;
value = f_in_2_out * (total_density2 - partial_density)
/ (total_density2 * total_density2);
result.setQuick(i, j, value);
/* Derivative terms with respect to supply/demand */
if (partial_density != 0) {
if (DfDdemand1 != 0) {
j = x_block_size * k + demand_supply_position + in_1 * 2;
assert Numerical.validNumber(DfDdemand1);
result.setQuick(i, j, DfDdemand1);
}
if (DfDdemand2 != 0) {
j = x_block_size * k + demand_supply_position + in_2 * 2;
assert Numerical.validNumber(DfDdemand2);
result.setQuick(i, j, DfDdemand2);
}
if (DfDsupply != 0) {
j = x_block_size * k + demand_supply_position + out * 2 + 1;
assert Numerical.validNumber(DfDsupply);
result.setQuick(i, j, DfDsupply);
}
}
}
}
}
// Derivative terms for 1xN junctions
} else if (nb_prev == 1) {
CellInfo cell_info;
for (int k = 0; k < T; k++) {
int in_id = junction.getPrev()[0].getUniqueId();
cell_info = state.profiles[k].getCell(in_id);
Cell[] next_cells = junction.getNext();
total_density = cell_info.total_density;
double demand = cell_info.demand;
if (total_density != 0) {
/*
* We find j such that f_(in_id)_out = min (supply_j /
* \beta_(in_id)_j)
*/
double minimum = Double.MAX_VALUE;
int minimum_id_cell = 0;
double min_supply = -1, supply, beta_at_minimum = 0;
Double beta;
for (int out = 0; out < next_cells.length; out++) {
beta = state.profiles[k]
.getJunction(junction)
.getAggregateSR(in_id, next_cells[out].getUniqueId());
if (beta == null)
beta = 0.0;
if (beta != 0) {
supply = state.profiles[k].getCell(next_cells[out]).supply;
if (supply / beta < minimum) {
min_supply = supply / beta;
minimum_id_cell = next_cells[out].getUniqueId();
beta_at_minimum = beta;
}
}
}
assert min_supply != -1;
double flow_out;
Double tmp;
if (demand < min_supply) {
flow_out = demand;
/* Derivative with respect to partial densities */
for (int c = 0; c < C + 1; c++) {
partial_density = cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
i = x_block_size * k + f_out_position
+ in_id * (C + 1) + c;
j = x_block_size * k + minimum_id_cell * (C + 1) + c;
tmp = internal_SR.get(k, j_id).get(in_id, minimum_id_cell, c);
if (tmp != null && tmp != 0) {
value = tmp
* flow_out *
(total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
/* Derivative with respect to supply and demand */
j = x_block_size * k + demand_supply_position + in_id * 2;
value = tmp
* partial_density / total_density;
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
}
}
} else if (min_supply < demand) {
flow_out = min_supply;
/* Derivative with respect to partial densities */
for (int c = 0; c < C + 1; c++) {
partial_density = cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
i = x_block_size * k + f_out_position
+ in_id * (C + 1) + c;
j = x_block_size * k + minimum_id_cell * (C + 1) + c;
tmp = internal_SR.get(k, j_id).get(in_id, minimum_id_cell, c);
if (tmp != null && tmp != 0) {
value = tmp
* flow_out *
(total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
/* Derivative with respect to supply and demand */
j = x_block_size * k + demand_supply_position
+ minimum_id_cell * 2 + 1;
value = tmp
* partial_density / total_density / beta_at_minimum;
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
}
}
}
}
}
} else {
assert false : "[dhdx] Only 1x1, 1x2, and Nx1 junctions are possible";
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the in-flows
*********************************************************/
// System.out.print("In-flows: ");
// startTime= System.currentTimeMillis();
int commodity, in_id, out_id;
for (int j_id = 0; j_id < junctions.length; j_id++) {
for (int k = 0; k < T; k++) {
junction_SR = internal_SR.get(k, j_id);
/* If there is no split ratios, it means it is a Nx1 junction */
if (junction_SR == null) {
for (in_id = junctions[j_id].getPrev()[0].getUniqueId(); in_id < junctions[j_id]
.getPrev().length; in_id++) {
// We don't know the split ratios so we suppose it is 1 for all
assert junctions[j_id].getNext().length <= 1;
for (int c = 0; c < C + 1; c++) {
i = x_block_size * k + 2 * size_density_block
+ flow_propagation_size + aggregate_SR_index
+ junctions[j_id].getNext()[0].getUniqueId() * (C + 1)
+ c;
j = x_block_size * k + f_out_position + in_id * (C + 1) + c;
result.setQuick(i, j, 1.0);
}
}
} else {
Iterator<Entry<Triplet, Double>> iterator =
junction_SR.non_compliant_split_ratios
.entrySet()
.iterator();
Entry<Triplet, Double> entry;
while (iterator.hasNext()) {
entry = iterator.next();
in_id = entry.getKey().incoming;
out_id = entry.getKey().outgoing;
commodity = entry.getKey().commodity;
i = x_block_size * k + 2 * size_density_block
+ flow_propagation_size + aggregate_SR_index + out_id * (C + 1)
+ commodity;
j = x_block_size * k + f_out_position + in_id * (C + 1) + commodity;
assert Numerical.validNumber(entry.getValue());
result.setQuick(i, j, entry.getValue());
}
}
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
// System.out.print("Diagonal terms: ");
// startTime= System.currentTimeMillis();
for (int index = 0; index < x_block_size * T; index++)
result.setQuick(index, index, -1.0);
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
return result;
}
/**
* @brief Computes the derivative dJ/dU
* @details
* The condition \beta >= 0 is already put in the solver (in
* AdjointJVM/org.wsj/Optimizers.scala) do there is only one barrier
* in J
*/
@Override
public DoubleMatrix1D djdu(State state, double[] control) {
DoubleMatrix1D result =
DoubleFactory1D.dense.make(T * temporal_control_block_size);
int index_in_control = 0;
double sum_of_split_ratios;
double[] origin_demands;
for (int orig = 0; orig < O; orig++) {
origin_demands = simulator.origin_demands.get(sources[orig]);
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
it.next(); // Needed to empty the iterator
for (int k = 0; k < T; k++) {
double derivative_term = 0;
/*
* If the demand is null, the cost function is independent of all the
* split ratios
*/
if (origin_demands[k] != 0) {
sum_of_split_ratios = state.sum_of_split_ratios[orig][k];
assert sum_of_split_ratios > 1 : "The sum of the split ratios ("
+ sum_of_split_ratios + ") should be >= 1";
derivative_term = epsilon / (1 - sum_of_split_ratios);
assert Numerical.validNumber(derivative_term);
result.set(k * temporal_control_block_size
+ index_in_control, derivative_term);
}
}
index_in_control++;
}
}
return result;
}
/**
* @brief Computes the dJ/dX matrix
* @details All terms are zero except the ones which are partial derivative in
* a partial density
*/
@Override
public SparseDoubleMatrix1D djdx(State state, double[] control) {
SparseDoubleMatrix1D result = new SparseDoubleMatrix1D(T * x_block_size);
/* We put 1 when we derivate along a partial density */
int block_position;
for (int k = 0; k < T; k++) {
block_position = k * x_block_size;
for (int partial_density_id = 0; partial_density_id < size_density_block; partial_density_id++) {
result.setQuick(block_position + partial_density_id, 1.0);
}
}
return result;
}
/**
* @brief Forward simulate after having loaded the external split ratios for
* compliant commodities
* @details For now we even put the null split ratios because we never clear
* the split ratios
*/
@Override
public State forwardSimulate(double[] control) {
return forwardSimulate(control, false);
}
public State forwardSimulate(double[] control, boolean debug) {
IntertemporalOriginsSplitRatios splits = simulator.splits;
int index_in_control = 0;
int commodity, coordinate;
double[][] sum_of_split_ratios = new double[O][T];
for (int orig = 0; orig < O; orig++) {
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
/*
* Mapping between splits.get(sources[orig], k).get(commodity) and
* U[k * C + index_in_control]
*/
coordinate = k * temporal_control_block_size + index_in_control;
splits.get(sources[orig], k).
put(commodity, control[coordinate] * alpha);
sum_of_split_ratios[orig][k] += control[coordinate];
}
index_in_control++;
}
}
State state = simulator.run(debug);
/* At the end we add the sum of the split ratios at the state */
state.sum_of_split_ratios = sum_of_split_ratios;
return state;
}
@Override
public double[] getStartingPoint() {
return getControl();
}
@Override
public double objective(double[] control) {
return objective(forwardSimulate(control), control);
}
/**
* @brief Computes the objective function:
* \sum_(i,c,k) \rho(i,c,k)
* - \sum_{origin o} epsilon2 * ln(\sum \rho(o,c,k) - 1)
* @details
* The condition \beta >= 0 is already put in the solver (in
* AdjointJVM/org.wsj/Optimizers.scala) do there is only one barrier
* in J
*/
public double objective(State state, double[] control) {
double objective = 0;
/*
* To compute the sum of the densities ON the network, we add the density of
* all the cells and then remove the density of the sinks
*/
for (int k = 0; k < T; k++) {
for (int cell_id = 0; cell_id < cells.length; cell_id++)
objective += state.profiles[k].getCell(cell_id).total_density;
for (int d = 0; d < destinations.length; d++)
objective -= state.profiles[k].getCell(destinations[d].getUniqueId()).total_density;
}
double[] origin_demands;
for (int orig = 0; orig < O; orig++) {
origin_demands = simulator.origin_demands.get(sources[orig]);
for (int k = 0; k < T; k++)
/* If the demand is null, there is no need to set up a barrier */
if (origin_demands[k] != 0) {
double diff = state.sum_of_split_ratios[orig][k] - 1;
// if (diff < 0) {
// System.out.println("Sum of the split ratio at one origin - 1 is "
// + diff + ". Should be > 0. Aborting.");
// assert false;
// }
objective -= epsilon * Math.log(diff);
// assert Numerical.validNumber(objective) :
// "Invalid objective function";
}
}
return objective;
}
public double totalTravelTime(State state, double[] control) {
double objective = 0;
/*
* To compute the sum of the densities ON the network, we add the density of
* all the cells and then remove the density of the sinks
*/
for (int k = 0; k < T; k++) {
for (int cell_id = 0; cell_id < cells.length; cell_id++)
objective += state.profiles[k].getCell(cell_id).total_density;
for (int d = 0; d < destinations.length; d++)
objective -= state.profiles[k].getCell(destinations[d].getUniqueId()).total_density;
}
return objective;
}
/**
* @brief Run the solver to find the optimal allocation of the compliant
* split-ratios
* @details It begins from a not physical initialized compliant split-ratios
* @return The control vector representing the compliant split-ratios
*/
public double[] solve() {
// The split ratios has been initialized in the constructor
/* solve is inherited by AdjointForJava<State> */
return optimize(getControl());
}
public void printProperties(State state) {
System.out.println("[Printing properties of the given state]");
System.out.println("Total split ratios at the origins through time steps:");
for (int o = 0; o < O; o++) {
System.out.print("[Origin " + o + "]");
for (int k = 0; k < T; k++)
System.out.print(" " + state.sum_of_split_ratios[o][k] + " ");
System.out.println();
}
}
public double getAlpha() {
return alpha;
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
private long averageTime(long begin, long end, int nb_cycles) {
return (end - begin);
}
public void profileComputationTime() {
long startTime;
long endTime;
double[] control = getControl();
int nb_iterations = 1000;
System.out.print("Time for " + nb_iterations
+ " iterations of forward simulate... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
forwardSimulate(control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
simulator.initializeSplitRatiosForOptimizer();
State state = forwardSimulate(getControl());
/* J */
System.out.print("Time for " + nb_iterations
+ " iterations of objective J... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
objective(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dH/dU */
System.out.print("Time for " + nb_iterations + " iterations of dhdu... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
dhdu(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dH/dX */
System.out.print("Time for " + nb_iterations + " iterations of dhdx... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
dhdx(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dJ/dX */
System.out.print("Time for " + nb_iterations + " iterations of djdx... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
djdx(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dJ/dU */
System.out.print("Time for " + nb_iterations + " iterations of djdu... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
djdu(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
}
}
|
src/dta_solver/SO_Optimizer.java
|
package dta_solver;
import io.InputOutput;
import java.util.Iterator;
import java.util.Map.Entry;
import generalLWRNetwork.Cell;
import generalLWRNetwork.Destination;
import generalLWRNetwork.Junction;
import generalLWRNetwork.Origin;
import generalNetwork.state.CellInfo;
import generalNetwork.state.JunctionInfo;
import generalNetwork.state.Profile;
import generalNetwork.state.State;
import generalNetwork.state.externalSplitRatios.IntertemporalOriginsSplitRatios;
import generalNetwork.state.internalSplitRatios.IntertemporalJunctionSplitRatios;
import generalNetwork.state.internalSplitRatios.IntertemporalSplitRatios;
import generalNetwork.state.internalSplitRatios.JunctionSplitRatios;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import cern.colt.matrix.tdouble.impl.SparseCCDoubleMatrix2D;
import cern.colt.matrix.tdouble.impl.SparseDoubleMatrix1D;
import cern.colt.matrix.tdouble.DoubleFactory1D;
import dataStructures.Numerical;
import dataStructures.Triplet;
import dta_solver.adjointMethod.Adjoint;
public class SO_Optimizer extends Adjoint<State> {
private Simulator simulator;
private double epsilon = 0.001;
/* Share of the compliant commodities */
private double alpha;
/* Total number of time steps */
private int T;
/* Number of compliant commodities */
private int C;
private Cell[] cells;
private Junction[] junctions;
private Origin[] sources;
private Destination[] destinations;
/* Number of origins */
private int O;
/* Number of destinations */
private int S;
/* Control Vector U */
/* Total size of a block for one time step of the control */
private int temporal_control_block_size;
/* State Vector X */
/* Size of a block describing all the densities for a given time step */
private int size_density_block;
/* Size of a block describing all the supply/demand at one time step */
private int size_demand_suply_block;
/* Size of the block describing all the Aggregate SR at one time sate */
private int size_aggregate_split_ratios;
/* Size of a block describing out-flows */
private int size_f_out_block;
/* Total size of the description of a profile for a given time step */
private int x_block_size;
private int demand_supply_position;
private int aggregate_split_ratios_position;
private int f_out_position;
private int f_in_position;
/* Constraints Vector H */
/* Size of a block describing the Mass Conversation constraints */
// size_density_block;
/* Size of a block describing the Flow Propagation constraints */
private int flow_propagation_size;
/* Size of the block describing the Aggregate SR constraints */
// size_aggregate_split_ratios;
/* Size of the block describing the out-flows constraints : */
// mass_conservation_size
/* Size of the block describing the in-flows constraints : */
// mass_conservation_size
/* Total size of a block of constraints for a given time step */
// x_block_size
public SO_Optimizer(int maxIter, Simulator simu) {
super(maxIter);
simulator = simu;
alpha = simu.getAlpha();
T = simulator.time_discretization.getNb_steps();
C = simulator.lwr_network.getNb_compliantCommodities();
cells = simulator.lwr_network.getCells();
sources = simulator.lwr_network.getSources();
O = sources.length;
destinations = simulator.lwr_network.getSinks();
S = destinations.length;
junctions = simulator.lwr_network.getJunctions();
/* For every time steps there are C compliant flows, and O non compliant */
temporal_control_block_size = C;
/* State Vector X */
/* Size of a block describing all the densities for a given time step */
size_density_block = cells.length * (C + 1);
/* Size of a block describing all the supply/demand at one time step */
size_demand_suply_block = 2 * cells.length;
/* Size of the block describing all the Aggregate SR at one time sate */
Junction junction;
int tmp_nb_aggregate_split_ratios = 0;
for (int j = 0; j < junctions.length; j++) {
junction = junctions[j];
tmp_nb_aggregate_split_ratios +=
junction.getPrev().length * junction.getNext().length;
}
size_aggregate_split_ratios = tmp_nb_aggregate_split_ratios;
/* Size of a block describing out-flows or in-flows */
size_f_out_block = size_density_block;
/* Total size of the description of a profile for a given time step */
x_block_size = (3 * (C + 1) + 2) * cells.length
+ size_aggregate_split_ratios;
demand_supply_position = size_density_block;
aggregate_split_ratios_position =
demand_supply_position + size_demand_suply_block;
f_out_position =
aggregate_split_ratios_position + size_aggregate_split_ratios;
f_in_position = f_out_position + size_f_out_block;
/* Constraints Vector H */
/* Size of a block describing the Mass Conversation constraints */
// size_density_block;
/* Size of a block describing the Flow Propagation constraints */
flow_propagation_size = size_demand_suply_block;
/* Size of the block describing the Aggregate SR constraints */
// size_aggregate_split_ratios;
/* Size of the block describing the out-flows constraints : */
// mass_conservation_size
/* Size of the block describing the in-flows constraints : */
// mass_conservation_size
/* Total size of a block of constraints for a given time step */
int H_block_size = 3 * size_density_block + flow_propagation_size
+ size_aggregate_split_ratios;
assert (H_block_size == x_block_size);
/* Initialization of the split ratios for the Optimizer */
simulator.initializeSplitRatiosForOptimizer();
}
public void printSizes() {
System.out.println("Total size of X: " + T * x_block_size);
System.out.println("Details: \n" +
"- time steps: " + T + "\n" +
"- density_block: " + size_density_block +
" : (1 NC + " + C + "compliant commodities )* " + cells.length
+ " cells\n" +
"- demand_supply: " + size_demand_suply_block +
" : 2 (for demand, supply) * " + cells.length + " cells)\n" +
"- aggregate SR: " + size_aggregate_split_ratios +
"(is the sum of the in.size() * out.size() at all junctions\n" +
"- f_in: " + size_density_block +
" : (same as the density block)\n" +
"- f_ out: " + size_density_block +
" : (same as the density block)");
System.out.println("Total size of H: " + T * x_block_size);
System.out.println("Details: " + T + " time steps, " +
"(Mass Cons: " + size_density_block +
", Flow prog: " + flow_propagation_size +
", aggregate SR: " + size_aggregate_split_ratios +
", f_in and out: " + 2 * size_density_block);
}
/**
* @brief Return the 1x(C*T) matrix representing the control where
* C is the number of compliant commodities
* @details There are T blocks of size C. The i-th block contains the
* controls at time step i.
*/
public double[] getControl() {
assert alpha != 0 : "The share of the compliant commodities is zero. No optimization possible";
IntertemporalOriginsSplitRatios splits = simulator.splits;
/* For every time steps there are C compliant flows */
double[] control = new double[T * temporal_control_block_size];
int index_in_control = 0;
int commodity;
Double split_ratio;
for (int orig = 0; orig < O; orig++) {
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
/*
* Mapping between splits.get(sources[orig], k).get(commodity) and
* U[k*(C + sources.length) + index_in_control]
*/
split_ratio = splits.get(sources[orig], k).get(commodity);
if (split_ratio != null)
// The sum of the split ratios at the control should be equal to 1
// for a given origin
control[k * temporal_control_block_size + index_in_control] = split_ratio
/ alpha;
}
index_in_control++;
}
}
return control;
}
/**
* @brief Return the 1x(C+O)*T= matrix representing the compliant and
* non-compliant commodities where C is the number of compliant
* commodities and 0 the number of origins
* @details There are T blocks of size (C+O). The i-th block contains the
* controls at time step i.
*/
private double[] getFullControl() {
IntertemporalOriginsSplitRatios splits = simulator.splits;
/* For every time steps there are C compliant flows, and O non compliant */
double[] control = new double[T * (C + 1)];
int index_in_control = 0;
int commodity;
Double split_ratio;
for (int orig = 0; orig < O; orig++) {
for (int k = 0; k < T; k++) {
split_ratio = splits.get(sources[orig], k).get(0);
if (split_ratio != null) {
control[k * temporal_control_block_size + index_in_control] = split_ratio;
}
}
index_in_control++;
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
split_ratio = splits.get(sources[orig], k).get(commodity);
if (split_ratio != null) {
control[k * temporal_control_block_size + index_in_control] = split_ratio
* alpha;
}
}
index_in_control++;
}
}
return control;
}
public void printFullControl() {
InputOutput.printControl(getFullControl(), C + 1);
}
private void parseStateVector(Profile p) {
int block_id, sub_block_id;
int commodity;
int index_in_state = 0;
double value;
CellInfo cell_info;
for (int k = 0; k < T; k++) {
/* Id of the first data of time step k */
block_id = k * x_block_size;
for (int cell_id = 0; cell_id < cells.length; cell_id++) {
cell_info = p.getCell(cells[cell_id]);
/* Id of the first index containing data from cells[cell_id] */
sub_block_id = block_id + cell_id * C;
// Operations on densities
Iterator<Entry<Integer, Double>> it =
cell_info.partial_densities.entrySet().iterator();
Entry<Integer, Double> entry;
while (it.hasNext()) {
entry = it.next();
commodity = entry.getKey();
// density (cell_id, commodity)(k)
index_in_state = sub_block_id + commodity;
value = entry.getValue();
}
// Operations on demand and supply
index_in_state = sub_block_id + size_density_block;
value = cell_info.demand;
index_in_state++;
value = cell_info.supply;
// Operations on aggregate split ratios
index_in_state += size_demand_suply_block;
JunctionInfo junction_info;
Junction junction;
for (int j = 0; j < junctions.length; j++) {
junction = junctions[j];
junction_info = p.getJunction(j);
for (int in = 0; in < junction.getPrev().length; in++) {
for (int out = 0; out < junction.getNext().length; out++) {
// Mapping between junctions_info.get(new PairCell(in, out));
index_in_state++;
}
}
}
// Operation on out-flows
sub_block_id += size_aggregate_split_ratios;
it = cell_info.out_flows.entrySet().iterator();
while (it.hasNext()) {
entry = it.next();
commodity = entry.getKey();
// flow_out (cell_id, commodity)(k)
index_in_state = sub_block_id + commodity;
value = entry.getValue();
}
// Operations on in-flows
index_in_state += size_f_out_block;
it = cell_info.in_flows.entrySet().iterator();
while (it.hasNext()) {
entry = it.next();
commodity = entry.getKey();
// flow_in (cell_id, commodity)(k)
index_in_state = sub_block_id + commodity;
value = entry.getValue();
}
}
}
}
/**
* @brief Computes the dH/dU matrix.
* @details
*/
@Override
public SparseCCDoubleMatrix2D dhdu(State state, double[] control) {
SparseCCDoubleMatrix2D result = new SparseCCDoubleMatrix2D(
x_block_size * T,
temporal_control_block_size * T);
int i, j, index_in_control = 0;
int commodity;
double[] origin_demands;
for (int orig = 0; orig < O; orig++) {
origin_demands = simulator.origin_demands.get(sources[orig]);
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
i = k * x_block_size + sources[orig].getUniqueId() * (C + 1)
+ commodity;
j = k * temporal_control_block_size + index_in_control;
result.setQuick(i, j, origin_demands[k] * alpha);
}
index_in_control++;
}
}
return result;
}
@Override
public SparseCCDoubleMatrix2D dhdx(State state, double[] control) {
IntertemporalSplitRatios internal_SR =
simulator.lwr_network.getInternal_split_ratios();
SparseCCDoubleMatrix2D result = new SparseCCDoubleMatrix2D(
x_block_size * T,
x_block_size * T);
double delta_t = simulator.time_discretization.getDelta_t();
/* The diagonal terms are done at the end */
/*********************************************************
* Derivative terms for the Mass Conservation constraints
*********************************************************/
// System.out.print("Mass conservation : ");
// long startTime = System.currentTimeMillis();
// Position of a block of constraints in H indexed by k
int block_upper_position;
// Position of a block in the Mass Conservation block indexed by the cell_id
int sub_block_position;
double delta_t_over_l;
int i, j;
for (int k = 1; k < T; k++) {
block_upper_position = k * x_block_size;
for (int cell_id = 0; cell_id < cells.length; cell_id++) {
sub_block_position = (C + 1) * cell_id;
for (int c = 0; c < C + 1; c++) {
// Line of interest in the H matrix
i = block_upper_position + sub_block_position + c;
// Column of interest in the H matrix
j = x_block_size * (k - 1) + sub_block_position + c;
/*
* We put 1 for the derivative terms of the mass conversation
* equations (i,c,k) with respect to density(i,c,k-1) for k \in [1, T]
*/
result.setQuick(i, j, 1.0);
/*
* Derivative terms with respect to flow-out(i,c,k-1) and
* flow-in(i,c,k-1)
*/
delta_t_over_l = delta_t /
simulator.lwr_network.getCell(cell_id).getLength();
assert Numerical.validNumber(delta_t_over_l);
// d \density(i, k) / d f_out(i,k-1) = - delta_t / l
result.setQuick(i, j + f_out_position, -delta_t_over_l);
// d \density(i, k) / d f_in(i,k-1) = delta_t / l
result.setQuick(i, j + f_in_position, delta_t_over_l);
}
}
// For the buffers and sinks we have put a derivative term that should
// have been zero
for (int o = 0; o < O; o++) {
for (int c = 0; c < C + 1; c++) {
i = block_upper_position + (C + 1) * sources[o].getUniqueId() + c;
j = x_block_size * (k - 1) + (C + 1) * sources[o].getUniqueId() + c;
// flow-in
result.setQuick(i, j + f_in_position, 0.0);
}
}
for (int s = 0; s < S; s++) {
for (int c = 0; c < C + 1; c++) {
i = block_upper_position + (C + 1) * destinations[s].getUniqueId()
+ c;
j = x_block_size * (k - 1) + (C + 1) * destinations[s].getUniqueId()
+ c;
// flow-out
result.setQuick(i, j + f_out_position, 0.0);
}
}
}
// long endTime = System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the Flow propagation (demand/supply)
*********************************************************/
// System.out.print("Flow propagation: ");
// startTime= System.currentTimeMillis();
double total_density;
for (int k = 0; k < T; k++) {
// Position of the first constraint in H dealing with supply/demand at
// time step k
block_upper_position = k * x_block_size + demand_supply_position;
for (int cell_id = 0; cell_id < cells.length; cell_id++) {
sub_block_position = cell_id * 2;
i = block_upper_position + sub_block_position;
total_density = state.profiles[k].getCell(cell_id).total_density;
for (int c = 0; c < C + 1; c++) {
// Demand first
result.setQuick(i,
x_block_size * k + cell_id * (C + 1) + c,
cells[cell_id].getDerivativeDemand(total_density, delta_t));
// Then supply
result.setQuick(i + 1,
x_block_size * k + cell_id * (C + 1) + c,
cells[cell_id].getDerivativeSupply(total_density));
}
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the Aggregate Split Ratios
*********************************************************/
// System.out.print("Aggregate SR: ");
// startTime= System.currentTimeMillis();
/*
* This part is not efficient because we have to do
* Nb_Aggregate_SR * T * (C+1) computation of derivative terms
*/
Junction junction;
/* Used to know the position of the current SR under study */
int aggregate_SR_index = 0;
Double partial_density;
/* Used to store beta(i,j,c)(k) */
Double i_j_c_SR;
/* Store the split ratios at a junction. Is null when Nx1 junction */
JunctionSplitRatios junction_SR;
CellInfo in_cell_info;
int prev_length, next_length;
for (int j_id = 0; j_id < junctions.length; j_id++) {
junction = junctions[j_id];
IntertemporalJunctionSplitRatios intert_junction_SR =
internal_SR.get(j_id);
prev_length = junction.getPrev().length;
for (int in = 0; in < prev_length; in++) {
Cell in_cell = junction.getPrev()[in];
next_length = junction.getNext().length;
for (int out = 0; out < next_length; out++) {
Cell out_cell = junction.getNext()[out];
for (int k = 0; k < T; k++) {
/* Here we study beta(in, out) (k) */
block_upper_position = k * x_block_size
+ aggregate_split_ratios_position;
/*
* There are no inter-temporal split ratios for Nx1 junctions.
* More precisely for all i \in Incoming link and j the unique
* outgoing link
* we have all the split ratio from i to j that is 1 and constant
*/
if (intert_junction_SR == null)
junction_SR = null;
else {
junction_SR = intert_junction_SR.get(k);
assert junction_SR != null;
}
in_cell_info = state.profiles[k].getCell(in_cell);
i = block_upper_position + aggregate_SR_index;
j = k * x_block_size + (C + 1) * in_cell.getUniqueId();
for (int c = 0; c < C + 1; c++) {
/*
* If there are no intertemporal_split ratios this means we are at
* a Nx1 junction and we always have beta = 1. However for the 1x1
* junction, the aggregate spit ratio has absolutely no influence
* on the flows and we can do without computing it
* TODO: Optimization possible
*/
if (junction_SR == null) {
if (prev_length == 1 && next_length == 1)
continue;
i_j_c_SR = 1.0;
} else
i_j_c_SR = junction_SR.get(in_cell.getUniqueId(),
out_cell.getUniqueId(), c);
/*
* If the split ratio for this commodity is zero, then the
* aggregate split ratio is independent of this split ratio
*/
// if (i_j_c_SR == null || i_j_c_SR == 0)
// continue;
if (i_j_c_SR == null) {
continue;
// i_j_c_SR = 0.0;
}
partial_density = in_cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
total_density = in_cell_info.total_density;
if (total_density != 0) {
double derivative_term = i_j_c_SR
* (total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(derivative_term);
if (derivative_term != 0)
result.setQuick(i, j + c, derivative_term);
}
}
}
aggregate_SR_index++;
}
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the out-flows
*********************************************************/
// System.out.print("Out-flows: ");
// startTime= System.currentTimeMillis();
int nb_prev, nb_next;
double value;
for (int j_id = 0; j_id < junctions.length; j_id++) {
junction = junctions[j_id];
nb_prev = junction.getPrev().length;
nb_next = junction.getNext().length;
// Derivative terms for 1x1 junctions
if (nb_prev == 1 && nb_next == 1) {
double demand, supply, f_out;
CellInfo cell_info;
int prev_id = junction.getPrev()[0].getUniqueId();
int next_id = junction.getNext()[0].getUniqueId();
for (int k = 0; k < T; k++) {
cell_info = state.profiles[k].getCell(prev_id);
total_density = cell_info.total_density;
if (total_density == 0)
continue;
demand = cell_info.demand;
supply = state.profiles[k].getCell(next_id).supply;
f_out = Math.min(demand, supply);
for (int c = 0; c < C + 1; c++) {
partial_density = cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
i = x_block_size * k + f_out_position + (C + 1) * prev_id + c;
/*
* Derivative terms with respect to the partial densities.
* There are 3 cases but the use of f_out = min (supply,demand)
* makes a factorization possible
*/
j = x_block_size * k + (C + 1) * prev_id + c;
value = f_out * (total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
/* Derivative terms with respect to supply/demand */
if (partial_density == 0)
continue;
if (demand < supply) {
j = x_block_size * k + demand_supply_position + 2 * prev_id;
} else if (supply < demand) {
j = x_block_size * k + demand_supply_position + 2 * prev_id + 1;
}
value = partial_density / total_density;
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
}
}
// Derivative terms for 1x2 junctions
} else if (nb_prev == 2 && nb_next == 1) {
int in_1 = junction.getPrev()[0].getUniqueId();
int in_2 = junction.getPrev()[1].getUniqueId();
int out = junction.getNext()[0].getUniqueId();
double P1 = junction.getPriority(in_1);
double P2 = junction.getPriority(in_2);
double demand1, demand2, supply, f_in;
for (int k = 0; k < T; k++) {
demand1 = state.profiles[k].getCell(in_1).demand;
demand2 = state.profiles[k].getCell(in_2).demand;
supply = state.profiles[k].getCell(out).supply;
f_in = Math.min(demand1 + demand2, supply);
double total_density1 = state.profiles[k].getCell(in_1).total_density;
double total_density2 = state.profiles[k].getCell(in_2).total_density;
for (int c = 0; c < C + 1; c++) {
double Df_inDdemand1 = 0, Df_inDdemand2 = 0, Df_inDsupply = 0;
if (demand1 + demand2 < supply) {
Df_inDdemand1 = 1;
Df_inDdemand2 = 1;
}
if (supply < demand1 + demand2) {
Df_inDsupply = 1;
}
/* For the first incoming road in_1 */
/* Derivative terms with respect to the partial densities */
partial_density = state.profiles[k].getCell(in_1).partial_densities
.get(c);
if (partial_density == null)
partial_density = 0.0;
if (total_density1 != 0) {
double f_in_1_out;
double DfDdemand1 = 0, DfDdemand2 = 0, DfDsupply = 0;
if (P1 * (f_in - demand1) > P2 * demand1) {
f_in_1_out = demand1;
DfDdemand1 = 1;
} else if (P1 * demand2 < P2 * (f_in - demand2)) {
f_in_1_out = f_in - demand2;
DfDdemand1 = Df_inDdemand1;
DfDdemand2 = Df_inDdemand2 - 1;
DfDsupply = Df_inDsupply;
} else {
f_in_1_out = P1 * f_in;
DfDdemand1 = P1 * Df_inDdemand1;
DfDdemand2 = P1 * Df_inDdemand2;
DfDsupply = P1 * Df_inDsupply;
}
i = x_block_size * k + size_density_block
+ flow_propagation_size + size_aggregate_split_ratios + in_1
* (C + 1) + c;
j = x_block_size * k + in_1 * (C + 1) + c;
value = f_in_1_out * (total_density1 - partial_density)
/ (total_density1 * total_density1);
result.setQuick(i, j, value);
/* Derivative terms with respect to supply/demand */
if (partial_density != 0) {
if (DfDdemand1 != 0) {
j = x_block_size * k + size_demand_suply_block + in_1 * 2;
assert Numerical.validNumber(DfDdemand1);
result.setQuick(i, j, DfDdemand1);
}
if (DfDdemand2 != 0) {
j = x_block_size * k + size_demand_suply_block + in_2 * 2;
assert Numerical.validNumber(DfDdemand2);
result.setQuick(i, j, DfDdemand2);
}
if (DfDsupply != 0) {
j = x_block_size * k + size_demand_suply_block + out * 2 + 1;
assert Numerical.validNumber(DfDsupply);
result.setQuick(i, j, DfDsupply);
}
}
}
/* For the second incoming road in_2 */
/* Derivative terms with respect to the partial densities */
partial_density = state.profiles[k].getCell(in_2).partial_densities
.get(c);
if (partial_density == null)
partial_density = 0.0;
if (total_density2 != 0) {
double f_in_2_out;
double DfDdemand1 = 0, DfDdemand2 = 0, DfDsupply = 0;
if (P2 * (f_in - demand2) > P1 * demand2) {
f_in_2_out = demand1;
DfDdemand2 = 1;
} else if (P2 * demand2 < P1 * (f_in - demand1)) {
f_in_2_out = f_in - demand1;
DfDdemand2 = Df_inDdemand2;
DfDdemand1 = Df_inDdemand1 - 1;
DfDsupply = Df_inDsupply;
} else {
f_in_2_out = P2 * f_in;
DfDdemand2 = P2 * Df_inDdemand2;
DfDdemand1 = P2 * Df_inDdemand1;
DfDsupply = P2 * Df_inDsupply;
}
i = x_block_size * k + size_density_block
+ flow_propagation_size + size_aggregate_split_ratios + in_2
* (C + 1) + c;
j = x_block_size * k + in_2 * (C + 1) + c;
value = f_in_2_out * (total_density2 - partial_density)
/ (total_density2 * total_density2);
result.setQuick(i, j, value);
/* Derivative terms with respect to supply/demand */
if (partial_density != 0) {
if (DfDdemand1 != 0) {
j = x_block_size * k + size_demand_suply_block + in_1 * 2;
assert Numerical.validNumber(DfDdemand1);
result.setQuick(i, j, DfDdemand1);
}
if (DfDdemand2 != 0) {
j = x_block_size * k + size_demand_suply_block + in_2 * 2;
assert Numerical.validNumber(DfDdemand2);
result.setQuick(i, j, DfDdemand2);
}
if (DfDsupply != 0) {
j = x_block_size * k + size_demand_suply_block + out * 2 + 1;
assert Numerical.validNumber(DfDsupply);
result.setQuick(i, j, DfDsupply);
}
}
}
}
}
// Derivative terms for 1xN junctions
} else if (nb_prev == 1) {
CellInfo cell_info;
for (int k = 0; k < T; k++) {
int in_id = junction.getPrev()[0].getUniqueId();
cell_info = state.profiles[k].getCell(in_id);
Cell[] next_cells = junction.getNext();
total_density = cell_info.total_density;
double demand = cell_info.demand;
if (total_density != 0) {
/*
* We find j such that f_(in_id)_out = min (supply_j /
* \beta_(in_id)_j)
*/
double minimum = Double.MAX_VALUE;
int minimum_id_cell = 0;
double min_supply = -1, supply, beta_at_minimum = 0;
Double beta;
for (int out = 0; out < next_cells.length; out++) {
beta = state.profiles[k]
.getJunction(junction)
.getAggregateSR(in_id, next_cells[out].getUniqueId());
if (beta == null)
beta = 0.0;
if (beta != 0) {
supply = state.profiles[k].getCell(next_cells[out]).supply;
if (supply / beta < minimum) {
min_supply = supply / beta;
minimum_id_cell = next_cells[out].getUniqueId();
beta_at_minimum = beta;
}
}
}
assert min_supply != -1;
double flow_out;
Double tmp;
if (demand < min_supply) {
flow_out = demand;
/* Derivative with respect to partial densities */
for (int c = 0; c < C + 1; c++) {
partial_density = cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
i = x_block_size * k + size_density_block
+ flow_propagation_size + size_aggregate_split_ratios
+ in_id * (C + 1) + c;
j = x_block_size * k + minimum_id_cell * (C + 1) + c;
tmp = internal_SR.get(k, j_id).get(in_id, minimum_id_cell, c);
if (tmp != null && tmp != 0) {
value = tmp
* flow_out *
(total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
/* Derivative with respect to supply and demand */
j = x_block_size * k + size_demand_suply_block + in_id * 2;
value = tmp
* partial_density / total_density;
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
}
}
} else if (min_supply < demand) {
flow_out = min_supply;
/* Derivative with respect to partial densities */
for (int c = 0; c < C + 1; c++) {
partial_density = cell_info.partial_densities.get(c);
if (partial_density == null)
partial_density = 0.0;
i = x_block_size * k + size_density_block
+ flow_propagation_size + size_aggregate_split_ratios
+ in_id * (C + 1) + c;
j = x_block_size * k + minimum_id_cell * (C + 1) + c;
tmp = internal_SR.get(k, j_id).get(in_id, minimum_id_cell, c);
if (tmp != null && tmp != 0) {
value = tmp
* flow_out *
(total_density - partial_density)
/ (total_density * total_density);
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
/* Derivative with respect to supply and demand */
j = x_block_size * k + size_demand_suply_block
+ minimum_id_cell * 2 + 1;
value = tmp
* partial_density / total_density / beta_at_minimum;
assert Numerical.validNumber(value);
result.setQuick(i, j, value);
}
}
}
}
}
} else {
assert false : "[dhdx] Only 1x1, 1x2, and Nx1 junctions are possible";
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
/*********************************************************
* Derivative terms for the in-flows
*********************************************************/
// System.out.print("In-flows: ");
// startTime= System.currentTimeMillis();
int commodity, in_id, out_id;
for (int j_id = 0; j_id < junctions.length; j_id++) {
for (int k = 0; k < T; k++) {
junction_SR = internal_SR.get(k, j_id);
/* If there is no split ratios, it means it is a Nx1 junction */
if (junction_SR == null) {
for (in_id = junctions[j_id].getPrev()[0].getUniqueId(); in_id < junctions[j_id]
.getPrev().length; in_id++) {
// We don't know the split ratios so we suppose it is 1 for all
assert junctions[j_id].getNext().length <= 1;
for (int c = 0; c < C + 1; c++) {
i = x_block_size * k + 2 * size_density_block
+ flow_propagation_size + aggregate_SR_index
+ junctions[j_id].getNext()[0].getUniqueId() * (C + 1)
+ c;
j = x_block_size * k + f_out_position + in_id * (C + 1) + c;
result.setQuick(i, j, 1.0);
}
}
} else {
Iterator<Entry<Triplet, Double>> iterator =
junction_SR.non_compliant_split_ratios
.entrySet()
.iterator();
Entry<Triplet, Double> entry;
while (iterator.hasNext()) {
entry = iterator.next();
in_id = entry.getKey().incoming;
out_id = entry.getKey().outgoing;
commodity = entry.getKey().commodity;
i = x_block_size * k + 2 * size_density_block
+ flow_propagation_size + aggregate_SR_index + out_id * (C + 1)
+ commodity;
j = x_block_size * k + f_out_position + in_id * (C + 1) + commodity;
assert Numerical.validNumber(entry.getValue());
result.setQuick(i, j, entry.getValue());
}
}
}
}
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
// System.out.print("Diagonal terms: ");
// startTime= System.currentTimeMillis();
for (int index = 0; index < x_block_size * T; index++)
result.setQuick(index, index, -1.0);
// endTime= System.currentTimeMillis();
// System.out.println(endTime - startTime);
return result;
}
/**
* @brief Computes the derivative dJ/dU
* @details
* The condition \beta >= 0 is already put in the solver (in
* AdjointJVM/org.wsj/Optimizers.scala) do there is only one barrier
* in J
*/
@Override
public DoubleMatrix1D djdu(State state, double[] control) {
DoubleMatrix1D result =
DoubleFactory1D.dense.make(T * temporal_control_block_size);
int index_in_control = 0;
double sum_of_split_ratios;
double[] origin_demands;
for (int orig = 0; orig < O; orig++) {
origin_demands = simulator.origin_demands.get(sources[orig]);
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
it.next(); // Needed to empty the iterator
for (int k = 0; k < T; k++) {
double derivative_term = 0;
/*
* If the demand is null, the cost function is independent of all the
* split ratios
*/
if (origin_demands[k] != 0) {
sum_of_split_ratios = state.sum_of_split_ratios[orig][k];
assert sum_of_split_ratios > 1 : "The sum of the split ratios ("
+ sum_of_split_ratios + ") should be >= 1";
derivative_term = epsilon / (1 - sum_of_split_ratios);
assert Numerical.validNumber(derivative_term);
result.set(k * temporal_control_block_size
+ index_in_control, derivative_term);
}
}
index_in_control++;
}
}
return result;
}
/**
* @brief Computes the dJ/dX matrix
* @details All terms are zero except the ones which are partial derivative in
* a partial density
*/
@Override
public SparseDoubleMatrix1D djdx(State state, double[] control) {
SparseDoubleMatrix1D result = new SparseDoubleMatrix1D(T * x_block_size);
/* We put 1 when we derivate along a partial density */
int block_position;
for (int k = 0; k < T; k++) {
block_position = k * x_block_size;
for (int partial_density_id = 0; partial_density_id < size_density_block; partial_density_id++) {
result.setQuick(block_position + partial_density_id, 1.0);
}
}
return result;
}
/**
* @brief Forward simulate after having loaded the external split ratios for
* compliant commodities
* @details For now we even put the null split ratios because we never clear
* the split ratios
*/
@Override
public State forwardSimulate(double[] control) {
return forwardSimulate(control, false);
}
public State forwardSimulate(double[] control, boolean debug) {
IntertemporalOriginsSplitRatios splits = simulator.splits;
int index_in_control = 0;
int commodity, coordinate;
double[][] sum_of_split_ratios = new double[O][T];
for (int orig = 0; orig < O; orig++) {
Iterator<Integer> it = sources[orig]
.getCompliant_commodities()
.iterator();
while (it.hasNext()) {
commodity = it.next();
for (int k = 0; k < T; k++) {
/*
* Mapping between splits.get(sources[orig], k).get(commodity) and
* U[k * C + index_in_control]
*/
coordinate = k * temporal_control_block_size + index_in_control;
splits.get(sources[orig], k).
put(commodity, control[coordinate] * alpha);
sum_of_split_ratios[orig][k] += control[coordinate];
}
index_in_control++;
}
}
State state = simulator.run(debug);
/* At the end we add the sum of the split ratios at the state */
state.sum_of_split_ratios = sum_of_split_ratios;
return state;
}
@Override
public double[] getStartingPoint() {
return getControl();
}
@Override
public double objective(double[] control) {
return objective(forwardSimulate(control), control);
}
/**
* @brief Computes the objective function:
* \sum_(i,c,k) \rho(i,c,k)
* - \sum_{origin o} epsilon2 * ln(\sum \rho(o,c,k) - 1)
* @details
* The condition \beta >= 0 is already put in the solver (in
* AdjointJVM/org.wsj/Optimizers.scala) do there is only one barrier
* in J
*/
public double objective(State state, double[] control) {
double objective = 0;
/*
* To compute the sum of the densities ON the network, we add the density of
* all the cells and then remove the density of the sinks
*/
for (int k = 0; k < T; k++) {
for (int cell_id = 0; cell_id < cells.length; cell_id++)
objective += state.profiles[k].getCell(cell_id).total_density;
for (int d = 0; d < destinations.length; d++)
objective -= state.profiles[k].getCell(destinations[d].getUniqueId()).total_density;
}
double[] origin_demands;
for (int orig = 0; orig < O; orig++) {
origin_demands = simulator.origin_demands.get(sources[orig]);
for (int k = 0; k < T; k++)
/* If the demand is null, there is no need to set up a barrier */
if (origin_demands[k] != 0) {
double diff = state.sum_of_split_ratios[orig][k] - 1;
// if (diff < 0) {
// System.out.println("Sum of the split ratio at one origin - 1 is "
// + diff + ". Should be > 0. Aborting.");
// assert false;
// }
objective -= epsilon * Math.log(diff);
// assert Numerical.validNumber(objective) :
// "Invalid objective function";
}
}
return objective;
}
public double totalTravelTime(State state, double[] control) {
double objective = 0;
/*
* To compute the sum of the densities ON the network, we add the density of
* all the cells and then remove the density of the sinks
*/
for (int k = 0; k < T; k++) {
for (int cell_id = 0; cell_id < cells.length; cell_id++)
objective += state.profiles[k].getCell(cell_id).total_density;
for (int d = 0; d < destinations.length; d++)
objective -= state.profiles[k].getCell(destinations[d].getUniqueId()).total_density;
}
return objective;
}
/**
* @brief Run the solver to find the optimal allocation of the compliant
* split-ratios
* @details It begins from a not physical initialized compliant split-ratios
* @return The control vector representing the compliant split-ratios
*/
public double[] solve() {
// The split ratios has been initialized in the constructor
/* solve is inherited by AdjointForJava<State> */
return optimize(getControl());
}
public void printProperties(State state) {
System.out.println("[Printing properties of the given state]");
System.out.println("Total split ratios at the origins through time steps:");
for (int o = 0; o < O; o++) {
System.out.print("[Origin " + o + "]");
for (int k = 0; k < T; k++)
System.out.print(" " + state.sum_of_split_ratios[o][k] + " ");
System.out.println();
}
}
public double getAlpha() {
return alpha;
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
private long averageTime(long begin, long end, int nb_cycles) {
return (end - begin);
}
public void profileComputationTime() {
long startTime;
long endTime;
double[] control = getControl();
int nb_iterations = 1000;
System.out.print("Time for " + nb_iterations
+ " iterations of forward simulate... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
forwardSimulate(control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
simulator.initializeSplitRatiosForOptimizer();
State state = forwardSimulate(getControl());
/* J */
System.out.print("Time for " + nb_iterations
+ " iterations of objective J... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
objective(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dH/dU */
System.out.print("Time for " + nb_iterations + " iterations of dhdu... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
dhdu(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dH/dX */
System.out.print("Time for " + nb_iterations + " iterations of dhdx... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
dhdx(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dJ/dX */
System.out.print("Time for " + nb_iterations + " iterations of djdx... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
djdx(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
/* dJ/dU */
System.out.print("Time for " + nb_iterations + " iterations of djdu... ");
startTime = System.currentTimeMillis();
for (int i = 0; i < nb_iterations; i++) {
djdu(state, control);
}
endTime = System.currentTimeMillis();
System.out.println(averageTime(startTime, endTime, nb_iterations));
}
}
|
Some refactoring without influence on the output
|
src/dta_solver/SO_Optimizer.java
|
Some refactoring without influence on the output
|
<ide><path>rc/dta_solver/SO_Optimizer.java
<ide> " : 2 (for demand, supply) * " + cells.length + " cells)\n" +
<ide> "- aggregate SR: " + size_aggregate_split_ratios +
<ide> "(is the sum of the in.size() * out.size() at all junctions\n" +
<del> "- f_in: " + size_density_block +
<add> "- f_out: " + size_density_block +
<ide> " : (same as the density block)\n" +
<del> "- f_ out: " + size_density_block +
<add> "- f_ in: " + size_density_block +
<ide> " : (same as the density block)");
<ide>
<ide> System.out.println("Total size of H: " + T * x_block_size);
<ide> DfDsupply = P1 * Df_inDsupply;
<ide> }
<ide>
<del> i = x_block_size * k + size_density_block
<del> + flow_propagation_size + size_aggregate_split_ratios + in_1
<add> i = x_block_size * k + f_out_position + in_1
<ide> * (C + 1) + c;
<ide> j = x_block_size * k + in_1 * (C + 1) + c;
<ide>
<ide> /* Derivative terms with respect to supply/demand */
<ide> if (partial_density != 0) {
<ide> if (DfDdemand1 != 0) {
<del> j = x_block_size * k + size_demand_suply_block + in_1 * 2;
<add> j = x_block_size * k + demand_supply_position + in_1 * 2;
<ide> assert Numerical.validNumber(DfDdemand1);
<ide> result.setQuick(i, j, DfDdemand1);
<ide> }
<ide> if (DfDdemand2 != 0) {
<del> j = x_block_size * k + size_demand_suply_block + in_2 * 2;
<add> j = x_block_size * k + demand_supply_position + in_2 * 2;
<ide> assert Numerical.validNumber(DfDdemand2);
<ide> result.setQuick(i, j, DfDdemand2);
<ide> }
<ide> if (DfDsupply != 0) {
<del> j = x_block_size * k + size_demand_suply_block + out * 2 + 1;
<add> j = x_block_size * k + demand_supply_position + out * 2 + 1;
<ide> assert Numerical.validNumber(DfDsupply);
<ide> result.setQuick(i, j, DfDsupply);
<ide> }
<ide> DfDsupply = P2 * Df_inDsupply;
<ide> }
<ide>
<del> i = x_block_size * k + size_density_block
<del> + flow_propagation_size + size_aggregate_split_ratios + in_2
<add> i = x_block_size * k + f_out_position + in_2
<ide> * (C + 1) + c;
<ide> j = x_block_size * k + in_2 * (C + 1) + c;
<ide>
<ide> /* Derivative terms with respect to supply/demand */
<ide> if (partial_density != 0) {
<ide> if (DfDdemand1 != 0) {
<del> j = x_block_size * k + size_demand_suply_block + in_1 * 2;
<add> j = x_block_size * k + demand_supply_position + in_1 * 2;
<ide> assert Numerical.validNumber(DfDdemand1);
<ide> result.setQuick(i, j, DfDdemand1);
<ide> }
<ide> if (DfDdemand2 != 0) {
<del> j = x_block_size * k + size_demand_suply_block + in_2 * 2;
<add> j = x_block_size * k + demand_supply_position + in_2 * 2;
<ide> assert Numerical.validNumber(DfDdemand2);
<ide> result.setQuick(i, j, DfDdemand2);
<ide> }
<ide> if (DfDsupply != 0) {
<del> j = x_block_size * k + size_demand_suply_block + out * 2 + 1;
<add> j = x_block_size * k + demand_supply_position + out * 2 + 1;
<ide> assert Numerical.validNumber(DfDsupply);
<ide> result.setQuick(i, j, DfDsupply);
<ide> }
<ide> if (partial_density == null)
<ide> partial_density = 0.0;
<ide>
<del> i = x_block_size * k + size_density_block
<del> + flow_propagation_size + size_aggregate_split_ratios
<add> i = x_block_size * k + f_out_position
<ide> + in_id * (C + 1) + c;
<ide> j = x_block_size * k + minimum_id_cell * (C + 1) + c;
<ide>
<ide> result.setQuick(i, j, value);
<ide>
<ide> /* Derivative with respect to supply and demand */
<del> j = x_block_size * k + size_demand_suply_block + in_id * 2;
<add> j = x_block_size * k + demand_supply_position + in_id * 2;
<ide> value = tmp
<ide> * partial_density / total_density;
<ide> assert Numerical.validNumber(value);
<ide> if (partial_density == null)
<ide> partial_density = 0.0;
<ide>
<del> i = x_block_size * k + size_density_block
<del> + flow_propagation_size + size_aggregate_split_ratios
<add> i = x_block_size * k + f_out_position
<ide> + in_id * (C + 1) + c;
<ide> j = x_block_size * k + minimum_id_cell * (C + 1) + c;
<ide>
<ide> result.setQuick(i, j, value);
<ide>
<ide> /* Derivative with respect to supply and demand */
<del> j = x_block_size * k + size_demand_suply_block
<add> j = x_block_size * k + demand_supply_position
<ide> + minimum_id_cell * 2 + 1;
<ide> value = tmp
<ide> * partial_density / total_density / beta_at_minimum;
|
|
Java
|
bsd-2-clause
|
cbf07eff2097cf91415c6093ac102068ae9c82bb
| 0 |
jenkinsci/p4-plugin,jenkinsci/p4-plugin,jenkinsci/p4-plugin
|
package org.jenkinsci.plugins.p4;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.perforce.p4java.exception.P4JavaException;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Plugin;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixExecutionStrategy;
import hudson.matrix.MatrixProject;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.LogTaskListener;
import jenkins.model.Jenkins;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.multiplescms.MultiSCM;
import org.jenkinsci.plugins.p4.browsers.P4Browser;
import org.jenkinsci.plugins.p4.browsers.SwarmBrowser;
import org.jenkinsci.plugins.p4.build.ExecutorHelper;
import org.jenkinsci.plugins.p4.build.NodeHelper;
import org.jenkinsci.plugins.p4.build.P4EnvironmentContributor;
import org.jenkinsci.plugins.p4.changes.P4ChangeEntry;
import org.jenkinsci.plugins.p4.changes.P4ChangeParser;
import org.jenkinsci.plugins.p4.changes.P4ChangeRef;
import org.jenkinsci.plugins.p4.changes.P4ChangeSet;
import org.jenkinsci.plugins.p4.changes.P4GraphRef;
import org.jenkinsci.plugins.p4.changes.P4LabelRef;
import org.jenkinsci.plugins.p4.changes.P4Ref;
import org.jenkinsci.plugins.p4.client.ConnectionHelper;
import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials;
import org.jenkinsci.plugins.p4.credentials.P4CredentialsImpl;
import org.jenkinsci.plugins.p4.credentials.P4InvalidCredentialException;
import org.jenkinsci.plugins.p4.filters.Filter;
import org.jenkinsci.plugins.p4.filters.FilterPerChangeImpl;
import org.jenkinsci.plugins.p4.matrix.MatrixOptions;
import org.jenkinsci.plugins.p4.populate.Populate;
import org.jenkinsci.plugins.p4.review.P4Review;
import org.jenkinsci.plugins.p4.review.ReviewProp;
import org.jenkinsci.plugins.p4.scm.AbstractP4ScmSource;
import org.jenkinsci.plugins.p4.scm.P4Path;
import org.jenkinsci.plugins.p4.tagging.TagAction;
import org.jenkinsci.plugins.p4.tasks.CheckoutStatus;
import org.jenkinsci.plugins.p4.tasks.CheckoutTask;
import org.jenkinsci.plugins.p4.tasks.PollTask;
import org.jenkinsci.plugins.p4.tasks.RemoveClientTask;
import org.jenkinsci.plugins.p4.tasks.WhereTask;
import org.jenkinsci.plugins.p4.workspace.ManualWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.SpecWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StreamWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition;
import org.jenkinsci.plugins.workflow.flow.FlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PerforceScm extends SCM {
private static Logger logger = Logger.getLogger(PerforceScm.class.getName());
private final String credential;
private final Workspace workspace;
private final List<Filter> filter;
private final Populate populate;
private final P4Browser browser;
private final P4Ref revision;
private String script;
private transient TagAction tagAction = null;
private transient P4Ref parentChange;
private transient P4Review review;
public static final int DEFAULT_FILE_LIMIT = 50;
public static final int DEFAULT_CHANGE_LIMIT = 20;
public static final long DEFAULT_HEAD_LIMIT = 1000;
public String getCredential() {
return credential;
}
public Workspace getWorkspace() {
return workspace;
}
public List<Filter> getFilter() {
return filter;
}
public Populate getPopulate() {
return populate;
}
@Override
public P4Browser getBrowser() {
return browser;
}
public P4Review getReview() {
return review;
}
public void setReview(P4Review review) {
this.review = review;
}
/**
* Helper function for converting an SCM object into a
* PerforceScm object when appropriate.
*
* @param scm the SCM object
* @return a PerforceScm instance or null
*/
public static PerforceScm convertToPerforceScm(SCM scm) {
PerforceScm perforceScm = null;
if (scm instanceof PerforceScm) {
perforceScm = (PerforceScm) scm;
} else {
Jenkins jenkins = Jenkins.getInstance();
if (jenkins != null) {
Plugin multiSCMPlugin = jenkins.getPlugin("multiple-scms");
if (multiSCMPlugin != null) {
if (scm instanceof MultiSCM) {
MultiSCM multiSCM = (MultiSCM) scm;
for (SCM configuredSCM : multiSCM.getConfiguredSCMs()) {
if (configuredSCM instanceof PerforceScm) {
perforceScm = (PerforceScm) configuredSCM;
break;
}
}
}
}
}
}
return perforceScm;
}
/**
* Create a constructor that takes non-transient fields, and add the
* annotation @DataBoundConstructor to it. Using the annotation helps the
* Stapler class to find which constructor that should be used when
* automatically copying values from a web form to a class.
*
* @param credential Credential ID
* @param workspace Workspace connection details
* @param filter Polling filters
* @param populate Populate options
* @param browser Browser options
*/
@DataBoundConstructor
public PerforceScm(String credential, Workspace workspace, List<Filter> filter, Populate populate,
P4Browser browser) {
this.credential = credential;
this.workspace = workspace;
this.filter = filter;
this.populate = populate;
this.browser = browser;
this.revision = null;
}
/**
* MultiBranch constructor for building jobs.
*
* @param source ScmSource
* @param path Perforce project path and mappings
* @param revision Perforce revision
*/
public PerforceScm(AbstractP4ScmSource source, P4Path path, P4Ref revision) {
this.credential = source.getCredential();
this.workspace = source.getWorkspace(path);
this.filter = source.getFilter();
this.populate = source.getPopulate();
this.browser = source.getBrowser();
this.revision = revision;
this.script = source.getScriptPathOrDefault();
}
/**
* Internal constructor for functional tests.
*
* @param credential Credential ID
* @param workspace Workspace type
* @param populate Populate options
*/
public PerforceScm(String credential, Workspace workspace, Populate populate) {
this.credential = credential;
this.workspace = workspace;
this.filter = null;
this.populate = populate;
this.browser = null;
this.revision = null;
}
@Override
public String getKey() {
String delim = "-";
StringBuffer key = new StringBuffer("p4");
// add Credential
key.append(delim);
key.append(credential);
// add Mapping/Stream
key.append(delim);
if (workspace instanceof ManualWorkspaceImpl) {
ManualWorkspaceImpl ws = (ManualWorkspaceImpl) workspace;
key.append(ws.getSpec().getView());
key.append(ws.getSpec().getStreamName());
}
if (workspace instanceof StreamWorkspaceImpl) {
StreamWorkspaceImpl ws = (StreamWorkspaceImpl) workspace;
key.append(ws.getStreamName());
}
if (workspace instanceof SpecWorkspaceImpl) {
SpecWorkspaceImpl ws = (SpecWorkspaceImpl) workspace;
key.append(ws.getSpecPath());
}
if (workspace instanceof StaticWorkspaceImpl) {
StaticWorkspaceImpl ws = (StaticWorkspaceImpl) workspace;
key.append(ws.getName());
}
if (workspace instanceof TemplateWorkspaceImpl) {
TemplateWorkspaceImpl ws = (TemplateWorkspaceImpl) workspace;
key.append(ws.getTemplateName());
}
return key.toString();
}
public static P4Browser findBrowser(String scmCredential) {
// Retrieve item from request
StaplerRequest req = Stapler.getCurrentRequest();
Job job = req == null ? null : req.findAncestorObject(Job.class);
// If cannot retrieve item, check from root
P4BaseCredentials credentials = job == null
? ConnectionHelper.findCredential(scmCredential, Jenkins.getActiveInstance())
: ConnectionHelper.findCredential(scmCredential, job);
if (credentials == null) {
logger.fine("Could not retrieve credentials from id: '${scmCredential}");
return null;
}
try (ConnectionHelper p4 = new ConnectionHelper(credentials, null)) {
String url = p4.getSwarm();
if (url != null) {
return new SwarmBrowser(url);
} else {
return null;
}
} catch (IOException e) {
logger.severe("Connection error. " + e.getMessage());
} catch (P4JavaException e) {
logger.severe("Unable to access Swarm Property. " + e.getMessage());
} catch (Exception e) {
logger.severe("Perforce resource error. " + e.getMessage());
}
return null;
}
/**
* Calculate the state of the workspace of the given build. The returned
* object is then fed into compareRemoteRevisionWith as the baseline
* SCMRevisionState to determine if the build is necessary, and is added to
* the build as an Action for later retrieval.
*/
@Override
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> run, FilePath buildWorkspace, Launcher launcher,
TaskListener listener) throws IOException, InterruptedException {
// A baseline is not required... but a baseline object is, so we'll
// return the NONE object.
return SCMRevisionState.NONE;
}
/**
* This method does the actual polling and returns a PollingResult. The
* change attribute of the PollingResult the significance of the changes
* detected by this poll.
*/
@Override
public PollingResult compareRemoteRevisionWith(Job<?, ?> job, Launcher launcher, FilePath buildWorkspace,
TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException {
String jobName = job.getName();
logger.finer("P4: polling[" + jobName + "] started...");
PollingResult state = PollingResult.NO_CHANGES;
// Get last run and build workspace
Run<?, ?> lastRun = job.getLastBuild();
Queue.Item[] items = Jenkins.getInstance().getQueue().getItems();
for(Queue.Item item : items) {
if(item.task instanceof WorkflowJob) {
WorkflowJob task = (WorkflowJob) item.task;
if(task.equals(job)) {
if(item instanceof Queue.WaitingItem) {
logger.info("P4: polling[" + jobName + "] skipping WaitingItem");
return PollingResult.NO_CHANGES;
}
if(item instanceof Queue.BlockedItem) {
logger.finer("P4: polling[" + jobName + "] BlockedItem");
}
if(item instanceof Queue.BuildableItem) {
logger.finer("P4: polling[" + jobName + "] BuildableItem");
}
}
}
}
// Build workspace is often null as requiresWorkspaceForPolling() returns false as a checked out workspace is
// not needed, but we still need a client and artificial root for the view.
// JENKINS-46908
if (buildWorkspace == null) {
String defaultRoot = job.getRootDir().getAbsoluteFile().getAbsolutePath();
if (lastRun != null) {
EnvVars env = lastRun.getEnvironment(listener);
buildWorkspace = new FilePath(new File(env.get("WORKSPACE", defaultRoot)));
} else {
listener.getLogger().println("Warning Jenkins Workspace root not defined.");
return PollingResult.NO_CHANGES;
}
}
Node node = NodeHelper.workspaceToNode(buildWorkspace);
if (job instanceof MatrixProject) {
if (isBuildParent(job)) {
// Poll PARENT only
EnvVars envVars = job.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
} else {
// Poll CHILDREN only
MatrixProject matrixProj = (MatrixProject) job;
Collection<MatrixConfiguration> configs = matrixProj.getActiveConfigurations();
for (MatrixConfiguration config : configs) {
EnvVars envVars = config.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
// exit early if changes found
if (state == PollingResult.BUILD_NOW) {
logger.finer("P4: polling[" + jobName + "] exit (Matrix): " + state.change);
return state;
}
}
}
} else {
EnvVars envVars = job.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
}
logger.finer("P4: polling[" + jobName + "] exit: " + state.change);
return state;
}
private boolean isConcurrentBuild(Job<?, ?> job) {
return job instanceof AbstractProject ? ((AbstractProject) job).isConcurrentBuild() :
job.getProperty(DisableConcurrentBuildsJobProperty.class) == null;
}
/**
* Construct workspace from environment and then look for changes.
*
* @param envVars
* @param listener
* @throws InterruptedException
* @throws IOException
*/
private PollingResult pollWorkspace(EnvVars envVars, TaskListener listener, FilePath buildWorkspace, Run<?, ?> lastRun)
throws InterruptedException, IOException {
// set NODE_NAME to Node or default "master" if not set
String nodeName = NodeHelper.getNodeName(buildWorkspace);
envVars.put("NODE_NAME", envVars.get("NODE_NAME", nodeName));
String executor = ExecutorHelper.getExecutorID(buildWorkspace, listener);
envVars.put("EXECUTOR_NUMBER", envVars.get("EXECUTOR_NUMBER", executor));
Workspace ws = workspace.deepClone();
// JENKINS-48434 by setting rootPath to null will leave client's root unchanged
ws.setRootPath(null);
ws.setExpand(envVars);
// Set EXPANDED client
String client = ws.getFullName();
listener.getLogger().println("P4: Polling on: " + nodeName + " with:" + client);
List<P4Ref> changes = lookForChanges(buildWorkspace, ws, lastRun, listener);
// Cleanup Perforce Client
cleanupPerforceClient(lastRun, buildWorkspace, listener, ws);
// Build if changes are found or report NO_CHANGE
if (changes == null) {
listener.getLogger().println("P4: Polling error; no previous change.");
return PollingResult.NO_CHANGES;
} else if(changes.isEmpty()) {
listener.getLogger().println("P4: Polling no changes found.");
return PollingResult.NO_CHANGES;
} else {
changes.forEach((c) -> listener.getLogger().println("P4: Polling found change: " + c));
return PollingResult.BUILD_NOW;
}
}
/**
* Look for un-built for changes
*
* @param ws
* @param lastRun
* @param listener
* @return A list of changes found during polling, empty list if no changes (up-to-date).
* Will return 'null' if no previous build.
*/
private List<P4Ref> lookForChanges(FilePath buildWorkspace, Workspace ws, Run<?, ?> lastRun, TaskListener listener)
throws IOException, InterruptedException {
// Set EXPANDED client
String syncID = ws.getSyncID();
// Set EXPANDED pinned label/change
String pin = populate.getPin();
if (pin != null && !pin.isEmpty()) {
pin = ws.getExpand().format(pin, false);
ws.getExpand().set(ReviewProp.P4_LABEL.toString(), pin);
}
// Calculate last change, build if null (JENKINS-40356)
List<P4Ref> lastRefs = TagAction.getLastChange(lastRun, listener, syncID);
if (lastRefs == null || lastRefs.isEmpty()) {
// no previous build, return null.
listener.getLogger().println("P4: Polling: No changes in previous build.");
return null;
}
// Create task
PollTask task = new PollTask(credential, lastRun, listener, filter, lastRefs);
task.setWorkspace(ws);
task.setLimit(pin);
// Execute remote task
List<P4Ref> changes = buildWorkspace.act(task);
return changes;
}
/**
* The checkout method is expected to check out modified files into the
* project workspace. In Perforce terms a 'p4 sync' on the project's
* workspace. Authorisation
*/
@Override
public void checkout(Run<?, ?> run, Launcher launcher, FilePath buildWorkspace, TaskListener listener,
File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException {
String jobName = run.getParent().getName();
logger.finer("P4: checkout[" + jobName + "] started...");
PrintStream log = listener.getLogger();
boolean success = true;
// Create task
CheckoutTask task = new CheckoutTask(credential, run, listener, populate);
// Update credential tracking
try {
CredentialsProvider.track(run, task.getCredential());
} catch (P4InvalidCredentialException e) {
String err = "P4: Unable to checkout: " + e;
logger.severe(err);
throw new AbortException(err);
}
// Get workspace used for the Task
Workspace ws = task.setEnvironment(run, workspace, buildWorkspace);
// Add review to environment, if defined
if (review != null) {
ws.addEnv(ReviewProp.SWARM_REVIEW.toString(), review.getId());
ws.addEnv(ReviewProp.SWARM_STATUS.toString(), CheckoutStatus.SHELVED.toString());
}
// Set the Workspace and initialise
task.setWorkspace(ws);
task.initialise();
// Override build change if polling per change.
if (isIncremental(getFilter())) {
Run<?, ?> lastRun = run.getPreviousBuiltBuild();
/* Fix for JENKINS-58639
Check if a previous build is in progress. If yes, do not try and build the same change that is being built.
To help lookForChanges() find the correct change to build, sending it the previousBuildInProgress
if not null else previousBuiltBuild.
*/
Run<?, ?> inProgressRun = run.getPreviousBuildInProgress();
if (inProgressRun != null) {
lastRun = inProgressRun;
}
List<P4Ref> changes = lookForChanges(buildWorkspace, ws, lastRun, listener);
task.setIncrementalChanges(changes);
}
// SCMRevision build per change
if (revision != null) {
List<P4Ref> changes = Arrays.asList(revision);
task.setIncrementalChanges(changes);
}
// Add tagging action to build, enabling label support.
TagAction tag = new TagAction(run, credential);
tag.setWorkspace(ws);
tag.setRefChanges(task.getSyncChange());
// JENKINS-37442: Make the log file name available
tag.setChangelog(changelogFile);
// JENKINS-39107: Make Depot location of Jenkinsfile available
WhereTask where = new WhereTask(credential, run, listener, getScriptPath(run));
where.setWorkspace(ws);
String jenkinsPath = buildWorkspace.act(where);
tag.setJenkinsPath(jenkinsPath);
tagAction = tag;
run.addAction(tag);
// Invoke build.
String node = ws.getExpand().get("NODE_NAME");
Job<?, ?> job = run.getParent();
if (run instanceof MatrixBuild) {
parentChange = new P4LabelRef(getChangeNumber(tag, run));
if (isBuildParent(job)) {
log.println("Building Parent on Node: " + node);
success &= buildWorkspace.act(task);
} else {
listener.getLogger().println("Skipping Parent build...");
success = true;
}
} else {
if (job instanceof MatrixProject) {
if (parentChange != null) {
log.println("Using parent change: " + parentChange);
task.setBuildChange(parentChange);
}
log.println("Building Child on Node: " + node);
} else {
log.println("Building on Node: " + node);
}
success &= buildWorkspace.act(task);
}
// Abort if build failed
if (!success) {
String msg = "P4: Build failed";
logger.warning(msg);
throw new AbortException(msg);
}
// Write change log if changeLogFile has been set.
if (changelogFile != null) {
// Calculate changes prior to build (based on last build)
listener.getLogger().println("P4: saving built changes.");
List<P4ChangeEntry> changes = calculateChanges(run, task);
P4ChangeSet.store(changelogFile, changes);
listener.getLogger().println("... done\n");
} else {
logger.fine("P4: unable to save changes, null changelogFile.");
}
// Cleanup Perforce Client
cleanupPerforceClient(run, buildWorkspace, listener, ws);
logger.finer("P4: checkout[" + jobName + "] finished.");
}
private String getScriptPath(Run<?, ?> run) {
if (script != null) {
return script;
}
if (!(run instanceof WorkflowRun)) {
return null;
}
WorkflowRun workflowRun = (WorkflowRun) run;
WorkflowJob job = workflowRun.getParent();
return getScriptPath(job);
}
public String getScriptPath(Item item) {
if (!(item instanceof WorkflowJob)) {
return null;
}
WorkflowJob job = (WorkflowJob) item;
FlowDefinition definition = job.getDefinition();
if (!(definition instanceof CpsScmFlowDefinition)) {
return null;
}
CpsScmFlowDefinition cps = (CpsScmFlowDefinition) definition;
if(!this.equals(cps.getScm())) {
return null;
}
return cps.getScriptPath();
}
private void cleanupPerforceClient(Run<?, ?> run, FilePath buildWorkspace, TaskListener listener, Workspace workspace) throws IOException, InterruptedException {
// exit early if cleanup not required
if (!workspace.isCleanup()) {
return;
}
listener.getLogger().println("P4Task: cleanup Client: " + workspace.getFullName());
RemoveClientTask removeClientTask = new RemoveClientTask(credential, run, listener);
// Override Global settings so that the client is deleted, but the files are preserved.
removeClientTask.setDeleteClient(true);
removeClientTask.setDeleteFiles(false);
// Set workspace used for the Task
Workspace ws = removeClientTask.setEnvironment(run, workspace, buildWorkspace);
removeClientTask.setWorkspace(ws);
buildWorkspace.act(removeClientTask);
}
// Get Matrix Execution options
private MatrixExecutionStrategy getMatrixExecutionStrategy(Job<?, ?> job) {
if (job instanceof MatrixProject) {
MatrixProject matrixProj = (MatrixProject) job;
return matrixProj.getExecutionStrategy();
}
return null;
}
boolean isBuildParent(Job<?, ?> job) {
MatrixExecutionStrategy matrix = getMatrixExecutionStrategy(job);
if (matrix instanceof MatrixOptions) {
return ((MatrixOptions) matrix).isBuildParent();
} else {
// if user hasn't configured "Perforce: Matrix Options" execution
// strategy, default to false
return false;
}
}
private List<P4ChangeEntry> calculateChanges(Run<?, ?> run, CheckoutTask task) {
List<P4ChangeEntry> list = new ArrayList<P4ChangeEntry>();
// Look for all changes since the last (completed) build.
// The lastBuild from getPreviousBuild() may be in progress or blocked.
Run<?, ?> lastBuild = run.getPreviousCompletedBuild();
String syncID = task.getSyncID();
List<P4Ref> lastRefs = TagAction.getLastChange(lastBuild, task.getListener(), syncID);
if (lastRefs != null && !lastRefs.isEmpty()) {
list.addAll(task.getChangesFull(lastRefs));
}
// if empty, look for shelves in current build. The latest change
// will not get listed as 'p4 changes n,n' will return no change
if (list.isEmpty()) {
List<P4Ref> lastRevisions = new ArrayList<>();
lastRevisions.add(task.getBuildChange());
if (lastRevisions != null && !lastRevisions.isEmpty()) {
list.addAll(task.getChangesFull(lastRevisions));
}
}
// still empty! No previous build, so add current
if ((lastBuild == null) && list.isEmpty()) {
list.add(task.getCurrentChange());
}
return list;
}
// Pre Jenkins 2.60
@Override
public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) {
super.buildEnvVars(build, env);
P4EnvironmentContributor.buildEnvironment(TagAction.getLastAction(build), env);
P4EnvironmentContributor.buildEnvironment(tagAction, env);
}
// Post Jenkins 2.60 JENKINS-37584 JENKINS-40885 JENKINS-52806 JENKINS-60074
public void buildEnvironment(Run<?, ?> run, Map<String, String> env) {
P4EnvironmentContributor.buildEnvironment(TagAction.getLastAction(run), env);
P4EnvironmentContributor.buildEnvironment(tagAction, env);
}
private String getChangeNumber(TagAction tagAction, Run<?, ?> run) {
List<P4Ref> builds = tagAction.getRefChanges();
for (P4Ref build : builds) {
if (build instanceof P4ChangeRef) {
// its a change, so return...
return build.toString();
}
if (build instanceof P4GraphRef) {
continue;
}
try {
// it is really a change number, so add change...
int change = Integer.parseInt(build.toString());
return String.valueOf(change);
} catch (NumberFormatException n) {
// not a change number
}
try (ConnectionHelper p4 = new ConnectionHelper(run, credential, null)) {
String name = build.toString();
// look for a label and return a change
String change = p4.labelToChange(name);
if (change != null) {
return change;
}
// look for a counter and return change
change = p4.counterToChange(name);
if (change != null) {
return change;
}
} catch (Exception e) {
// log error, but try next item
logger.severe("P4: Unable to getChangeNumber: " + e.getMessage());
}
}
return "";
}
/**
* The checkout method should, besides checking out the modified files,
* write a changelog.xml file that contains the changes for a certain build.
* The changelog.xml file is specific for each SCM implementation, and the
* createChangeLogParser returns a parser that can parse the file and return
* a ChangeLogSet.
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new P4ChangeParser(credential);
}
/**
* Called before a workspace is deleted on the given node, to provide SCM an
* opportunity to perform clean up.
*/
@Override
public boolean processWorkspaceBeforeDeletion(Job<?, ?> job, FilePath buildWorkspace, Node node)
throws IOException, InterruptedException {
logger.finer("processWorkspaceBeforeDeletion");
Run<?, ?> run = job.getLastBuild();
if (run == null) {
logger.warning("P4: No previous builds found");
return false;
}
// exit early if client workspace is undefined
LogTaskListener listener = new LogTaskListener(logger, Level.INFO);
EnvVars envVars = run.getEnvironment(listener);
String client = envVars.get("P4_CLIENT");
if (client == null || client.isEmpty()) {
logger.warning("P4: Unable to read P4_CLIENT");
return false;
}
// exit early if client workspace does not exist
ConnectionHelper connection = new ConnectionHelper(run, credential, null);
try {
if (!connection.isClient(client)) {
logger.warning("P4: client not found:" + client);
return false;
}
//JENKINS-60144 Checking if the template ws exists before deleting client, otherwise it throws exception along the line.
if (workspace instanceof TemplateWorkspaceImpl) {
TemplateWorkspaceImpl template = (TemplateWorkspaceImpl) workspace;
boolean exists = template.templateExists(connection.getConnection());
if (!exists) {
return false;
}
}
} catch (Exception e) {
logger.warning("P4: Not able to get connection");
return false;
}
// Setup Cleanup Task
RemoveClientTask task = new RemoveClientTask(credential, job, listener);
// Set workspace used for the Task
Workspace ws = task.setEnvironment(run, workspace, buildWorkspace);
task.setWorkspace(ws);
boolean clean = buildWorkspace.act(task);
logger.finer("processWorkspaceBeforeDeletion cleaned: " + clean);
return clean;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* The relationship of Descriptor and SCM (the describable) is akin to class
* and object. What this means is that the descriptor is used to create
* instances of the describable. Usually the Descriptor is an internal class
* in the SCM class named DescriptorImpl. The Descriptor should also contain
* the global configuration options as fields, just like the SCM class
* contains the configurations options for a job.
*
* @author pallen
*/
@Extension
@Symbol("perforce")
public static class DescriptorImpl extends SCMDescriptor<PerforceScm> {
private boolean autoSave;
private String credential;
private String clientName;
private String depotPath;
private boolean autoSubmitOnChange;
private boolean deleteClient;
private boolean deleteFiles;
private boolean hideTicket;
private int maxFiles = DEFAULT_FILE_LIMIT;
private int maxChanges = DEFAULT_CHANGE_LIMIT;
private long headLimit = DEFAULT_HEAD_LIMIT;
public boolean isAutoSave() {
return autoSave;
}
public String getCredential() {
return credential;
}
public String getClientName() {
return clientName;
}
public String getDepotPath() {
return depotPath;
}
public boolean isAutoSubmitOnChange() {
return autoSubmitOnChange;
}
public boolean isDeleteClient() {
return deleteClient;
}
public boolean isDeleteFiles() {
return deleteFiles;
}
public boolean isHideTicket() {
return hideTicket;
}
public int getMaxFiles() {
return maxFiles;
}
public int getMaxChanges() {
return maxChanges;
}
public long getHeadLimit() {
return headLimit;
}
/**
* public no-argument constructor
*/
public DescriptorImpl() {
super(PerforceScm.class, P4Browser.class);
load();
}
/**
* Returns the name of the SCM, this is the name that will show up next
* to CVS and Subversion when configuring a job.
*/
@Override
public String getDisplayName() {
return "Perforce Software";
}
@Override
public boolean isApplicable(Job project) {
return true;
}
@Override
public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException {
PerforceScm scm = (PerforceScm) super.newInstance(req, formData);
return scm;
}
/**
* The configure method is invoked when the global configuration page is
* submitted. In the method the data in the web form should be copied to
* the Descriptor's fields. To persist the fields to the global
* configuration XML file, the save() method must be called. Data is
* defined in the global.jelly page.
*/
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
try {
autoSave = json.getBoolean("autoSave");
credential = json.getString("credential");
clientName = json.getString("clientName");
depotPath = json.getString("depotPath");
autoSubmitOnChange = json.getBoolean("autoSubmitOnChange");
} catch (JSONException e) {
logger.info("Unable to read Auto Version configuration.");
autoSave = false;
}
try {
deleteClient = json.getBoolean("deleteClient");
deleteFiles = json.getBoolean("deleteFiles");
} catch (JSONException e) {
logger.info("Unable to read client cleanup configuration.");
deleteClient = false;
deleteFiles = false;
}
try {
hideTicket = json.getBoolean("hideTicket");
} catch (JSONException e) {
logger.info("Unable to read TICKET security configuration.");
hideTicket = false;
}
try {
maxFiles = json.getInt("maxFiles");
maxChanges = json.getInt("maxChanges");
} catch (JSONException e) {
logger.info("Unable to read Max limits in configuration.");
maxFiles = DEFAULT_FILE_LIMIT;
maxChanges = DEFAULT_CHANGE_LIMIT;
}
try {
headLimit = json.getLong("headLimit");
} catch (JSONException e) {
logger.info("Unable to read query limits in configuration.");
headLimit = DEFAULT_HEAD_LIMIT;
}
save();
return true;
}
/**
* Credentials list, a Jelly config method for a build job.
*
* @param project Jenkins project item
* @param credential Perforce credential ID
* @return A list of Perforce credential items to populate the jelly
* Select list.
*/
public ListBoxModel doFillCredentialItems(@AncestorInPath Item project, @QueryParameter String credential) {
return P4CredentialsImpl.doFillCredentialItems(project, credential);
}
/**
* Credentials list, a Jelly config method for a build job.
*
* @param project Jenkins project item
* @param value credential user input value
* @return A list of Perforce credential items to populate the jelly
* Select list.
*/
public FormValidation doCheckCredential(@AncestorInPath Item project, @QueryParameter String value) {
return P4CredentialsImpl.doCheckCredential(project, value);
}
}
/**
* This methods determines if the SCM plugin can be used for polling
*/
@Override
public boolean supportsPolling() {
return true;
}
/**
* This method should return true if the SCM requires a workspace for
* polling. Perforce however can report submitted, pending and shelved
* changes without needing a workspace
*/
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
/**
* Incremental polling filter is set
*
* @param filter List of filters to check for incrementaloption
* @return true if set
*/
public static boolean isIncremental(List<Filter> filter) {
if (filter != null) {
for (Filter f : filter) {
if (f instanceof FilterPerChangeImpl) {
if (((FilterPerChangeImpl) f).isPerChange()) {
return true;
}
}
}
}
return false;
}
}
|
src/main/java/org/jenkinsci/plugins/p4/PerforceScm.java
|
package org.jenkinsci.plugins.p4;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.perforce.p4java.exception.P4JavaException;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Plugin;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixExecutionStrategy;
import hudson.matrix.MatrixProject;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.LogTaskListener;
import jenkins.model.Jenkins;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.multiplescms.MultiSCM;
import org.jenkinsci.plugins.p4.browsers.P4Browser;
import org.jenkinsci.plugins.p4.browsers.SwarmBrowser;
import org.jenkinsci.plugins.p4.build.ExecutorHelper;
import org.jenkinsci.plugins.p4.build.NodeHelper;
import org.jenkinsci.plugins.p4.build.P4EnvironmentContributor;
import org.jenkinsci.plugins.p4.changes.P4ChangeEntry;
import org.jenkinsci.plugins.p4.changes.P4ChangeParser;
import org.jenkinsci.plugins.p4.changes.P4ChangeRef;
import org.jenkinsci.plugins.p4.changes.P4ChangeSet;
import org.jenkinsci.plugins.p4.changes.P4GraphRef;
import org.jenkinsci.plugins.p4.changes.P4LabelRef;
import org.jenkinsci.plugins.p4.changes.P4Ref;
import org.jenkinsci.plugins.p4.client.ConnectionHelper;
import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials;
import org.jenkinsci.plugins.p4.credentials.P4CredentialsImpl;
import org.jenkinsci.plugins.p4.credentials.P4InvalidCredentialException;
import org.jenkinsci.plugins.p4.filters.Filter;
import org.jenkinsci.plugins.p4.filters.FilterPerChangeImpl;
import org.jenkinsci.plugins.p4.matrix.MatrixOptions;
import org.jenkinsci.plugins.p4.populate.Populate;
import org.jenkinsci.plugins.p4.review.P4Review;
import org.jenkinsci.plugins.p4.review.ReviewProp;
import org.jenkinsci.plugins.p4.scm.AbstractP4ScmSource;
import org.jenkinsci.plugins.p4.scm.P4Path;
import org.jenkinsci.plugins.p4.tagging.TagAction;
import org.jenkinsci.plugins.p4.tasks.CheckoutStatus;
import org.jenkinsci.plugins.p4.tasks.CheckoutTask;
import org.jenkinsci.plugins.p4.tasks.PollTask;
import org.jenkinsci.plugins.p4.tasks.RemoveClientTask;
import org.jenkinsci.plugins.p4.tasks.WhereTask;
import org.jenkinsci.plugins.p4.workspace.ManualWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.SpecWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StreamWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition;
import org.jenkinsci.plugins.workflow.flow.FlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PerforceScm extends SCM {
private static Logger logger = Logger.getLogger(PerforceScm.class.getName());
private final String credential;
private final Workspace workspace;
private final List<Filter> filter;
private final Populate populate;
private final P4Browser browser;
private final P4Ref revision;
private String script;
private TagAction tagAction = null;
private transient P4Ref parentChange;
private transient P4Review review;
public static final int DEFAULT_FILE_LIMIT = 50;
public static final int DEFAULT_CHANGE_LIMIT = 20;
public static final long DEFAULT_HEAD_LIMIT = 1000;
public String getCredential() {
return credential;
}
public Workspace getWorkspace() {
return workspace;
}
public List<Filter> getFilter() {
return filter;
}
public Populate getPopulate() {
return populate;
}
@Override
public P4Browser getBrowser() {
return browser;
}
public P4Review getReview() {
return review;
}
public void setReview(P4Review review) {
this.review = review;
}
/**
* Helper function for converting an SCM object into a
* PerforceScm object when appropriate.
*
* @param scm the SCM object
* @return a PerforceScm instance or null
*/
public static PerforceScm convertToPerforceScm(SCM scm) {
PerforceScm perforceScm = null;
if (scm instanceof PerforceScm) {
perforceScm = (PerforceScm) scm;
} else {
Jenkins jenkins = Jenkins.getInstance();
if (jenkins != null) {
Plugin multiSCMPlugin = jenkins.getPlugin("multiple-scms");
if (multiSCMPlugin != null) {
if (scm instanceof MultiSCM) {
MultiSCM multiSCM = (MultiSCM) scm;
for (SCM configuredSCM : multiSCM.getConfiguredSCMs()) {
if (configuredSCM instanceof PerforceScm) {
perforceScm = (PerforceScm) configuredSCM;
break;
}
}
}
}
}
}
return perforceScm;
}
/**
* Create a constructor that takes non-transient fields, and add the
* annotation @DataBoundConstructor to it. Using the annotation helps the
* Stapler class to find which constructor that should be used when
* automatically copying values from a web form to a class.
*
* @param credential Credential ID
* @param workspace Workspace connection details
* @param filter Polling filters
* @param populate Populate options
* @param browser Browser options
*/
@DataBoundConstructor
public PerforceScm(String credential, Workspace workspace, List<Filter> filter, Populate populate,
P4Browser browser) {
this.credential = credential;
this.workspace = workspace;
this.filter = filter;
this.populate = populate;
this.browser = browser;
this.revision = null;
}
/**
* MultiBranch constructor for building jobs.
*
* @param source ScmSource
* @param path Perforce project path and mappings
* @param revision Perforce revision
*/
public PerforceScm(AbstractP4ScmSource source, P4Path path, P4Ref revision) {
this.credential = source.getCredential();
this.workspace = source.getWorkspace(path);
this.filter = source.getFilter();
this.populate = source.getPopulate();
this.browser = source.getBrowser();
this.revision = revision;
this.script = source.getScriptPathOrDefault();
}
/**
* Internal constructor for functional tests.
*
* @param credential Credential ID
* @param workspace Workspace type
* @param populate Populate options
*/
public PerforceScm(String credential, Workspace workspace, Populate populate) {
this.credential = credential;
this.workspace = workspace;
this.filter = null;
this.populate = populate;
this.browser = null;
this.revision = null;
}
@Override
public String getKey() {
String delim = "-";
StringBuffer key = new StringBuffer("p4");
// add Credential
key.append(delim);
key.append(credential);
// add Mapping/Stream
key.append(delim);
if (workspace instanceof ManualWorkspaceImpl) {
ManualWorkspaceImpl ws = (ManualWorkspaceImpl) workspace;
key.append(ws.getSpec().getView());
key.append(ws.getSpec().getStreamName());
}
if (workspace instanceof StreamWorkspaceImpl) {
StreamWorkspaceImpl ws = (StreamWorkspaceImpl) workspace;
key.append(ws.getStreamName());
}
if (workspace instanceof SpecWorkspaceImpl) {
SpecWorkspaceImpl ws = (SpecWorkspaceImpl) workspace;
key.append(ws.getSpecPath());
}
if (workspace instanceof StaticWorkspaceImpl) {
StaticWorkspaceImpl ws = (StaticWorkspaceImpl) workspace;
key.append(ws.getName());
}
if (workspace instanceof TemplateWorkspaceImpl) {
TemplateWorkspaceImpl ws = (TemplateWorkspaceImpl) workspace;
key.append(ws.getTemplateName());
}
return key.toString();
}
public static P4Browser findBrowser(String scmCredential) {
// Retrieve item from request
StaplerRequest req = Stapler.getCurrentRequest();
Job job = req == null ? null : req.findAncestorObject(Job.class);
// If cannot retrieve item, check from root
P4BaseCredentials credentials = job == null
? ConnectionHelper.findCredential(scmCredential, Jenkins.getActiveInstance())
: ConnectionHelper.findCredential(scmCredential, job);
if (credentials == null) {
logger.fine("Could not retrieve credentials from id: '${scmCredential}");
return null;
}
try (ConnectionHelper p4 = new ConnectionHelper(credentials, null)) {
String url = p4.getSwarm();
if (url != null) {
return new SwarmBrowser(url);
} else {
return null;
}
} catch (IOException e) {
logger.severe("Connection error. " + e.getMessage());
} catch (P4JavaException e) {
logger.severe("Unable to access Swarm Property. " + e.getMessage());
} catch (Exception e) {
logger.severe("Perforce resource error. " + e.getMessage());
}
return null;
}
/**
* Calculate the state of the workspace of the given build. The returned
* object is then fed into compareRemoteRevisionWith as the baseline
* SCMRevisionState to determine if the build is necessary, and is added to
* the build as an Action for later retrieval.
*/
@Override
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> run, FilePath buildWorkspace, Launcher launcher,
TaskListener listener) throws IOException, InterruptedException {
// A baseline is not required... but a baseline object is, so we'll
// return the NONE object.
return SCMRevisionState.NONE;
}
/**
* This method does the actual polling and returns a PollingResult. The
* change attribute of the PollingResult the significance of the changes
* detected by this poll.
*/
@Override
public PollingResult compareRemoteRevisionWith(Job<?, ?> job, Launcher launcher, FilePath buildWorkspace,
TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException {
String jobName = job.getName();
logger.finer("P4: polling[" + jobName + "] started...");
PollingResult state = PollingResult.NO_CHANGES;
// Get last run and build workspace
Run<?, ?> lastRun = job.getLastBuild();
Queue.Item[] items = Jenkins.getInstance().getQueue().getItems();
for(Queue.Item item : items) {
if(item.task instanceof WorkflowJob) {
WorkflowJob task = (WorkflowJob) item.task;
if(task.equals(job)) {
if(item instanceof Queue.WaitingItem) {
logger.info("P4: polling[" + jobName + "] skipping WaitingItem");
return PollingResult.NO_CHANGES;
}
if(item instanceof Queue.BlockedItem) {
logger.finer("P4: polling[" + jobName + "] BlockedItem");
}
if(item instanceof Queue.BuildableItem) {
logger.finer("P4: polling[" + jobName + "] BuildableItem");
}
}
}
}
// Build workspace is often null as requiresWorkspaceForPolling() returns false as a checked out workspace is
// not needed, but we still need a client and artificial root for the view.
// JENKINS-46908
if (buildWorkspace == null) {
String defaultRoot = job.getRootDir().getAbsoluteFile().getAbsolutePath();
if (lastRun != null) {
EnvVars env = lastRun.getEnvironment(listener);
buildWorkspace = new FilePath(new File(env.get("WORKSPACE", defaultRoot)));
} else {
listener.getLogger().println("Warning Jenkins Workspace root not defined.");
return PollingResult.NO_CHANGES;
}
}
Node node = NodeHelper.workspaceToNode(buildWorkspace);
if (job instanceof MatrixProject) {
if (isBuildParent(job)) {
// Poll PARENT only
EnvVars envVars = job.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
} else {
// Poll CHILDREN only
MatrixProject matrixProj = (MatrixProject) job;
Collection<MatrixConfiguration> configs = matrixProj.getActiveConfigurations();
for (MatrixConfiguration config : configs) {
EnvVars envVars = config.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
// exit early if changes found
if (state == PollingResult.BUILD_NOW) {
logger.finer("P4: polling[" + jobName + "] exit (Matrix): " + state.change);
return state;
}
}
}
} else {
EnvVars envVars = job.getEnvironment(node, listener);
state = pollWorkspace(envVars, listener, buildWorkspace, lastRun);
}
logger.finer("P4: polling[" + jobName + "] exit: " + state.change);
return state;
}
private boolean isConcurrentBuild(Job<?, ?> job) {
return job instanceof AbstractProject ? ((AbstractProject) job).isConcurrentBuild() :
job.getProperty(DisableConcurrentBuildsJobProperty.class) == null;
}
/**
* Construct workspace from environment and then look for changes.
*
* @param envVars
* @param listener
* @throws InterruptedException
* @throws IOException
*/
private PollingResult pollWorkspace(EnvVars envVars, TaskListener listener, FilePath buildWorkspace, Run<?, ?> lastRun)
throws InterruptedException, IOException {
// set NODE_NAME to Node or default "master" if not set
String nodeName = NodeHelper.getNodeName(buildWorkspace);
envVars.put("NODE_NAME", envVars.get("NODE_NAME", nodeName));
String executor = ExecutorHelper.getExecutorID(buildWorkspace, listener);
envVars.put("EXECUTOR_NUMBER", envVars.get("EXECUTOR_NUMBER", executor));
Workspace ws = workspace.deepClone();
// JENKINS-48434 by setting rootPath to null will leave client's root unchanged
ws.setRootPath(null);
ws.setExpand(envVars);
// Set EXPANDED client
String client = ws.getFullName();
listener.getLogger().println("P4: Polling on: " + nodeName + " with:" + client);
List<P4Ref> changes = lookForChanges(buildWorkspace, ws, lastRun, listener);
// Cleanup Perforce Client
cleanupPerforceClient(lastRun, buildWorkspace, listener, ws);
// Build if changes are found or report NO_CHANGE
if (changes == null) {
listener.getLogger().println("P4: Polling error; no previous change.");
return PollingResult.NO_CHANGES;
} else if(changes.isEmpty()) {
listener.getLogger().println("P4: Polling no changes found.");
return PollingResult.NO_CHANGES;
} else {
changes.forEach((c) -> listener.getLogger().println("P4: Polling found change: " + c));
return PollingResult.BUILD_NOW;
}
}
/**
* Look for un-built for changes
*
* @param ws
* @param lastRun
* @param listener
* @return A list of changes found during polling, empty list if no changes (up-to-date).
* Will return 'null' if no previous build.
*/
private List<P4Ref> lookForChanges(FilePath buildWorkspace, Workspace ws, Run<?, ?> lastRun, TaskListener listener)
throws IOException, InterruptedException {
// Set EXPANDED client
String syncID = ws.getSyncID();
// Set EXPANDED pinned label/change
String pin = populate.getPin();
if (pin != null && !pin.isEmpty()) {
pin = ws.getExpand().format(pin, false);
ws.getExpand().set(ReviewProp.P4_LABEL.toString(), pin);
}
// Calculate last change, build if null (JENKINS-40356)
List<P4Ref> lastRefs = TagAction.getLastChange(lastRun, listener, syncID);
if (lastRefs == null || lastRefs.isEmpty()) {
// no previous build, return null.
listener.getLogger().println("P4: Polling: No changes in previous build.");
return null;
}
// Create task
PollTask task = new PollTask(credential, lastRun, listener, filter, lastRefs);
task.setWorkspace(ws);
task.setLimit(pin);
// Execute remote task
List<P4Ref> changes = buildWorkspace.act(task);
return changes;
}
/**
* The checkout method is expected to check out modified files into the
* project workspace. In Perforce terms a 'p4 sync' on the project's
* workspace. Authorisation
*/
@Override
public void checkout(Run<?, ?> run, Launcher launcher, FilePath buildWorkspace, TaskListener listener,
File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException {
String jobName = run.getParent().getName();
logger.finer("P4: checkout[" + jobName + "] started...");
PrintStream log = listener.getLogger();
boolean success = true;
// Create task
CheckoutTask task = new CheckoutTask(credential, run, listener, populate);
// Update credential tracking
try {
CredentialsProvider.track(run, task.getCredential());
} catch (P4InvalidCredentialException e) {
String err = "P4: Unable to checkout: " + e;
logger.severe(err);
throw new AbortException(err);
}
// Get workspace used for the Task
Workspace ws = task.setEnvironment(run, workspace, buildWorkspace);
// Add review to environment, if defined
if (review != null) {
ws.addEnv(ReviewProp.SWARM_REVIEW.toString(), review.getId());
ws.addEnv(ReviewProp.SWARM_STATUS.toString(), CheckoutStatus.SHELVED.toString());
}
// Set the Workspace and initialise
task.setWorkspace(ws);
task.initialise();
// Override build change if polling per change.
if (isIncremental(getFilter())) {
Run<?, ?> lastRun = run.getPreviousBuiltBuild();
/* Fix for JENKINS-58639
Check if a previous build is in progress. If yes, do not try and build the same change that is being built.
To help lookForChanges() find the correct change to build, sending it the previousBuildInProgress
if not null else previousBuiltBuild.
*/
Run<?, ?> inProgressRun = run.getPreviousBuildInProgress();
if (inProgressRun != null) {
lastRun = inProgressRun;
}
List<P4Ref> changes = lookForChanges(buildWorkspace, ws, lastRun, listener);
task.setIncrementalChanges(changes);
}
// SCMRevision build per change
if (revision != null) {
List<P4Ref> changes = Arrays.asList(revision);
task.setIncrementalChanges(changes);
}
// Add tagging action to build, enabling label support.
TagAction tag = new TagAction(run, credential);
tag.setWorkspace(ws);
tag.setRefChanges(task.getSyncChange());
// JENKINS-37442: Make the log file name available
tag.setChangelog(changelogFile);
// JENKINS-39107: Make Depot location of Jenkinsfile available
WhereTask where = new WhereTask(credential, run, listener, getScriptPath(run));
where.setWorkspace(ws);
String jenkinsPath = buildWorkspace.act(where);
tag.setJenkinsPath(jenkinsPath);
tagAction = tag;
run.addAction(tag);
// Invoke build.
String node = ws.getExpand().get("NODE_NAME");
Job<?, ?> job = run.getParent();
if (run instanceof MatrixBuild) {
parentChange = new P4LabelRef(getChangeNumber(tag, run));
if (isBuildParent(job)) {
log.println("Building Parent on Node: " + node);
success &= buildWorkspace.act(task);
} else {
listener.getLogger().println("Skipping Parent build...");
success = true;
}
} else {
if (job instanceof MatrixProject) {
if (parentChange != null) {
log.println("Using parent change: " + parentChange);
task.setBuildChange(parentChange);
}
log.println("Building Child on Node: " + node);
} else {
log.println("Building on Node: " + node);
}
success &= buildWorkspace.act(task);
}
// Abort if build failed
if (!success) {
String msg = "P4: Build failed";
logger.warning(msg);
throw new AbortException(msg);
}
// Write change log if changeLogFile has been set.
if (changelogFile != null) {
// Calculate changes prior to build (based on last build)
listener.getLogger().println("P4: saving built changes.");
List<P4ChangeEntry> changes = calculateChanges(run, task);
P4ChangeSet.store(changelogFile, changes);
listener.getLogger().println("... done\n");
} else {
logger.fine("P4: unable to save changes, null changelogFile.");
}
// Cleanup Perforce Client
cleanupPerforceClient(run, buildWorkspace, listener, ws);
logger.finer("P4: checkout[" + jobName + "] finished.");
}
private String getScriptPath(Run<?, ?> run) {
if (script != null) {
return script;
}
if (!(run instanceof WorkflowRun)) {
return null;
}
WorkflowRun workflowRun = (WorkflowRun) run;
WorkflowJob job = workflowRun.getParent();
return getScriptPath(job);
}
public String getScriptPath(Item item) {
if (!(item instanceof WorkflowJob)) {
return null;
}
WorkflowJob job = (WorkflowJob) item;
FlowDefinition definition = job.getDefinition();
if (!(definition instanceof CpsScmFlowDefinition)) {
return null;
}
CpsScmFlowDefinition cps = (CpsScmFlowDefinition) definition;
if(!this.equals(cps.getScm())) {
return null;
}
return cps.getScriptPath();
}
private void cleanupPerforceClient(Run<?, ?> run, FilePath buildWorkspace, TaskListener listener, Workspace workspace) throws IOException, InterruptedException {
// exit early if cleanup not required
if (!workspace.isCleanup()) {
return;
}
listener.getLogger().println("P4Task: cleanup Client: " + workspace.getFullName());
RemoveClientTask removeClientTask = new RemoveClientTask(credential, run, listener);
// Override Global settings so that the client is deleted, but the files are preserved.
removeClientTask.setDeleteClient(true);
removeClientTask.setDeleteFiles(false);
// Set workspace used for the Task
Workspace ws = removeClientTask.setEnvironment(run, workspace, buildWorkspace);
removeClientTask.setWorkspace(ws);
buildWorkspace.act(removeClientTask);
}
// Get Matrix Execution options
private MatrixExecutionStrategy getMatrixExecutionStrategy(Job<?, ?> job) {
if (job instanceof MatrixProject) {
MatrixProject matrixProj = (MatrixProject) job;
return matrixProj.getExecutionStrategy();
}
return null;
}
boolean isBuildParent(Job<?, ?> job) {
MatrixExecutionStrategy matrix = getMatrixExecutionStrategy(job);
if (matrix instanceof MatrixOptions) {
return ((MatrixOptions) matrix).isBuildParent();
} else {
// if user hasn't configured "Perforce: Matrix Options" execution
// strategy, default to false
return false;
}
}
private List<P4ChangeEntry> calculateChanges(Run<?, ?> run, CheckoutTask task) {
List<P4ChangeEntry> list = new ArrayList<P4ChangeEntry>();
// Look for all changes since the last (completed) build.
// The lastBuild from getPreviousBuild() may be in progress or blocked.
Run<?, ?> lastBuild = run.getPreviousCompletedBuild();
String syncID = task.getSyncID();
List<P4Ref> lastRefs = TagAction.getLastChange(lastBuild, task.getListener(), syncID);
if (lastRefs != null && !lastRefs.isEmpty()) {
list.addAll(task.getChangesFull(lastRefs));
}
// if empty, look for shelves in current build. The latest change
// will not get listed as 'p4 changes n,n' will return no change
if (list.isEmpty()) {
List<P4Ref> lastRevisions = new ArrayList<>();
lastRevisions.add(task.getBuildChange());
if (lastRevisions != null && !lastRevisions.isEmpty()) {
list.addAll(task.getChangesFull(lastRevisions));
}
}
// still empty! No previous build, so add current
if ((lastBuild == null) && list.isEmpty()) {
list.add(task.getCurrentChange());
}
return list;
}
// Pre Jenkins 2.60
@Override
public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) {
super.buildEnvVars(build, env);
P4EnvironmentContributor.buildEnvironment(TagAction.getLastAction(build), env);
P4EnvironmentContributor.buildEnvironment(tagAction, env);
}
// Post Jenkins 2.60 JENKINS-37584 JENKINS-40885 JENKINS-52806 JENKINS-60074
public void buildEnvironment(Run<?, ?> run, Map<String, String> env) {
P4EnvironmentContributor.buildEnvironment(TagAction.getLastAction(run), env);
P4EnvironmentContributor.buildEnvironment(tagAction, env);
}
private String getChangeNumber(TagAction tagAction, Run<?, ?> run) {
List<P4Ref> builds = tagAction.getRefChanges();
for (P4Ref build : builds) {
if (build instanceof P4ChangeRef) {
// its a change, so return...
return build.toString();
}
if (build instanceof P4GraphRef) {
continue;
}
try {
// it is really a change number, so add change...
int change = Integer.parseInt(build.toString());
return String.valueOf(change);
} catch (NumberFormatException n) {
// not a change number
}
try (ConnectionHelper p4 = new ConnectionHelper(run, credential, null)) {
String name = build.toString();
// look for a label and return a change
String change = p4.labelToChange(name);
if (change != null) {
return change;
}
// look for a counter and return change
change = p4.counterToChange(name);
if (change != null) {
return change;
}
} catch (Exception e) {
// log error, but try next item
logger.severe("P4: Unable to getChangeNumber: " + e.getMessage());
}
}
return "";
}
/**
* The checkout method should, besides checking out the modified files,
* write a changelog.xml file that contains the changes for a certain build.
* The changelog.xml file is specific for each SCM implementation, and the
* createChangeLogParser returns a parser that can parse the file and return
* a ChangeLogSet.
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new P4ChangeParser(credential);
}
/**
* Called before a workspace is deleted on the given node, to provide SCM an
* opportunity to perform clean up.
*/
@Override
public boolean processWorkspaceBeforeDeletion(Job<?, ?> job, FilePath buildWorkspace, Node node)
throws IOException, InterruptedException {
logger.finer("processWorkspaceBeforeDeletion");
Run<?, ?> run = job.getLastBuild();
if (run == null) {
logger.warning("P4: No previous builds found");
return false;
}
// exit early if client workspace is undefined
LogTaskListener listener = new LogTaskListener(logger, Level.INFO);
EnvVars envVars = run.getEnvironment(listener);
String client = envVars.get("P4_CLIENT");
if (client == null || client.isEmpty()) {
logger.warning("P4: Unable to read P4_CLIENT");
return false;
}
// exit early if client workspace does not exist
ConnectionHelper connection = new ConnectionHelper(run, credential, null);
try {
if (!connection.isClient(client)) {
logger.warning("P4: client not found:" + client);
return false;
}
//JENKINS-60144 Checking if the template ws exists before deleting client, otherwise it throws exception along the line.
if (workspace instanceof TemplateWorkspaceImpl) {
TemplateWorkspaceImpl template = (TemplateWorkspaceImpl) workspace;
boolean exists = template.templateExists(connection.getConnection());
if (!exists) {
return false;
}
}
} catch (Exception e) {
logger.warning("P4: Not able to get connection");
return false;
}
// Setup Cleanup Task
RemoveClientTask task = new RemoveClientTask(credential, job, listener);
// Set workspace used for the Task
Workspace ws = task.setEnvironment(run, workspace, buildWorkspace);
task.setWorkspace(ws);
boolean clean = buildWorkspace.act(task);
logger.finer("processWorkspaceBeforeDeletion cleaned: " + clean);
return clean;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* The relationship of Descriptor and SCM (the describable) is akin to class
* and object. What this means is that the descriptor is used to create
* instances of the describable. Usually the Descriptor is an internal class
* in the SCM class named DescriptorImpl. The Descriptor should also contain
* the global configuration options as fields, just like the SCM class
* contains the configurations options for a job.
*
* @author pallen
*/
@Extension
@Symbol("perforce")
public static class DescriptorImpl extends SCMDescriptor<PerforceScm> {
private boolean autoSave;
private String credential;
private String clientName;
private String depotPath;
private boolean autoSubmitOnChange;
private boolean deleteClient;
private boolean deleteFiles;
private boolean hideTicket;
private int maxFiles = DEFAULT_FILE_LIMIT;
private int maxChanges = DEFAULT_CHANGE_LIMIT;
private long headLimit = DEFAULT_HEAD_LIMIT;
public boolean isAutoSave() {
return autoSave;
}
public String getCredential() {
return credential;
}
public String getClientName() {
return clientName;
}
public String getDepotPath() {
return depotPath;
}
public boolean isAutoSubmitOnChange() {
return autoSubmitOnChange;
}
public boolean isDeleteClient() {
return deleteClient;
}
public boolean isDeleteFiles() {
return deleteFiles;
}
public boolean isHideTicket() {
return hideTicket;
}
public int getMaxFiles() {
return maxFiles;
}
public int getMaxChanges() {
return maxChanges;
}
public long getHeadLimit() {
return headLimit;
}
/**
* public no-argument constructor
*/
public DescriptorImpl() {
super(PerforceScm.class, P4Browser.class);
load();
}
/**
* Returns the name of the SCM, this is the name that will show up next
* to CVS and Subversion when configuring a job.
*/
@Override
public String getDisplayName() {
return "Perforce Software";
}
@Override
public boolean isApplicable(Job project) {
return true;
}
@Override
public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException {
PerforceScm scm = (PerforceScm) super.newInstance(req, formData);
return scm;
}
/**
* The configure method is invoked when the global configuration page is
* submitted. In the method the data in the web form should be copied to
* the Descriptor's fields. To persist the fields to the global
* configuration XML file, the save() method must be called. Data is
* defined in the global.jelly page.
*/
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
try {
autoSave = json.getBoolean("autoSave");
credential = json.getString("credential");
clientName = json.getString("clientName");
depotPath = json.getString("depotPath");
autoSubmitOnChange = json.getBoolean("autoSubmitOnChange");
} catch (JSONException e) {
logger.info("Unable to read Auto Version configuration.");
autoSave = false;
}
try {
deleteClient = json.getBoolean("deleteClient");
deleteFiles = json.getBoolean("deleteFiles");
} catch (JSONException e) {
logger.info("Unable to read client cleanup configuration.");
deleteClient = false;
deleteFiles = false;
}
try {
hideTicket = json.getBoolean("hideTicket");
} catch (JSONException e) {
logger.info("Unable to read TICKET security configuration.");
hideTicket = false;
}
try {
maxFiles = json.getInt("maxFiles");
maxChanges = json.getInt("maxChanges");
} catch (JSONException e) {
logger.info("Unable to read Max limits in configuration.");
maxFiles = DEFAULT_FILE_LIMIT;
maxChanges = DEFAULT_CHANGE_LIMIT;
}
try {
headLimit = json.getLong("headLimit");
} catch (JSONException e) {
logger.info("Unable to read query limits in configuration.");
headLimit = DEFAULT_HEAD_LIMIT;
}
save();
return true;
}
/**
* Credentials list, a Jelly config method for a build job.
*
* @param project Jenkins project item
* @param credential Perforce credential ID
* @return A list of Perforce credential items to populate the jelly
* Select list.
*/
public ListBoxModel doFillCredentialItems(@AncestorInPath Item project, @QueryParameter String credential) {
return P4CredentialsImpl.doFillCredentialItems(project, credential);
}
/**
* Credentials list, a Jelly config method for a build job.
*
* @param project Jenkins project item
* @param value credential user input value
* @return A list of Perforce credential items to populate the jelly
* Select list.
*/
public FormValidation doCheckCredential(@AncestorInPath Item project, @QueryParameter String value) {
return P4CredentialsImpl.doCheckCredential(project, value);
}
}
/**
* This methods determines if the SCM plugin can be used for polling
*/
@Override
public boolean supportsPolling() {
return true;
}
/**
* This method should return true if the SCM requires a workspace for
* polling. Perforce however can report submitted, pending and shelved
* changes without needing a workspace
*/
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
/**
* Incremental polling filter is set
*
* @param filter List of filters to check for incrementaloption
* @return true if set
*/
public static boolean isIncremental(List<Filter> filter) {
if (filter != null) {
for (Filter f : filter) {
if (f instanceof FilterPerChangeImpl) {
if (((FilterPerChangeImpl) f).isPerChange()) {
return true;
}
}
}
}
return false;
}
}
|
tagAction should not be written to config.xml
|
src/main/java/org/jenkinsci/plugins/p4/PerforceScm.java
|
tagAction should not be written to config.xml
|
<ide><path>rc/main/java/org/jenkinsci/plugins/p4/PerforceScm.java
<ide> private final P4Ref revision;
<ide>
<ide> private String script;
<del> private TagAction tagAction = null;
<del>
<add>
<add> private transient TagAction tagAction = null;
<ide> private transient P4Ref parentChange;
<ide> private transient P4Review review;
<ide>
|
|
Java
|
apache-2.0
|
a97e59691fd236197a1388af9da227f7ec00acf1
| 0 |
murara/teste,murara/teste
|
public class JoseMiguel {
public static void main(String[] args) {
// falaaaaaaaaaaa zzo kk
}
}
|
src/JoseMiguel.java
|
public class JoseMiguel {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
comentei
|
src/JoseMiguel.java
|
<ide><path>rc/JoseMiguel.java
<ide>
<ide> public class JoseMiguel {
<add>
<ide>
<ide> public static void main(String[] args) {
<del> // TODO Auto-generated method stub
<add>
<add> // falaaaaaaaaaaa zzo kk
<add>
<ide>
<ide> }
<ide>
|
||
Java
|
apache-2.0
|
c83f38a5e29a69d226e45cc96aab7fde1e998bbe
| 0 |
ricepanda/rice,ricepanda/rice,ricepanda/rice,ricepanda/rice
|
/*
* Copyright 2007 The Kuali Foundation Licensed under the Educational Community
* License, Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.opensource.org/licenses/ecl1.php Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.kuali.rice.krad.uif.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.mo.common.active.Inactivatable;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.uif.core.ActiveCollectionFilter;
import org.kuali.rice.krad.uif.core.BindingInfo;
import org.kuali.rice.krad.uif.core.CollectionFilter;
import org.kuali.rice.krad.uif.core.Component;
import org.kuali.rice.krad.uif.core.DataBinding;
import org.kuali.rice.krad.uif.field.ActionField;
import org.kuali.rice.krad.uif.field.AttributeField;
import org.kuali.rice.krad.uif.field.Field;
import org.kuali.rice.krad.uif.field.LabelField;
import org.kuali.rice.krad.uif.util.ComponentUtils;
/**
* Group that holds a collection of objects and configuration for presenting the
* collection in the UI. Supports functionality such as add line, line actions,
* and nested collections.
*
* <p>
* Note the standard header/footer can be used to give a header to the
* collection as a whole, or to provide actions that apply to the entire
* collection
* </p>
*
* <p>
* For binding purposes the binding path of each row field is indexed. The name
* property inherited from <code>ComponentBase</code> is used as the collection
* name. The collectionObjectClass property is used to lookup attributes from
* the data dictionary.
* </p>
*
* @author Kuali Rice Team ([email protected])
*/
public class CollectionGroup extends Group implements DataBinding {
private static final long serialVersionUID = -6496712566071542452L;
private Class<?> collectionObjectClass;
private String propertyName;
private BindingInfo bindingInfo;
private boolean renderAddLine;
private String addLinePropertyName;
private BindingInfo addLineBindingInfo;
private LabelField addLineLabelField;
private List<? extends Field> addLineFields;
private List<ActionField> addLineActionFields;
private boolean renderLineActions;
private List<ActionField> actionFields;
private boolean showHideInactiveButton;
private boolean showInactive;
private CollectionFilter activeCollectionFilter;
private List<CollectionGroup> subCollections;
private CollectionGroupBuilder collectionGroupBuilder;
public CollectionGroup() {
renderAddLine = true;
renderLineActions = true;
showInactive = false;
showHideInactiveButton = true;
actionFields = new ArrayList<ActionField>();
addLineFields = new ArrayList<Field>();
addLineActionFields = new ArrayList<ActionField>();
subCollections = new ArrayList<CollectionGroup>();
}
/**
* The following actions are performed:
*
* <ul>
* <li>Set fieldBindModelPath to the collection model path (since the fields
* have to belong to the same model as the collection)</li>
* <li>Set defaults for binding</li>
* <li>Default add line field list to groups items list</li>
* <li>Sets default active collection filter if not set</li>
* <li>Sets the dictionary entry (if blank) on each of the items to the
* collection class</li>
* </ul>
*
* @see org.kuali.rice.krad.uif.core.ComponentBase#performInitialization(org.kuali.rice.krad.uif.container.View)
*/
@Override
public void performInitialization(View view) {
setFieldBindingObjectPath(getBindingInfo().getBindingObjectPath());
super.performInitialization(view);
if (bindingInfo != null) {
bindingInfo.setDefaults(view, getPropertyName());
}
if (StringUtils.isNotBlank(getFieldBindByNamePrefix())) {
String bindByNamePrefixToSet = getFieldBindByNamePrefix();
if (StringUtils.isNotBlank(getBindingInfo().getBindByNamePrefix())) {
bindByNamePrefixToSet += "." + getBindingInfo().getBindByNamePrefix();
}
getBindingInfo().setBindByNamePrefix(bindByNamePrefixToSet);
}
if (addLineBindingInfo != null) {
// add line binds to model property
if (StringUtils.isNotBlank(addLinePropertyName)) {
addLineBindingInfo.setDefaults(view, getPropertyName());
addLineBindingInfo.setBindingName(addLinePropertyName);
if (StringUtils.isNotBlank(getFieldBindByNamePrefix())) {
addLineBindingInfo.setBindByNamePrefix(getFieldBindByNamePrefix());
}
}
}
for (Component item : getItems()) {
if (item instanceof AttributeField) {
AttributeField field = (AttributeField) item;
if (StringUtils.isBlank(field.getDictionaryObjectEntry())) {
field.setDictionaryObjectEntry(collectionObjectClass.getName());
}
}
}
if ((addLineFields == null) || addLineFields.isEmpty()) {
addLineFields = getItems();
}
// if active collection filter not set use default
if (this.activeCollectionFilter == null) {
activeCollectionFilter = new ActiveCollectionFilter();
}
// set static collection path on items
String collectionPath = "";
if (StringUtils.isNotBlank(getBindingInfo().getCollectionPath())) {
collectionPath += getBindingInfo().getCollectionPath() + ".";
}
if (StringUtils.isNotBlank(getBindingInfo().getBindByNamePrefix())) {
collectionPath += getBindingInfo().getBindByNamePrefix() + ".";
}
collectionPath += getBindingInfo().getBindingName();
List<AttributeField> collectionFields = ComponentUtils.getComponentsOfTypeDeep(getItems(), AttributeField.class);
for (AttributeField collectionField : collectionFields) {
collectionField.getBindingInfo().setCollectionPath(collectionPath);
}
for (CollectionGroup collectionGroup : getSubCollections()) {
collectionGroup.getBindingInfo().setCollectionPath(collectionPath);
view.getViewHelperService().performComponentInitialization(view, collectionGroup);
}
// add collection entry to abstract classes
if (!view.getAbstractTypeClasses().containsKey(collectionPath)) {
view.getAbstractTypeClasses().put(collectionPath, getCollectionObjectClass());
}
// initialize container items and sub-collections (since they are not in
// child list)
for (Component item : getItems()) {
view.getViewHelperService().performComponentInitialization(view, item);
}
}
/**
* Calls the configured <code>CollectionGroupBuilder</code> to build the
* necessary components based on the collection data
*
* @see org.kuali.rice.krad.uif.container.ContainerBase#performApplyModel(org.kuali.rice.krad.uif.container.View,
* java.lang.Object)
*/
@Override
public void performApplyModel(View view, Object model, Component parent) {
super.performApplyModel(view, model, parent);
pushCollectionGroupToReference();
getCollectionGroupBuilder().build(view, model, this);
pushCollectionGroupToReference();
}
/**
* Sets a reference in the context map for all nested components to the collection group
* instance, and sets name as parameter for an action fields in the group
*/
protected void pushCollectionGroupToReference() {
List<Component> components = this.getNestedComponents();
ComponentUtils
.pushObjectToContext(components, UifConstants.ContextVariableNames.COLLECTION_GROUP,
this);
List<ActionField> actionFields =
ComponentUtils.getComponentsOfTypeDeep(components, ActionField.class);
for (ActionField actionField : actionFields) {
actionField.addActionParameter(UifParameters.SELLECTED_COLLECTION_PATH,
this.getBindingInfo().getBindingPath());
}
}
/**
* Performs any filtering necessary on the collection before building the collection fields
*
* <p>
* If showInactive is set to false and the collection line type implements <code>Inactivatable</code>,
* invokes the active collection filer
* </p>
*
* @param model - object containing the views data, from which the collection will be pulled
*/
protected List<Integer> performCollectionFiltering(View view, Object model) {
if (Inactivatable.class.isAssignableFrom(this.collectionObjectClass) && !showInactive) {
return this.activeCollectionFilter.filter(view, model, this);
}else{
return null;
}
}
/**
* New collection lines are handled in the framework by maintaining a map on
* the form. The map contains as a key the collection name, and as value an
* instance of the collection type. An entry is created here for the
* collection represented by the <code>CollectionGroup</code> if an instance
* is not available (clearExistingLine will force a new instance). The given
* model must be a subclass of <code>UifFormBase</code> in order to find the
* Map.
*
* @param model
* - Model instance that contains the new collection lines Map
* @param clearExistingLine
* - boolean that indicates whether the line should be set to a
* new instance if it already exists
*/
public void initializeNewCollectionLine(View view, Object model, CollectionGroup collectionGroup,
boolean clearExistingLine) {
getCollectionGroupBuilder().initializeNewCollectionLine(view, model, collectionGroup, clearExistingLine);
}
/**
* @see org.kuali.rice.krad.uif.container.ContainerBase#getNestedComponents()
*/
@Override
public List<Component> getNestedComponents() {
List<Component> components = super.getNestedComponents();
components.add(addLineLabelField);
components.addAll(actionFields);
components.addAll(addLineActionFields);
// remove the containers items because we don't want them as children
// (they will become children of the layout manager as the rows are
// created)
// TODO: is this necessary?
for (Component item : getItems()) {
if (components.contains(item)) {
components.remove(item);
}
}
return components;
}
/**
* Object class the collection maintains. Used to get dictionary information
* in addition to creating new instances for the collection when necessary
*
* @return Class<?> collection object class
*/
public Class<?> getCollectionObjectClass() {
return this.collectionObjectClass;
}
/**
* Setter for the collection object class
*
* @param collectionObjectClass
*/
public void setCollectionObjectClass(Class<?> collectionObjectClass) {
this.collectionObjectClass = collectionObjectClass;
}
/**
* @see org.kuali.rice.krad.uif.core.DataBinding#getPropertyName()
*/
public String getPropertyName() {
return this.propertyName;
}
/**
* Setter for the collections property name
*
* @param propertyName
*/
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
/**
* Determines the binding path for the collection. Used to get the
* collection value from the model in addition to setting the binding path
* for the collection attributes
*
* @see org.kuali.rice.krad.uif.core.DataBinding#getBindingInfo()
*/
public BindingInfo getBindingInfo() {
return this.bindingInfo;
}
/**
* Setter for the binding info instance
*
* @param bindingInfo
*/
public void setBindingInfo(BindingInfo bindingInfo) {
this.bindingInfo = bindingInfo;
}
/**
* Action fields that should be rendered for each collection line. Example
* line action is the delete action
*
* @return List<ActionField> line action fields
*/
public List<ActionField> getActionFields() {
return this.actionFields;
}
/**
* Setter for the line action fields list
*
* @param actionFields
*/
public void setActionFields(List<ActionField> actionFields) {
this.actionFields = actionFields;
}
/**
* Indicates whether the action column for the collection should be rendered
*
* @return boolean true if the actions should be rendered, false if not
* @see #getActionFields()
*/
public boolean isRenderLineActions() {
return this.renderLineActions;
}
/**
* Setter for the render line actions indicator
*
* @param renderLineActions
*/
public void setRenderLineActions(boolean renderLineActions) {
this.renderLineActions = renderLineActions;
}
/**
* Indicates whether an add line should be rendered for the collection
*
* @return boolean true if add line should be rendered, false if it should
* not be
*/
public boolean isRenderAddLine() {
return this.renderAddLine;
}
/**
* Setter for the render add line indicator
*
* @param renderAddLine
*/
public void setRenderAddLine(boolean renderAddLine) {
this.renderAddLine = renderAddLine;
}
/**
* Convenience getter for the add line label field text. The text is used to
* label the add line when rendered and its placement depends on the
* <code>LayoutManager</code>.
* <p>
* For the <code>TableLayoutManager</code> the label appears in the sequence
* column to the left of the add line fields. For the
* <code>StackedLayoutManager</code> the label is placed into the group
* header for the line.
* </p>
*
* @return String add line label
*/
public String getAddLineLabel() {
if (getAddLineLabelField() != null) {
return getAddLineLabelField().getLabelText();
}
return null;
}
/**
* Setter for the add line label text
*
* @param addLineLabel
*/
public void setAddLineLabel(String addLineLabel) {
if (getAddLineLabelField() != null) {
getAddLineLabelField().setLabelText(addLineLabel);
}
}
/**
* <code>LabelField</code> instance for the add line label
*
* @return LabelField add line label field
* @see #getAddLineLabel()
*/
public LabelField getAddLineLabelField() {
return this.addLineLabelField;
}
/**
* Setter for the <code>LabelField</code> instance for the add line label
*
* @param addLineLabelField
* @see #getAddLineLabel()
*/
public void setAddLineLabelField(LabelField addLineLabelField) {
this.addLineLabelField = addLineLabelField;
}
/**
* Name of the property that contains an instance for the add line. If set
* this is used with the binding info to create the path to the add line.
* Can be left blank in which case the framework will manage the add line
* instance in a generic map.
*
* @return String add line property name
*/
public String getAddLinePropertyName() {
return this.addLinePropertyName;
}
/**
* Setter for the add line property name
*
* @param addLinePropertyName
*/
public void setAddLinePropertyName(String addLinePropertyName) {
this.addLinePropertyName = addLinePropertyName;
}
/**
* <code>BindingInfo</code> instance for the add line property used to
* determine the full binding path. If add line name given
* {@link #getAddLineLabel()} then it is set as the binding name on the
* binding info. Add line label and binding info are not required, in which
* case the framework will manage the new add line instances through a
* generic map (model must extend UifFormBase)
*
* @return BindingInfo add line binding info
*/
public BindingInfo getAddLineBindingInfo() {
return this.addLineBindingInfo;
}
/**
* Setter for the add line binding info
*
* @param addLineBindingInfo
*/
public void setAddLineBindingInfo(BindingInfo addLineBindingInfo) {
this.addLineBindingInfo = addLineBindingInfo;
}
/**
* List of <code>Field</code> instances that should be rendered for the
* collection add line (if enabled). If not set, the default group's items
* list will be used
*
* @return List<? extends Field> add line field list
*/
public List<? extends Field> getAddLineFields() {
return this.addLineFields;
}
/**
* Setter for the add line field list
*
* @param addLineFields
*/
public void setAddLineFields(List<? extends Field> addLineFields) {
this.addLineFields = addLineFields;
}
/**
* Action fields that should be rendered for the add line. This is generally
* the add action (button) but can be configured to contain additional
* actions
*
* @return List<ActionField> add line action fields
*/
public List<ActionField> getAddLineActionFields() {
return this.addLineActionFields;
}
/**
* Setter for the add line action fields
*
* @param addLineActionFields
*/
public void setAddLineActionFields(List<ActionField> addLineActionFields) {
this.addLineActionFields = addLineActionFields;
}
/**
* Indicates whether inactive collections lines should be displayed
*
* <p>
* Setting only applies when the collection line type implements the
* <code>Inactivatable</code> interface. If true and showInactive is
* set to false, the collection will be filtered to remove any items
* whose active status returns false
* </p>
*
* @return boolean true to show inactive records, false to not render inactive records
*/
public boolean isShowInactive() {
return showInactive;
}
/**
* Setter for the show inactive indicator
*
* @param boolean show inactive
*/
public void setShowInactive(boolean showInactive) {
this.showInactive = showInactive;
}
/**
* Collection filter instance for filtering the collection data when the
* showInactive flag is set to false
*
* @return CollectionFilter
*/
public CollectionFilter getActiveCollectionFilter() {
return activeCollectionFilter;
}
/**
* Setter for the collection filter to use for filter inactive records from the
* collection
*
* @param activeCollectionFilter - CollectionFilter instance
*/
public void setActiveCollectionFilter(CollectionFilter activeCollectionFilter) {
this.activeCollectionFilter = activeCollectionFilter;
}
/**
* List of <code>CollectionGroup</code> instances that are sub-collections
* of the collection represented by this collection group
*
* @return List<CollectionGroup> sub collections
*/
public List<CollectionGroup> getSubCollections() {
return this.subCollections;
}
/**
* Setter for the sub collection list
*
* @param subCollections
*/
public void setSubCollections(List<CollectionGroup> subCollections) {
this.subCollections = subCollections;
}
/**
* <code>CollectionGroupBuilder</code> instance that will build the
* components dynamically for the collection instance
*
* @return CollectionGroupBuilder instance
*/
public CollectionGroupBuilder getCollectionGroupBuilder() {
if (this.collectionGroupBuilder == null) {
this.collectionGroupBuilder = new CollectionGroupBuilder();
}
return this.collectionGroupBuilder;
}
/**
* Setter for the collection group building instance
*
* @param collectionGroupBuilder
*/
public void setCollectionGroupBuilder(CollectionGroupBuilder collectionGroupBuilder) {
this.collectionGroupBuilder = collectionGroupBuilder;
}
/**
* @see org.kuali.rice.krad.uif.container.ContainerBase#getItems()
*/
@SuppressWarnings("unchecked")
@Override
public List<? extends Field> getItems() {
return (List<? extends Field>) super.getItems();
}
/**
* @param showHideInactiveButton the showHideInactiveButton to set
*/
public void setShowHideInactiveButton(boolean showHideInactiveButton) {
this.showHideInactiveButton = showHideInactiveButton;
}
/**
* @return the showHideInactiveButton
*/
public boolean isShowHideInactiveButton() {
return showHideInactiveButton;
}
}
|
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/CollectionGroup.java
|
/*
* Copyright 2007 The Kuali Foundation Licensed under the Educational Community
* License, Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.opensource.org/licenses/ecl1.php Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.kuali.rice.krad.uif.container;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.mo.common.active.Inactivatable;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.uif.core.ActiveCollectionFilter;
import org.kuali.rice.krad.uif.core.BindingInfo;
import org.kuali.rice.krad.uif.core.CollectionFilter;
import org.kuali.rice.krad.uif.core.Component;
import org.kuali.rice.krad.uif.core.DataBinding;
import org.kuali.rice.krad.uif.field.ActionField;
import org.kuali.rice.krad.uif.field.AttributeField;
import org.kuali.rice.krad.uif.field.Field;
import org.kuali.rice.krad.uif.field.LabelField;
import org.kuali.rice.krad.uif.util.ComponentUtils;
/**
* Group that holds a collection of objects and configuration for presenting the
* collection in the UI. Supports functionality such as add line, line actions,
* and nested collections.
*
* <p>
* Note the standard header/footer can be used to give a header to the
* collection as a whole, or to provide actions that apply to the entire
* collection
* </p>
*
* <p>
* For binding purposes the binding path of each row field is indexed. The name
* property inherited from <code>ComponentBase</code> is used as the collection
* name. The collectionObjectClass property is used to lookup attributes from
* the data dictionary.
* </p>
*
* @author Kuali Rice Team ([email protected])
*/
public class CollectionGroup extends Group implements DataBinding {
private static final long serialVersionUID = -6496712566071542452L;
private Class<?> collectionObjectClass;
private String propertyName;
private BindingInfo bindingInfo;
private boolean renderAddLine;
private String addLinePropertyName;
private BindingInfo addLineBindingInfo;
private LabelField addLineLabelField;
private List<? extends Field> addLineFields;
private List<ActionField> addLineActionFields;
private boolean renderLineActions;
private List<ActionField> actionFields;
private boolean showHideInactiveButton;
private boolean showInactive;
private CollectionFilter activeCollectionFilter;
private List<CollectionGroup> subCollections;
private CollectionGroupBuilder collectionGroupBuilder;
public CollectionGroup() {
renderAddLine = true;
renderLineActions = true;
showInactive = false;
actionFields = new ArrayList<ActionField>();
addLineFields = new ArrayList<Field>();
addLineActionFields = new ArrayList<ActionField>();
subCollections = new ArrayList<CollectionGroup>();
}
/**
* The following actions are performed:
*
* <ul>
* <li>Set fieldBindModelPath to the collection model path (since the fields
* have to belong to the same model as the collection)</li>
* <li>Set defaults for binding</li>
* <li>Default add line field list to groups items list</li>
* <li>Sets default active collection filter if not set</li>
* <li>Sets the dictionary entry (if blank) on each of the items to the
* collection class</li>
* </ul>
*
* @see org.kuali.rice.krad.uif.core.ComponentBase#performInitialization(org.kuali.rice.krad.uif.container.View)
*/
@Override
public void performInitialization(View view) {
setFieldBindingObjectPath(getBindingInfo().getBindingObjectPath());
super.performInitialization(view);
if (bindingInfo != null) {
bindingInfo.setDefaults(view, getPropertyName());
}
if (StringUtils.isNotBlank(getFieldBindByNamePrefix())) {
String bindByNamePrefixToSet = getFieldBindByNamePrefix();
if (StringUtils.isNotBlank(getBindingInfo().getBindByNamePrefix())) {
bindByNamePrefixToSet += "." + getBindingInfo().getBindByNamePrefix();
}
getBindingInfo().setBindByNamePrefix(bindByNamePrefixToSet);
}
if (addLineBindingInfo != null) {
// add line binds to model property
if (StringUtils.isNotBlank(addLinePropertyName)) {
addLineBindingInfo.setDefaults(view, getPropertyName());
addLineBindingInfo.setBindingName(addLinePropertyName);
if (StringUtils.isNotBlank(getFieldBindByNamePrefix())) {
addLineBindingInfo.setBindByNamePrefix(getFieldBindByNamePrefix());
}
}
}
for (Component item : getItems()) {
if (item instanceof AttributeField) {
AttributeField field = (AttributeField) item;
if (StringUtils.isBlank(field.getDictionaryObjectEntry())) {
field.setDictionaryObjectEntry(collectionObjectClass.getName());
}
}
}
if ((addLineFields == null) || addLineFields.isEmpty()) {
addLineFields = getItems();
}
// if active collection filter not set use default
if (this.activeCollectionFilter == null) {
activeCollectionFilter = new ActiveCollectionFilter();
}
// set static collection path on items
String collectionPath = "";
if (StringUtils.isNotBlank(getBindingInfo().getCollectionPath())) {
collectionPath += getBindingInfo().getCollectionPath() + ".";
}
if (StringUtils.isNotBlank(getBindingInfo().getBindByNamePrefix())) {
collectionPath += getBindingInfo().getBindByNamePrefix() + ".";
}
collectionPath += getBindingInfo().getBindingName();
List<AttributeField> collectionFields = ComponentUtils.getComponentsOfTypeDeep(getItems(), AttributeField.class);
for (AttributeField collectionField : collectionFields) {
collectionField.getBindingInfo().setCollectionPath(collectionPath);
}
for (CollectionGroup collectionGroup : getSubCollections()) {
collectionGroup.getBindingInfo().setCollectionPath(collectionPath);
view.getViewHelperService().performComponentInitialization(view, collectionGroup);
}
// add collection entry to abstract classes
if (!view.getAbstractTypeClasses().containsKey(collectionPath)) {
view.getAbstractTypeClasses().put(collectionPath, getCollectionObjectClass());
}
// initialize container items and sub-collections (since they are not in
// child list)
for (Component item : getItems()) {
view.getViewHelperService().performComponentInitialization(view, item);
}
}
/**
* Calls the configured <code>CollectionGroupBuilder</code> to build the
* necessary components based on the collection data
*
* @see org.kuali.rice.krad.uif.container.ContainerBase#performApplyModel(org.kuali.rice.krad.uif.container.View,
* java.lang.Object)
*/
@Override
public void performApplyModel(View view, Object model, Component parent) {
super.performApplyModel(view, model, parent);
pushCollectionGroupToReference();
getCollectionGroupBuilder().build(view, model, this);
pushCollectionGroupToReference();
}
/**
* Sets a reference in the context map for all nested components to the collection group
* instance, and sets name as parameter for an action fields in the group
*/
protected void pushCollectionGroupToReference() {
List<Component> components = this.getNestedComponents();
ComponentUtils
.pushObjectToContext(components, UifConstants.ContextVariableNames.COLLECTION_GROUP,
this);
List<ActionField> actionFields =
ComponentUtils.getComponentsOfTypeDeep(components, ActionField.class);
for (ActionField actionField : actionFields) {
actionField.addActionParameter(UifParameters.SELLECTED_COLLECTION_PATH,
this.getBindingInfo().getBindingPath());
}
}
/**
* Performs any filtering necessary on the collection before building the collection fields
*
* <p>
* If showInactive is set to false and the collection line type implements <code>Inactivatable</code>,
* invokes the active collection filer
* </p>
*
* @param model - object containing the views data, from which the collection will be pulled
*/
protected List<Integer> performCollectionFiltering(View view, Object model) {
if (Inactivatable.class.isAssignableFrom(this.collectionObjectClass) && !showInactive) {
return this.activeCollectionFilter.filter(view, model, this);
}else{
return null;
}
}
/**
* New collection lines are handled in the framework by maintaining a map on
* the form. The map contains as a key the collection name, and as value an
* instance of the collection type. An entry is created here for the
* collection represented by the <code>CollectionGroup</code> if an instance
* is not available (clearExistingLine will force a new instance). The given
* model must be a subclass of <code>UifFormBase</code> in order to find the
* Map.
*
* @param model
* - Model instance that contains the new collection lines Map
* @param clearExistingLine
* - boolean that indicates whether the line should be set to a
* new instance if it already exists
*/
public void initializeNewCollectionLine(View view, Object model, CollectionGroup collectionGroup,
boolean clearExistingLine) {
getCollectionGroupBuilder().initializeNewCollectionLine(view, model, collectionGroup, clearExistingLine);
}
/**
* @see org.kuali.rice.krad.uif.container.ContainerBase#getNestedComponents()
*/
@Override
public List<Component> getNestedComponents() {
List<Component> components = super.getNestedComponents();
components.add(addLineLabelField);
components.addAll(actionFields);
components.addAll(addLineActionFields);
// remove the containers items because we don't want them as children
// (they will become children of the layout manager as the rows are
// created)
// TODO: is this necessary?
for (Component item : getItems()) {
if (components.contains(item)) {
components.remove(item);
}
}
return components;
}
/**
* Object class the collection maintains. Used to get dictionary information
* in addition to creating new instances for the collection when necessary
*
* @return Class<?> collection object class
*/
public Class<?> getCollectionObjectClass() {
return this.collectionObjectClass;
}
/**
* Setter for the collection object class
*
* @param collectionObjectClass
*/
public void setCollectionObjectClass(Class<?> collectionObjectClass) {
this.collectionObjectClass = collectionObjectClass;
}
/**
* @see org.kuali.rice.krad.uif.core.DataBinding#getPropertyName()
*/
public String getPropertyName() {
return this.propertyName;
}
/**
* Setter for the collections property name
*
* @param propertyName
*/
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
/**
* Determines the binding path for the collection. Used to get the
* collection value from the model in addition to setting the binding path
* for the collection attributes
*
* @see org.kuali.rice.krad.uif.core.DataBinding#getBindingInfo()
*/
public BindingInfo getBindingInfo() {
return this.bindingInfo;
}
/**
* Setter for the binding info instance
*
* @param bindingInfo
*/
public void setBindingInfo(BindingInfo bindingInfo) {
this.bindingInfo = bindingInfo;
}
/**
* Action fields that should be rendered for each collection line. Example
* line action is the delete action
*
* @return List<ActionField> line action fields
*/
public List<ActionField> getActionFields() {
return this.actionFields;
}
/**
* Setter for the line action fields list
*
* @param actionFields
*/
public void setActionFields(List<ActionField> actionFields) {
this.actionFields = actionFields;
}
/**
* Indicates whether the action column for the collection should be rendered
*
* @return boolean true if the actions should be rendered, false if not
* @see #getActionFields()
*/
public boolean isRenderLineActions() {
return this.renderLineActions;
}
/**
* Setter for the render line actions indicator
*
* @param renderLineActions
*/
public void setRenderLineActions(boolean renderLineActions) {
this.renderLineActions = renderLineActions;
}
/**
* Indicates whether an add line should be rendered for the collection
*
* @return boolean true if add line should be rendered, false if it should
* not be
*/
public boolean isRenderAddLine() {
return this.renderAddLine;
}
/**
* Setter for the render add line indicator
*
* @param renderAddLine
*/
public void setRenderAddLine(boolean renderAddLine) {
this.renderAddLine = renderAddLine;
}
/**
* Convenience getter for the add line label field text. The text is used to
* label the add line when rendered and its placement depends on the
* <code>LayoutManager</code>.
* <p>
* For the <code>TableLayoutManager</code> the label appears in the sequence
* column to the left of the add line fields. For the
* <code>StackedLayoutManager</code> the label is placed into the group
* header for the line.
* </p>
*
* @return String add line label
*/
public String getAddLineLabel() {
if (getAddLineLabelField() != null) {
return getAddLineLabelField().getLabelText();
}
return null;
}
/**
* Setter for the add line label text
*
* @param addLineLabel
*/
public void setAddLineLabel(String addLineLabel) {
if (getAddLineLabelField() != null) {
getAddLineLabelField().setLabelText(addLineLabel);
}
}
/**
* <code>LabelField</code> instance for the add line label
*
* @return LabelField add line label field
* @see #getAddLineLabel()
*/
public LabelField getAddLineLabelField() {
return this.addLineLabelField;
}
/**
* Setter for the <code>LabelField</code> instance for the add line label
*
* @param addLineLabelField
* @see #getAddLineLabel()
*/
public void setAddLineLabelField(LabelField addLineLabelField) {
this.addLineLabelField = addLineLabelField;
}
/**
* Name of the property that contains an instance for the add line. If set
* this is used with the binding info to create the path to the add line.
* Can be left blank in which case the framework will manage the add line
* instance in a generic map.
*
* @return String add line property name
*/
public String getAddLinePropertyName() {
return this.addLinePropertyName;
}
/**
* Setter for the add line property name
*
* @param addLinePropertyName
*/
public void setAddLinePropertyName(String addLinePropertyName) {
this.addLinePropertyName = addLinePropertyName;
}
/**
* <code>BindingInfo</code> instance for the add line property used to
* determine the full binding path. If add line name given
* {@link #getAddLineLabel()} then it is set as the binding name on the
* binding info. Add line label and binding info are not required, in which
* case the framework will manage the new add line instances through a
* generic map (model must extend UifFormBase)
*
* @return BindingInfo add line binding info
*/
public BindingInfo getAddLineBindingInfo() {
return this.addLineBindingInfo;
}
/**
* Setter for the add line binding info
*
* @param addLineBindingInfo
*/
public void setAddLineBindingInfo(BindingInfo addLineBindingInfo) {
this.addLineBindingInfo = addLineBindingInfo;
}
/**
* List of <code>Field</code> instances that should be rendered for the
* collection add line (if enabled). If not set, the default group's items
* list will be used
*
* @return List<? extends Field> add line field list
*/
public List<? extends Field> getAddLineFields() {
return this.addLineFields;
}
/**
* Setter for the add line field list
*
* @param addLineFields
*/
public void setAddLineFields(List<? extends Field> addLineFields) {
this.addLineFields = addLineFields;
}
/**
* Action fields that should be rendered for the add line. This is generally
* the add action (button) but can be configured to contain additional
* actions
*
* @return List<ActionField> add line action fields
*/
public List<ActionField> getAddLineActionFields() {
return this.addLineActionFields;
}
/**
* Setter for the add line action fields
*
* @param addLineActionFields
*/
public void setAddLineActionFields(List<ActionField> addLineActionFields) {
this.addLineActionFields = addLineActionFields;
}
/**
* Indicates whether inactive collections lines should be displayed
*
* <p>
* Setting only applies when the collection line type implements the
* <code>Inactivatable</code> interface. If true and showInactive is
* set to false, the collection will be filtered to remove any items
* whose active status returns false
* </p>
*
* @return boolean true to show inactive records, false to not render inactive records
*/
public boolean isShowInactive() {
return showInactive;
}
/**
* Setter for the show inactive indicator
*
* @param boolean show inactive
*/
public void setShowInactive(boolean showInactive) {
this.showInactive = showInactive;
}
/**
* Collection filter instance for filtering the collection data when the
* showInactive flag is set to false
*
* @return CollectionFilter
*/
public CollectionFilter getActiveCollectionFilter() {
return activeCollectionFilter;
}
/**
* Setter for the collection filter to use for filter inactive records from the
* collection
*
* @param activeCollectionFilter - CollectionFilter instance
*/
public void setActiveCollectionFilter(CollectionFilter activeCollectionFilter) {
this.activeCollectionFilter = activeCollectionFilter;
}
/**
* List of <code>CollectionGroup</code> instances that are sub-collections
* of the collection represented by this collection group
*
* @return List<CollectionGroup> sub collections
*/
public List<CollectionGroup> getSubCollections() {
return this.subCollections;
}
/**
* Setter for the sub collection list
*
* @param subCollections
*/
public void setSubCollections(List<CollectionGroup> subCollections) {
this.subCollections = subCollections;
}
/**
* <code>CollectionGroupBuilder</code> instance that will build the
* components dynamically for the collection instance
*
* @return CollectionGroupBuilder instance
*/
public CollectionGroupBuilder getCollectionGroupBuilder() {
if (this.collectionGroupBuilder == null) {
this.collectionGroupBuilder = new CollectionGroupBuilder();
}
return this.collectionGroupBuilder;
}
/**
* Setter for the collection group building instance
*
* @param collectionGroupBuilder
*/
public void setCollectionGroupBuilder(CollectionGroupBuilder collectionGroupBuilder) {
this.collectionGroupBuilder = collectionGroupBuilder;
}
/**
* @see org.kuali.rice.krad.uif.container.ContainerBase#getItems()
*/
@SuppressWarnings("unchecked")
@Override
public List<? extends Field> getItems() {
return (List<? extends Field>) super.getItems();
}
/**
* @param showHideInactiveButton the showHideInactiveButton to set
*/
public void setShowHideInactiveButton(boolean showHideInactiveButton) {
this.showHideInactiveButton = showHideInactiveButton;
}
/**
* @return the showHideInactiveButton
*/
public boolean isShowHideInactiveButton() {
return showHideInactiveButton;
}
}
|
KULRICE-5256 : Default the showHideInactiveButton flag to true.
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@21674 7a7aa7f6-c479-11dc-97e2-85a2497f191d
|
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/CollectionGroup.java
|
KULRICE-5256 : Default the showHideInactiveButton flag to true.
|
<ide><path>rad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/CollectionGroup.java
<ide> renderAddLine = true;
<ide> renderLineActions = true;
<ide> showInactive = false;
<add> showHideInactiveButton = true;
<ide>
<ide> actionFields = new ArrayList<ActionField>();
<ide> addLineFields = new ArrayList<Field>();
|
|
Java
|
apache-2.0
|
8eee7061808237798f4941f339ac53aff4ecf904
| 0 |
kelemen/JTrim,kelemen/JTrim
|
package org.jtrim.event;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.jtrim.collections.RefCollection;
import org.jtrim.collections.RefLinkedList;
import org.jtrim.collections.RefList;
import org.jtrim.utils.ExceptionHelper;
/**
* An {@link EventHandlerContainer} implementation which creates a copy of the
* currently registered listeners when dispatching events. That is, in the
* {@link #onEvent(EventDispatcher, java.lang.Object) onEvent} method, it first
* creates copy of the currently added listeners as done by the
* {@link #getListeners() getListeners()} method and then dispatches the event
* to all of them.
* <P>
* This implementation allows to register the same listener multiple times and
* listeners registered multiple times will be notified multiple times as well
* when dispatching events.
* <P>
* Adding and removing listeners are constant time operations but, of course,
* dispatching events requires linear time in the number of registered
* listeners (plus the time the listeners need).
*
* <h3>Thread safety</h3>
* As required by {@code EventHandlerContainer}, the methods of this class are
* safe to be accessed concurrently by multiple threads.
*
* <h4>Synchronization transparency</h4>
* As required by {@code EventHandlerContainer}, except for the {@code onEvent}
* method, methods of this class are <I>synchronization transparent</I>.
*
* @param <ListenerType> the type of the event handlers can possibly be added
* to the container
* @param <ArgType> the type of the argument which can be passed to event
* handlers by the {@code onEvent} method
*
* @author Kelemen Attila
*/
public final class CopyOnTriggerEventHandlerContainer<ListenerType, ArgType>
implements
EventHandlerContainer<ListenerType, ArgType> {
private final Lock readLock;
private final Lock writeLock;
private final RefList<ListenerType> listeners;
/**
* Creates a new {@code CopyOnTriggerEventHandlerContainer} with no
* listeners registered.
*/
public CopyOnTriggerEventHandlerContainer() {
ReadWriteLock listenerLock = new ReentrantReadWriteLock();
this.readLock = listenerLock.readLock();
this.writeLock = listenerLock.writeLock();
this.listeners = new RefLinkedList<>();
}
/**
* {@inheritDoc }
* <P>
* <B>Implementation note</B>: Adding and removing (using the returned
* reference) a listener is a constant time operation.
*/
@Override
public ListenerRef<ListenerType> registerListener(ListenerType listener) {
ExceptionHelper.checkNotNullArgument(listener, "listener");
RefCollection.ElementRef<ListenerType> listenerRef;
writeLock.lock();
try {
listenerRef = listeners.addGetReference(listener);
} finally {
writeLock.unlock();
}
return new CollectionBasedListenerRef<>(readLock, writeLock, listenerRef);
}
/**
* {@inheritDoc }
* <P>
* <B>Implementation note</B>: In case an exception is thrown by a
* registered listener, other listeners will still be invoked. After
* notifying all the listeners, the first exception thrown by the listeners
* will be rethrown by this method suppressing all other exceptions (i.e.:
* adding them as {@link Throwable#addSuppressed(Throwable) suppressed}
* exceptions to the thrown exception).
*/
@Override
public void onEvent(
EventDispatcher<? super ListenerType, ? super ArgType> eventDispatcher,
ArgType arg) {
ExceptionHelper.checkNotNullArgument(eventDispatcher, "eventDispatcher");
Throwable error = null;
for (ListenerType listener: getListeners()) {
try {
eventDispatcher.onEvent(listener, arg);
} catch (Throwable ex) {
if (error == null) {
error = ex;
}
else {
error.addSuppressed(ex);
}
}
}
if (error != null) {
ExceptionHelper.rethrow(error);
}
}
/**
* {@inheritDoc }
* <P>
* <B>Implementation note</B>: Retrieving the listeners is a linear time
* operation in the number of registered listeners.
*/
@Override
public Collection<ListenerType> getListeners() {
readLock.lock();
try {
return listeners.isEmpty()
? Collections.<ListenerType>emptySet()
: new ArrayList<>(listeners);
} finally {
readLock.unlock();
}
}
/**
* {@inheritDoc }
* <P>
* <B>Implementation note</B>: Retrieving the number of listeners is a
* constant time operation.
*/
@Override
public int getListenerCount() {
readLock.lock();
try {
return listeners.size();
} finally {
readLock.unlock();
}
}
private static class CollectionBasedListenerRef<ListenerType>
implements
ListenerRef<ListenerType> {
private final Lock readLock;
private final Lock writeLock;
private final RefCollection.ElementRef<ListenerType> listenerRef;
public CollectionBasedListenerRef(Lock readLock, Lock writeLock,
RefCollection.ElementRef<ListenerType> listenerRef) {
assert readLock != null;
assert writeLock != null;
assert listenerRef != null;
this.readLock = readLock;
this.writeLock = writeLock;
this.listenerRef = listenerRef;
}
@Override
public boolean isRegistered() {
readLock.lock();
try {
return !listenerRef.isRemoved();
} finally {
readLock.unlock();
}
}
@Override
public void unregister() {
writeLock.lock();
try {
listenerRef.remove();
} finally {
writeLock.unlock();
}
}
@Override
public ListenerType getListener() {
readLock.lock();
try {
return listenerRef.getElement();
} finally {
readLock.unlock();
}
}
}
}
|
JTrim/src/main/java/org/jtrim/event/CopyOnTriggerEventHandlerContainer.java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jtrim.event;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.jtrim.collections.RefCollection;
import org.jtrim.collections.RefLinkedList;
import org.jtrim.collections.RefList;
import org.jtrim.utils.ExceptionHelper;
/**
*
* @author Kelemen Attila
*/
public final class CopyOnTriggerEventHandlerContainer<ListenerType, ArgType>
implements
EventHandlerContainer<ListenerType, ArgType> {
private final Lock readLock;
private final Lock writeLock;
private final RefList<ListenerType> listeners;
public CopyOnTriggerEventHandlerContainer() {
ReadWriteLock listenerLock = new ReentrantReadWriteLock();
this.readLock = listenerLock.readLock();
this.writeLock = listenerLock.writeLock();
this.listeners = new RefLinkedList<>();
}
@Override
public ListenerRef<ListenerType> registerListener(ListenerType listener) {
ExceptionHelper.checkNotNullArgument(listener, "listener");
RefCollection.ElementRef<ListenerType> listenerRef;
writeLock.lock();
try {
listenerRef = listeners.addGetReference(listener);
} finally {
writeLock.unlock();
}
return new CollectionBasedListenerRef<>(readLock, writeLock, listenerRef);
}
@Override
public void onEvent(
EventDispatcher<? super ListenerType, ? super ArgType> eventDispatcher,
ArgType arg) {
ExceptionHelper.checkNotNullArgument(eventDispatcher, "eventDispatcher");
Throwable error = null;
for (ListenerType listener: getListeners()) {
try {
eventDispatcher.onEvent(listener, arg);
} catch (Throwable ex) {
if (error == null) {
error = ex;
}
else {
error.addSuppressed(ex);
}
}
}
if (error != null) {
ExceptionHelper.rethrow(error);
}
}
@Override
public Collection<ListenerType> getListeners() {
readLock.lock();
try {
return listeners.isEmpty()
? Collections.<ListenerType>emptySet()
: new ArrayList<>(listeners);
} finally {
readLock.unlock();
}
}
@Override
public int getListenerCount() {
readLock.lock();
try {
return listeners.size();
} finally {
readLock.unlock();
}
}
private static class CollectionBasedListenerRef<ListenerType>
implements
ListenerRef<ListenerType> {
private final Lock readLock;
private final Lock writeLock;
private final RefCollection.ElementRef<ListenerType> listenerRef;
public CollectionBasedListenerRef(Lock readLock, Lock writeLock,
RefCollection.ElementRef<ListenerType> listenerRef) {
assert readLock != null;
assert writeLock != null;
assert listenerRef != null;
this.readLock = readLock;
this.writeLock = writeLock;
this.listenerRef = listenerRef;
}
@Override
public boolean isRegistered() {
readLock.lock();
try {
return !listenerRef.isRemoved();
} finally {
readLock.unlock();
}
}
@Override
public void unregister() {
writeLock.lock();
try {
listenerRef.remove();
} finally {
writeLock.unlock();
}
}
@Override
public ListenerType getListener() {
readLock.lock();
try {
return listenerRef.getElement();
} finally {
readLock.unlock();
}
}
}
}
|
- Documented CopyOnTriggerEventHandlerContainer
|
JTrim/src/main/java/org/jtrim/event/CopyOnTriggerEventHandlerContainer.java
|
- Documented CopyOnTriggerEventHandlerContainer
|
<ide><path>Trim/src/main/java/org/jtrim/event/CopyOnTriggerEventHandlerContainer.java
<del>/*
<del> * To change this template, choose Tools | Templates
<del> * and open the template in the editor.
<del> */
<del>
<ide> package org.jtrim.event;
<ide>
<ide> import java.util.ArrayList;
<ide> import org.jtrim.utils.ExceptionHelper;
<ide>
<ide> /**
<add> * An {@link EventHandlerContainer} implementation which creates a copy of the
<add> * currently registered listeners when dispatching events. That is, in the
<add> * {@link #onEvent(EventDispatcher, java.lang.Object) onEvent} method, it first
<add> * creates copy of the currently added listeners as done by the
<add> * {@link #getListeners() getListeners()} method and then dispatches the event
<add> * to all of them.
<add> * <P>
<add> * This implementation allows to register the same listener multiple times and
<add> * listeners registered multiple times will be notified multiple times as well
<add> * when dispatching events.
<add> * <P>
<add> * Adding and removing listeners are constant time operations but, of course,
<add> * dispatching events requires linear time in the number of registered
<add> * listeners (plus the time the listeners need).
<add> *
<add> * <h3>Thread safety</h3>
<add> * As required by {@code EventHandlerContainer}, the methods of this class are
<add> * safe to be accessed concurrently by multiple threads.
<add> *
<add> * <h4>Synchronization transparency</h4>
<add> * As required by {@code EventHandlerContainer}, except for the {@code onEvent}
<add> * method, methods of this class are <I>synchronization transparent</I>.
<add> *
<add> * @param <ListenerType> the type of the event handlers can possibly be added
<add> * to the container
<add> * @param <ArgType> the type of the argument which can be passed to event
<add> * handlers by the {@code onEvent} method
<ide> *
<ide> * @author Kelemen Attila
<ide> */
<ide> private final Lock writeLock;
<ide> private final RefList<ListenerType> listeners;
<ide>
<add> /**
<add> * Creates a new {@code CopyOnTriggerEventHandlerContainer} with no
<add> * listeners registered.
<add> */
<ide> public CopyOnTriggerEventHandlerContainer() {
<ide> ReadWriteLock listenerLock = new ReentrantReadWriteLock();
<ide> this.readLock = listenerLock.readLock();
<ide> this.listeners = new RefLinkedList<>();
<ide> }
<ide>
<add> /**
<add> * {@inheritDoc }
<add> * <P>
<add> * <B>Implementation note</B>: Adding and removing (using the returned
<add> * reference) a listener is a constant time operation.
<add> */
<ide> @Override
<ide> public ListenerRef<ListenerType> registerListener(ListenerType listener) {
<ide> ExceptionHelper.checkNotNullArgument(listener, "listener");
<ide> return new CollectionBasedListenerRef<>(readLock, writeLock, listenerRef);
<ide> }
<ide>
<add> /**
<add> * {@inheritDoc }
<add> * <P>
<add> * <B>Implementation note</B>: In case an exception is thrown by a
<add> * registered listener, other listeners will still be invoked. After
<add> * notifying all the listeners, the first exception thrown by the listeners
<add> * will be rethrown by this method suppressing all other exceptions (i.e.:
<add> * adding them as {@link Throwable#addSuppressed(Throwable) suppressed}
<add> * exceptions to the thrown exception).
<add> */
<ide> @Override
<ide> public void onEvent(
<ide> EventDispatcher<? super ListenerType, ? super ArgType> eventDispatcher,
<ide> }
<ide> }
<ide>
<add> /**
<add> * {@inheritDoc }
<add> * <P>
<add> * <B>Implementation note</B>: Retrieving the listeners is a linear time
<add> * operation in the number of registered listeners.
<add> */
<ide> @Override
<ide> public Collection<ListenerType> getListeners() {
<ide> readLock.lock();
<ide> }
<ide> }
<ide>
<add> /**
<add> * {@inheritDoc }
<add> * <P>
<add> * <B>Implementation note</B>: Retrieving the number of listeners is a
<add> * constant time operation.
<add> */
<ide> @Override
<ide> public int getListenerCount() {
<ide> readLock.lock();
|
|
Java
|
apache-2.0
|
e97f751d50f34b7991ff273d8b5e503e2b474f53
| 0 |
joserabal/sakai,pushyamig/sakai,introp-software/sakai,buckett/sakai-gitflow,whumph/sakai,surya-janani/sakai,noondaysun/sakai,udayg/sakai,rodriguezdevera/sakai,frasese/sakai,joserabal/sakai,colczr/sakai,whumph/sakai,surya-janani/sakai,liubo404/sakai,pushyamig/sakai,tl-its-umich-edu/sakai,colczr/sakai,zqian/sakai,liubo404/sakai,kwedoff1/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,puramshetty/sakai,buckett/sakai-gitflow,wfuedu/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,ouit0408/sakai,bkirschn/sakai,willkara/sakai,wfuedu/sakai,lorenamgUMU/sakai,noondaysun/sakai,kingmook/sakai,frasese/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,wfuedu/sakai,wfuedu/sakai,kingmook/sakai,surya-janani/sakai,noondaysun/sakai,noondaysun/sakai,puramshetty/sakai,lorenamgUMU/sakai,joserabal/sakai,kingmook/sakai,hackbuteer59/sakai,bkirschn/sakai,kwedoff1/sakai,bkirschn/sakai,Fudan-University/sakai,lorenamgUMU/sakai,zqian/sakai,surya-janani/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,colczr/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,OpenCollabZA/sakai,puramshetty/sakai,conder/sakai,bkirschn/sakai,bzhouduke123/sakai,kingmook/sakai,udayg/sakai,ouit0408/sakai,bzhouduke123/sakai,whumph/sakai,bkirschn/sakai,frasese/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,kingmook/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,liubo404/sakai,liubo404/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,ktakacs/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,willkara/sakai,rodriguezdevera/sakai,pushyamig/sakai,kwedoff1/sakai,conder/sakai,bzhouduke123/sakai,joserabal/sakai,buckett/sakai-gitflow,lorenamgUMU/sakai,surya-janani/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,pushyamig/sakai,whumph/sakai,bkirschn/sakai,ouit0408/sakai,clhedrick/sakai,puramshetty/sakai,clhedrick/sakai,clhedrick/sakai,whumph/sakai,frasese/sakai,udayg/sakai,bzhouduke123/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,zqian/sakai,kwedoff1/sakai,liubo404/sakai,joserabal/sakai,kwedoff1/sakai,kwedoff1/sakai,whumph/sakai,rodriguezdevera/sakai,frasese/sakai,colczr/sakai,introp-software/sakai,ktakacs/sakai,introp-software/sakai,bzhouduke123/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,willkara/sakai,willkara/sakai,bkirschn/sakai,conder/sakai,udayg/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,kwedoff1/sakai,clhedrick/sakai,introp-software/sakai,ktakacs/sakai,frasese/sakai,colczr/sakai,whumph/sakai,joserabal/sakai,conder/sakai,rodriguezdevera/sakai,ktakacs/sakai,zqian/sakai,kingmook/sakai,joserabal/sakai,udayg/sakai,hackbuteer59/sakai,conder/sakai,udayg/sakai,tl-its-umich-edu/sakai,introp-software/sakai,lorenamgUMU/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,noondaysun/sakai,willkara/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,zqian/sakai,zqian/sakai,introp-software/sakai,liubo404/sakai,introp-software/sakai,Fudan-University/sakai,surya-janani/sakai,conder/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,hackbuteer59/sakai,ktakacs/sakai,clhedrick/sakai,OpenCollabZA/sakai,introp-software/sakai,ktakacs/sakai,pushyamig/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,zqian/sakai,colczr/sakai,willkara/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,colczr/sakai,noondaysun/sakai,wfuedu/sakai,willkara/sakai,wfuedu/sakai,lorenamgUMU/sakai,OpenCollabZA/sakai,rodriguezdevera/sakai,udayg/sakai,conder/sakai,kingmook/sakai,whumph/sakai,zqian/sakai,puramshetty/sakai,bkirschn/sakai,noondaysun/sakai,Fudan-University/sakai,ouit0408/sakai,Fudan-University/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,willkara/sakai,conder/sakai,rodriguezdevera/sakai,udayg/sakai,clhedrick/sakai,joserabal/sakai,kwedoff1/sakai,Fudan-University/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,pushyamig/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,liubo404/sakai,noondaysun/sakai,frasese/sakai,clhedrick/sakai,rodriguezdevera/sakai,Fudan-University/sakai,wfuedu/sakai,kingmook/sakai,hackbuteer59/sakai,pushyamig/sakai,Fudan-University/sakai,ktakacs/sakai,frasese/sakai
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the"License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.ui.listener.author;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.facade.SectionFacade;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.author.AssessmentBean;
import org.sakaiproject.tool.assessment.ui.bean.author.ItemAuthorBean;
import org.sakaiproject.tool.assessment.ui.bean.author.SectionBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
/**
* <p>Title: Samigo</p>
* <p>Description: Sakai Assessment Manager</p>
* <p>Copyright: Copyright (c) 2004 Sakai Project</p>
* <p>Organization: Sakai Project</p>
* @author Ed Smiley
* @version $Id$
*/
public class AuthorPartListener implements ActionListener
{
private static Log log = LogFactory.getLog(AuthorPartListener.class);
private static ContextUtil cu;
public AuthorPartListener()
{
}
public void processAction(ActionEvent ae) throws AbortProcessingException
{
FacesContext context = FacesContext.getCurrentInstance();
Map reqMap = context.getExternalContext().getRequestMap();
Map requestParams = context.getExternalContext().getRequestParameterMap();
// #1a. prepare sectionBean
AssessmentBean assessmentBean = (AssessmentBean) cu.lookupBean(
"assessmentBean");
ItemAuthorBean itemauthorbean = (ItemAuthorBean) cu.lookupBean("itemauthor");
SectionBean sectionBean = (SectionBean) cu.lookupBean(
"sectionBean");
// clean it
sectionBean.setSectionTitle("");
sectionBean.setAssessmentTitle(assessmentBean.getTitle());
sectionBean.setSectionDescription("");
sectionBean.setSectionId("");
String assessmentId = assessmentBean.getAssessmentId();
// #1b. goto editPart.jsp
//sectionBean.setPoolsAvailable(itemauthorbean.getPoolSelectList());
sectionBean.setHideRandom(false);
sectionBean.setNumberSelected("");
sectionBean.setSelectedPool("");
// new part has no attachment
sectionBean.setAttachmentList(null);
sectionBean.setHasAttachment(false);
// set default
sectionBean.setType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE.toString());
sectionBean.setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE.toString());
log.debug("**** sectionBean.getTitle="+sectionBean.getSectionTitle());
}
}
|
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/AuthorPartListener.java
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the"License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.ui.listener.author;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.facade.SectionFacade;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.author.AssessmentBean;
import org.sakaiproject.tool.assessment.ui.bean.author.ItemAuthorBean;
import org.sakaiproject.tool.assessment.ui.bean.author.SectionBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
/**
* <p>Title: Samigo</p>
* <p>Description: Sakai Assessment Manager</p>
* <p>Copyright: Copyright (c) 2004 Sakai Project</p>
* <p>Organization: Sakai Project</p>
* @author Ed Smiley
* @version $Id$
*/
public class AuthorPartListener implements ActionListener
{
private static Log log = LogFactory.getLog(AuthorPartListener.class);
private static ContextUtil cu;
public AuthorPartListener()
{
}
public void processAction(ActionEvent ae) throws AbortProcessingException
{
FacesContext context = FacesContext.getCurrentInstance();
Map reqMap = context.getExternalContext().getRequestMap();
Map requestParams = context.getExternalContext().getRequestParameterMap();
// #1a. prepare sectionBean
AssessmentBean assessmentBean = (AssessmentBean) cu.lookupBean(
"assessmentBean");
ItemAuthorBean itemauthorbean = (ItemAuthorBean) cu.lookupBean("itemauthor");
SectionBean sectionBean = (SectionBean) cu.lookupBean(
"sectionBean");
// clean it
sectionBean.setSectionTitle("");
sectionBean.setAssessmentTitle(assessmentBean.getTitle());
sectionBean.setSectionDescription("");
sectionBean.setSectionId("");
String assessmentId = assessmentBean.getAssessmentId();
// #1b. goto editPart.jsp
//sectionBean.setPoolsAvailable(itemauthorbean.getPoolSelectList());
sectionBean.setHideRandom(false);
sectionBean.setNumberSelected("");
sectionBean.setSelectedPool("");
// set default
sectionBean.setType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE.toString());
sectionBean.setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE.toString());
log.debug("**** sectionBean.getTitle="+sectionBean.getSectionTitle());
}
}
|
SAK-6506
git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@15683 66ffb92e-73f9-0310-93c1-f5514f145a0a
|
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/AuthorPartListener.java
|
SAK-6506
|
<ide><path>amigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/AuthorPartListener.java
<ide> sectionBean.setHideRandom(false);
<ide> sectionBean.setNumberSelected("");
<ide> sectionBean.setSelectedPool("");
<add> // new part has no attachment
<add> sectionBean.setAttachmentList(null);
<add> sectionBean.setHasAttachment(false);
<ide> // set default
<ide> sectionBean.setType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE.toString());
<ide> sectionBean.setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE.toString());
|
|
Java
|
apache-2.0
|
11f91f88b80a492278b84ffabf854f63a527bf5a
| 0 |
koma-akdb/org.ops4j.pax.exam2,The-Alchemist/org.ops4j.pax.exam2,ops4j/org.ops4j.pax.exam2,bimargulies/org.ops4j.pax.exam2,The-Alchemist/org.ops4j.pax.exam2,bimargulies/org.ops4j.pax.exam2,koma-akdb/org.ops4j.pax.exam2,ops4j/org.ops4j.pax.exam2
|
/*
* Copyright 2012 Harald Wellmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.ops4j.pax.exam.spi.war;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.glassfish.embeddable.archive.ScatteredArchive;
import org.glassfish.embeddable.archive.ScatteredArchive.Type;
import org.ops4j.io.ZipExploder;
import org.ops4j.pax.exam.TestAddress;
import org.ops4j.pax.exam.TestContainerException;
import org.ops4j.pax.exam.TestInstantiationInstruction;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.TestProbeProvider;
import org.ops4j.pax.exam.spi.intern.DefaultTestAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Files;
public class WarTestProbeBuilderImpl implements TestProbeBuilder
{
private static final Logger LOG = LoggerFactory.getLogger( WarTestProbeBuilderImpl.class );
private static String[] classPathExcludes = {
".cp",
"org.eclipse.osgi",
"scattered-archive-api",
"simple-glassfish-api",
"jersey-client",
"pax-exam-junit4",
"pax-exam-container",
"pax-exam-spi",
"tinybundles",
"geronimo-atinject",
"bndlib"
};
private ClasspathFilter classpathFilter;
private List<File> metadataFiles;
private File tempDir;
private File warBase;
private final Map<TestAddress, TestInstantiationInstruction> probeCalls = new HashMap<TestAddress, TestInstantiationInstruction>();
public WarTestProbeBuilderImpl()
{
this.classpathFilter = new ClasspathFilter( classPathExcludes );
this.metadataFiles = new ArrayList<File>();
this.tempDir = Files.createTempDir();
}
@SuppressWarnings( "rawtypes" )
@Override
public TestAddress addTest( Class clazz, String methodName, Object... args )
{
TestAddress address = new DefaultTestAddress( clazz.getSimpleName() + "." + methodName, args );
probeCalls.put( address, new TestInstantiationInstruction( clazz.getName() + ";" + methodName ) );
return address;
}
@SuppressWarnings( "rawtypes" )
@Override
public TestAddress addTest( Class clazz, Object... args )
{
throw new UnsupportedOperationException();
}
@SuppressWarnings( "rawtypes" )
@Override
public List<TestAddress> addTests( Class clazz, Method... m )
{
throw new UnsupportedOperationException();
}
@Override
public TestProbeBuilder setHeader( String key, String value )
{
throw new UnsupportedOperationException();
}
@SuppressWarnings( "rawtypes" )
@Override
public TestProbeBuilder ignorePackageOf( Class... classes )
{
throw new UnsupportedOperationException();
}
@Override
public TestProbeProvider build()
{
try
{
createDefaultMetadata();
String warName = "pax-exam-" + UUID.randomUUID().toString();
ScatteredArchive sar;
File webResourceDir = getWebResourceDir();
if( webResourceDir.exists() && webResourceDir.isDirectory() )
{
sar = new ScatteredArchive( warName, Type.WAR, webResourceDir );
}
else
{
sar = new ScatteredArchive( warName, Type.WAR );
}
String classpath = System.getProperty( "java.class.path" );
String[] pathElems = classpath.split( File.pathSeparator );
for( String pathElem : pathElems )
{
File file = new File( pathElem );
if( file.exists() && classpathFilter.accept( file ) )
{
LOG.debug( "including classpath element {}", file );
sar.addClassPath( file );
}
}
for( File metadata : metadataFiles )
{
if( metadata.exists() )
{
sar.addMetadata( metadata );
}
}
URI warUri = sar.toURI();
LOG.info( "probe WAR at {}", warUri );
return new WarTestProbeProvider( warUri, getTests() );
}
catch ( IOException exc )
{
throw new TestContainerException( exc );
}
}
public Set<TestAddress> getTests()
{
return probeCalls.keySet();
}
private File getWebResourceDir() throws IOException
{
File webResourceDir;
// FIXME create configuration property
// String warBase = config.getWarBase();
if( warBase == null )
{
webResourceDir = new File( "src/main/webapp" );
}
else
{
ZipExploder exploder = new ZipExploder();
webResourceDir = new File( tempDir, "exploded" );
webResourceDir.mkdir();
exploder.processFile( warBase.getAbsolutePath(),
webResourceDir.getAbsolutePath() );
}
return webResourceDir;
}
private void createDefaultMetadata()
{
File webInf = new File( "src/main/webapp/WEB-INF" );
metadataFiles.add( new File( webInf, "web.xml" ) );
File beansXml = new File( webInf, "beans.xml" );
if( !beansXml.exists() )
{
beansXml = new File( tempDir, "beans.xml" );
try
{
beansXml.createNewFile();
}
catch ( IOException exc )
{
throw new TestContainerException( "cannot create " + beansXml );
}
}
metadataFiles.add( beansXml );
}
}
|
core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/WarTestProbeBuilderImpl.java
|
/*
* Copyright 2012 Harald Wellmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.ops4j.pax.exam.spi.war;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.glassfish.embeddable.archive.ScatteredArchive;
import org.glassfish.embeddable.archive.ScatteredArchive.Type;
import org.ops4j.io.ZipExploder;
import org.ops4j.pax.exam.TestAddress;
import org.ops4j.pax.exam.TestContainerException;
import org.ops4j.pax.exam.TestInstantiationInstruction;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.TestProbeProvider;
import org.ops4j.pax.exam.spi.intern.DefaultTestAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Files;
public class WarTestProbeBuilderImpl implements TestProbeBuilder
{
private static final Logger LOG = LoggerFactory.getLogger( WarTestProbeBuilderImpl.class );
private static String[] classPathExcludes = {
".cp",
"scattered-archive-api",
"simple-glassfish-api",
"jersey-client",
"pax-exam-container",
"pax-exam-spi",
"tinybundles",
"geronimo-atinject",
"bndlib"
};
private ClasspathFilter classpathFilter;
private List<File> metadataFiles;
private File tempDir;
private File warBase;
private final Map<TestAddress, TestInstantiationInstruction> probeCalls = new HashMap<TestAddress, TestInstantiationInstruction>();
public WarTestProbeBuilderImpl()
{
this.classpathFilter = new ClasspathFilter( classPathExcludes );
this.metadataFiles = new ArrayList<File>();
this.tempDir = Files.createTempDir();
}
@SuppressWarnings( "rawtypes" )
@Override
public TestAddress addTest( Class clazz, String methodName, Object... args )
{
TestAddress address = new DefaultTestAddress( clazz.getSimpleName() + "." + methodName, args );
probeCalls.put( address, new TestInstantiationInstruction( clazz.getName() + ";" + methodName ) );
return address;
}
@SuppressWarnings( "rawtypes" )
@Override
public TestAddress addTest( Class clazz, Object... args )
{
throw new UnsupportedOperationException();
}
@SuppressWarnings( "rawtypes" )
@Override
public List<TestAddress> addTests( Class clazz, Method... m )
{
throw new UnsupportedOperationException();
}
@Override
public TestProbeBuilder setHeader( String key, String value )
{
throw new UnsupportedOperationException();
}
@SuppressWarnings( "rawtypes" )
@Override
public TestProbeBuilder ignorePackageOf( Class... classes )
{
throw new UnsupportedOperationException();
}
@Override
public TestProbeProvider build()
{
try
{
createDefaultMetadata();
String warName = "pax-exam-" + UUID.randomUUID().toString();
ScatteredArchive sar;
File webResourceDir = getWebResourceDir();
if( webResourceDir.exists() && webResourceDir.isDirectory() )
{
sar = new ScatteredArchive( warName, Type.WAR, webResourceDir );
}
else
{
sar = new ScatteredArchive( warName, Type.WAR );
}
String classpath = System.getProperty( "java.class.path" );
String[] pathElems = classpath.split( File.pathSeparator );
for( String pathElem : pathElems )
{
File file = new File( pathElem );
if( file.exists() && classpathFilter.accept( file ) )
{
LOG.debug( "including classpath element {}", file );
sar.addClassPath( file );
}
}
for( File metadata : metadataFiles )
{
if( metadata.exists() )
{
sar.addMetadata( metadata );
}
}
URI warUri = sar.toURI();
LOG.info( "probe WAR at {}", warUri );
return new WarTestProbeProvider( warUri, getTests() );
}
catch ( IOException exc )
{
throw new TestContainerException( exc );
}
}
public Set<TestAddress> getTests()
{
return probeCalls.keySet();
}
private File getWebResourceDir() throws IOException
{
File webResourceDir;
// FIXME create configuration property
// String warBase = config.getWarBase();
if( warBase == null )
{
webResourceDir = new File( "src/main/webapp" );
}
else
{
ZipExploder exploder = new ZipExploder();
webResourceDir = new File( tempDir, "exploded" );
webResourceDir.mkdir();
exploder.processFile( warBase.getAbsolutePath(),
webResourceDir.getAbsolutePath() );
}
return webResourceDir;
}
private void createDefaultMetadata()
{
File webInf = new File( "src/main/webapp/WEB-INF" );
metadataFiles.add( new File( webInf, "web.xml" ) );
File beansXml = new File( webInf, "beans.xml" );
if( !beansXml.exists() )
{
beansXml = new File( tempDir, "beans.xml" );
try
{
beansXml.createNewFile();
}
catch ( IOException exc )
{
throw new TestContainerException( "cannot create " + beansXml );
}
}
metadataFiles.add( beansXml );
}
}
|
[PAXEXAM-326] exclude org.eclipse.osgi and pax-exam-junit4 from WAR
probe
|
core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/WarTestProbeBuilderImpl.java
|
[PAXEXAM-326] exclude org.eclipse.osgi and pax-exam-junit4 from WAR probe
|
<ide><path>ore/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/war/WarTestProbeBuilderImpl.java
<ide>
<ide> private static String[] classPathExcludes = {
<ide> ".cp",
<add> "org.eclipse.osgi",
<ide> "scattered-archive-api",
<ide> "simple-glassfish-api",
<ide> "jersey-client",
<add> "pax-exam-junit4",
<ide> "pax-exam-container",
<ide> "pax-exam-spi",
<ide> "tinybundles",
|
|
Java
|
apache-2.0
|
eea3ee7392722bf5c3a02a6ae7da38e43cc7712e
| 0 |
Flipkart/foxtrot,Flipkart/foxtrot,Flipkart/foxtrot,Flipkart/foxtrot,Flipkart/foxtrot
|
package com.flipkart.foxtrot.core.querystore.actions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.foxtrot.common.ActionRequest;
import com.flipkart.foxtrot.common.ActionResponse;
import com.flipkart.foxtrot.common.Opcodes;
import com.flipkart.foxtrot.common.query.*;
import com.flipkart.foxtrot.common.query.numeric.BetweenFilter;
import com.flipkart.foxtrot.common.util.CollectionUtils;
import com.flipkart.foxtrot.core.alerts.EmailConfig;
import com.flipkart.foxtrot.core.cache.CacheManager;
import com.flipkart.foxtrot.core.common.Action;
import com.flipkart.foxtrot.core.datastore.DataStore;
import com.flipkart.foxtrot.core.exception.FoxtrotException;
import com.flipkart.foxtrot.core.exception.FoxtrotExceptions;
import com.flipkart.foxtrot.core.exception.MalformedQueryException;
import com.flipkart.foxtrot.core.querystore.QueryStore;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsLoader;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsProvider;
import com.flipkart.foxtrot.core.querystore.impl.ElasticsearchConnection;
import com.flipkart.foxtrot.core.table.TableMetadataManager;
import org.elasticsearch.action.ActionRequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/***
Created by mudit.g on Jan, 2019
***/
@AnalyticsProvider(opcode = "multi_time_query", request = MultiTimeQueryRequest.class, response = MultiTimeQueryResponse.class, cacheable = false)
public class MultiTimeQueryAction extends Action<MultiTimeQueryRequest> {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiTimeQueryAction.class);
private AnalyticsLoader analyticsLoader;
private Action action;
private MultiQueryRequest multiQueryRequest;
public MultiTimeQueryAction(MultiTimeQueryRequest parameter, TableMetadataManager tableMetadataManager, DataStore dataStore,
QueryStore queryStore, ElasticsearchConnection connection, String cacheToken,
CacheManager cacheManager, ObjectMapper objectMapper, EmailConfig emailConfig,
AnalyticsLoader analyticsLoader) {
super(parameter, tableMetadataManager, dataStore, queryStore, connection, cacheToken, cacheManager,
objectMapper, emailConfig);
this.analyticsLoader = analyticsLoader;
}
@Override
public void preprocess() {
MultiTimeQueryRequest multiTimeQueryRequest = getParameter();
int sampleSize;
BetweenFilter betweenFilter = (BetweenFilter) multiTimeQueryRequest.getActionRequest().getFilters().stream()
.filter(filter -> filter instanceof BetweenFilter)
.findFirst()
.get();
if (betweenFilter == null) {
throw new RuntimeException("No Between Filter found in actionRequest multiQueryRequest : " + multiQueryRequest.toString());
}
if (multiTimeQueryRequest.getSampleSize() != 0) {
sampleSize = multiTimeQueryRequest.getSampleSize();
} else if (multiTimeQueryRequest.getSkipDuration().toHours() > 24) {
sampleSize = (int) (30/(multiTimeQueryRequest.getSkipDuration().toDays()));
} else {
sampleSize = (int) (24/(multiTimeQueryRequest.getSkipDuration().toHours()));
}
multiTimeQueryRequest.getActionRequest().getFilters().addAll(multiTimeQueryRequest.getFilters());
multiQueryRequest = createMultiQueryRequests(sampleSize, betweenFilter);
try {
action = analyticsLoader.getAction(multiQueryRequest);
} catch (Exception e) {
throw new RuntimeException("No action found for multiQueryRequest : " + multiQueryRequest.toString());
}
if(null == action) {
throw new RuntimeException("No action found for multiQueryRequest : " + multiQueryRequest.toString());
}
action.preprocess();
}
@Override
public String getMetricKey() {
return action.getMetricKey();
}
@Override
public String getRequestCacheKey() {
return action.getRequestCacheKey();
}
@Override
public void validateImpl(MultiTimeQueryRequest parameter) throws MalformedQueryException {
List<String> validationErrors = new ArrayList<>();
if(parameter.getActionRequest() == null) {
validationErrors.add("action request cannot be null or empty");
}
if(parameter.getSkipDuration() == null) {
validationErrors.add("skip duration cannot be null or empty");
}
if(!CollectionUtils.isNullOrEmpty(validationErrors)) {
throw FoxtrotExceptions.createMalformedQueryException(parameter, validationErrors);
}
action.validateImpl(multiQueryRequest);
}
@Override
public ActionResponse execute(MultiTimeQueryRequest parameter) throws FoxtrotException {
return action.execute(multiQueryRequest);
}
@Override
public ActionRequestBuilder getRequestBuilder(MultiTimeQueryRequest parameter) throws FoxtrotException {
return action.getRequestBuilder(multiQueryRequest);
}
@Override
public ActionResponse getResponse(org.elasticsearch.action.ActionResponse multiSearchResponse,
MultiTimeQueryRequest parameter) throws FoxtrotException {
MultiQueryResponse multiQueryResponse = (MultiQueryResponse)action.getResponse(multiSearchResponse, multiQueryRequest);
MultiTimeQueryResponse multiTimeQueryResponse = new MultiTimeQueryResponse(Opcodes.MULTI_TIME_QUERY);
multiTimeQueryResponse.setResponses(multiQueryResponse.getResponses());
return multiTimeQueryResponse;
}
private MultiQueryRequest createMultiQueryRequests(int sampleSize, BetweenFilter betweenFilter) {
MultiTimeQueryRequest multiTimeQueryRequest = getParameter() ;
Map<String, ActionRequest> requests = new HashMap<>();
long from = betweenFilter.getFrom().longValue();
long to = betweenFilter.getTo().longValue();
for(int itr = 0; itr < sampleSize; itr++) {
List<Filter> filters = multiTimeQueryRequest.getActionRequest().getFilters();
for (int i = 0; i < filters.size(); i++) {
if (filters.get(i) instanceof BetweenFilter) {
BetweenFilter tempBetweenFilter = (BetweenFilter) filters.get(i);
BetweenFilter tempBetweenFilter1 = new BetweenFilter(tempBetweenFilter.getField(),
from, to, tempBetweenFilter.isFilterTemporal());
filters.set(i, tempBetweenFilter1);
break;
}
}
multiTimeQueryRequest.getActionRequest().setFilters(filters);
try{
requests.put(Long.toString(from), (ActionRequest) multiTimeQueryRequest.getActionRequest().clone());
} catch (Exception e) {
throw new RuntimeException("Error in cloning action request : " + multiTimeQueryRequest.getActionRequest().toString()
+ " Error Message: " + e);
}
from -= multiTimeQueryRequest.getSkipDuration().toMilliseconds();
to -= multiTimeQueryRequest.getSkipDuration().toMilliseconds();
}
return new MultiQueryRequest(requests);
}
}
|
foxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/actions/MultiTimeQueryAction.java
|
package com.flipkart.foxtrot.core.querystore.actions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.foxtrot.common.ActionRequest;
import com.flipkart.foxtrot.common.ActionResponse;
import com.flipkart.foxtrot.common.Opcodes;
import com.flipkart.foxtrot.common.query.*;
import com.flipkart.foxtrot.common.query.numeric.BetweenFilter;
import com.flipkart.foxtrot.common.util.CollectionUtils;
import com.flipkart.foxtrot.core.alerts.EmailConfig;
import com.flipkart.foxtrot.core.cache.CacheManager;
import com.flipkart.foxtrot.core.common.Action;
import com.flipkart.foxtrot.core.datastore.DataStore;
import com.flipkart.foxtrot.core.exception.FoxtrotException;
import com.flipkart.foxtrot.core.exception.FoxtrotExceptions;
import com.flipkart.foxtrot.core.exception.MalformedQueryException;
import com.flipkart.foxtrot.core.querystore.QueryStore;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsLoader;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsProvider;
import com.flipkart.foxtrot.core.querystore.impl.ElasticsearchConnection;
import com.flipkart.foxtrot.core.table.TableMetadataManager;
import org.elasticsearch.action.ActionRequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/***
Created by mudit.g on Jan, 2019
***/
@AnalyticsProvider(opcode = "multi_time_query", request = MultiTimeQueryRequest.class, response = MultiTimeQueryResponse.class, cacheable = false)
public class MultiTimeQueryAction extends Action<MultiTimeQueryRequest> {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiTimeQueryAction.class);
private AnalyticsLoader analyticsLoader;
private Action action;
private MultiQueryRequest multiQueryRequest;
public MultiTimeQueryAction(MultiTimeQueryRequest parameter, TableMetadataManager tableMetadataManager, DataStore dataStore,
QueryStore queryStore, ElasticsearchConnection connection, String cacheToken,
CacheManager cacheManager, ObjectMapper objectMapper, EmailConfig emailConfig,
AnalyticsLoader analyticsLoader) {
super(parameter, tableMetadataManager, dataStore, queryStore, connection, cacheToken, cacheManager,
objectMapper, emailConfig);
this.analyticsLoader = analyticsLoader;
}
@Override
public void preprocess() {
MultiTimeQueryRequest multiTimeQueryRequest = getParameter();
int sampleSize;
BetweenFilter betweenFilter = (BetweenFilter) multiTimeQueryRequest.getActionRequest().getFilters().stream()
.filter(filter -> filter instanceof BetweenFilter)
.findFirst()
.get();
if (betweenFilter == null) {
throw new RuntimeException("No Between Filter found in actionRequest multiQueryRequest : " + multiQueryRequest.toString());
}
if (multiTimeQueryRequest.getSampleSize() != 0) {
sampleSize = multiTimeQueryRequest.getSampleSize();
} else if (multiTimeQueryRequest.getSkipDuration().toHours() > 24) {
sampleSize = (int) (30/(multiTimeQueryRequest.getSkipDuration().toDays()));
} else {
sampleSize = (int) (24/(multiTimeQueryRequest.getSkipDuration().toHours()));
}
multiQueryRequest = createMultiQueryRequests(sampleSize, betweenFilter);
try {
action = analyticsLoader.getAction(multiQueryRequest);
} catch (Exception e) {
throw new RuntimeException("No action found for multiQueryRequest : " + multiQueryRequest.toString());
}
if(null == action) {
throw new RuntimeException("No action found for multiQueryRequest : " + multiQueryRequest.toString());
}
action.preprocess();
}
@Override
public String getMetricKey() {
return action.getMetricKey();
}
@Override
public String getRequestCacheKey() {
return action.getRequestCacheKey();
}
@Override
public void validateImpl(MultiTimeQueryRequest parameter) throws MalformedQueryException {
List<String> validationErrors = new ArrayList<>();
if(parameter.getActionRequest() == null) {
validationErrors.add("action request cannot be null or empty");
}
if(parameter.getSkipDuration() == null) {
validationErrors.add("skip duration cannot be null or empty");
}
if(!CollectionUtils.isNullOrEmpty(validationErrors)) {
throw FoxtrotExceptions.createMalformedQueryException(parameter, validationErrors);
}
action.validateImpl(multiQueryRequest);
}
@Override
public ActionResponse execute(MultiTimeQueryRequest parameter) throws FoxtrotException {
return action.execute(multiQueryRequest);
}
@Override
public ActionRequestBuilder getRequestBuilder(MultiTimeQueryRequest parameter) throws FoxtrotException {
return action.getRequestBuilder(multiQueryRequest);
}
@Override
public ActionResponse getResponse(org.elasticsearch.action.ActionResponse multiSearchResponse,
MultiTimeQueryRequest parameter) throws FoxtrotException {
MultiQueryResponse multiQueryResponse = (MultiQueryResponse)action.getResponse(multiSearchResponse, multiQueryRequest);
MultiTimeQueryResponse multiTimeQueryResponse = new MultiTimeQueryResponse(Opcodes.MULTI_TIME_QUERY);
multiTimeQueryResponse.setResponses(multiQueryResponse.getResponses());
return multiTimeQueryResponse;
}
private MultiQueryRequest createMultiQueryRequests(int sampleSize, BetweenFilter betweenFilter) {
MultiTimeQueryRequest multiTimeQueryRequest = getParameter() ;
Map<String, ActionRequest> requests = new HashMap<>();
long from = betweenFilter.getFrom().longValue();
long to = betweenFilter.getTo().longValue();
for(int itr = 0; itr < sampleSize; itr++) {
List<Filter> filters = multiTimeQueryRequest.getActionRequest().getFilters();
for (int i = 0; i < filters.size(); i++) {
if (filters.get(i) instanceof BetweenFilter) {
BetweenFilter tempBetweenFilter = (BetweenFilter) filters.get(i);
BetweenFilter tempBetweenFilter1 = new BetweenFilter(tempBetweenFilter.getField(),
from, to, tempBetweenFilter.isFilterTemporal());
filters.set(i, tempBetweenFilter1);
break;
}
}
multiTimeQueryRequest.getActionRequest().setFilters(filters);
try{
requests.put(Long.toString(from), (ActionRequest) multiTimeQueryRequest.getActionRequest().clone());
} catch (Exception e) {
throw new RuntimeException("Error in cloning action request : " + multiTimeQueryRequest.getActionRequest().toString()
+ " Error Message: " + e);
}
from -= multiTimeQueryRequest.getSkipDuration().toMilliseconds();
to -= multiTimeQueryRequest.getSkipDuration().toMilliseconds();
}
return new MultiQueryRequest(requests);
}
}
|
appending multiTimeQuery filters to multiTimeQuery ActionRequest filters
|
foxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/actions/MultiTimeQueryAction.java
|
appending multiTimeQuery filters to multiTimeQuery ActionRequest filters
|
<ide><path>oxtrot-core/src/main/java/com/flipkart/foxtrot/core/querystore/actions/MultiTimeQueryAction.java
<ide> } else {
<ide> sampleSize = (int) (24/(multiTimeQueryRequest.getSkipDuration().toHours()));
<ide> }
<add> multiTimeQueryRequest.getActionRequest().getFilters().addAll(multiTimeQueryRequest.getFilters());
<ide> multiQueryRequest = createMultiQueryRequests(sampleSize, betweenFilter);
<ide> try {
<ide> action = analyticsLoader.getAction(multiQueryRequest);
|
|
Java
|
agpl-3.0
|
0b8b16e0de116b805dc4c6088f4b238426d47934
| 0 |
imam-san/jPOS-1,imam-san/jPOS-1,yinheli/jPOS,poynt/jPOS,atancasis/jPOS,sebastianpacheco/jPOS,bharavi/jPOS,c0deh4xor/jPOS,atancasis/jPOS,barspi/jPOS,juanibdn/jPOS,yinheli/jPOS,jpos/jPOS,chhil/jPOS,poynt/jPOS,c0deh4xor/jPOS,barspi/jPOS,jpos/jPOS,juanibdn/jPOS,c0deh4xor/jPOS,fayezasar/jPOS,yinheli/jPOS,jpos/jPOS,sebastianpacheco/jPOS,bharavi/jPOS,sebastianpacheco/jPOS,fayezasar/jPOS,alcarraz/jPOS,alcarraz/jPOS,barspi/jPOS,alcarraz/jPOS,juanibdn/jPOS,imam-san/jPOS-1,poynt/jPOS,chhil/jPOS,atancasis/jPOS,bharavi/jPOS
|
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2010 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.transaction;
import org.jdom.Element;
import org.jpos.core.Configuration;
import org.jpos.core.Configurable;
import org.jpos.core.ConfigurationException;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.QFactory;
import org.jpos.space.*;
import org.jpos.util.*;
import java.io.Serializable;
import java.util.*;
@SuppressWarnings("unchecked")
public class TransactionManager
extends QBeanSupport
implements Runnable, TransactionConstants, TransactionManagerMBean
{
public static final String HEAD = "$HEAD";
public static final String TAIL = "$TAIL";
public static final String CONTEXT = "$CONTEXT.";
public static final String STATE = "$STATE.";
public static final String GROUPS = "$GROUPS.";
public static final String TAILLOCK = "$TAILLOCK";
public static final String RETRY_QUEUE = "$RETRY_QUEUE";
public static final Integer PREPARING = 0;
public static final Integer COMMITTING = 1;
public static final Integer DONE = 2;
public static final String DEFAULT_GROUP = "";
public static final long MAX_PARTICIPANTS = 1000; // loop prevention
protected Map groups;
Space sp;
Space psp;
Space isp; // input space
String queue;
String tailLock;
Thread[] threads;
final List<TransactionStatusListener> statusListeners = new ArrayList<TransactionStatusListener>();
boolean hasStatusListeners;
int activeSessions;
boolean debug;
boolean profiler;
boolean doRecover;
int maxActiveSessions;
long head, tail;
long retryInterval = 5000L;
long retryTimeout = 60000L;
long pauseTimeout = 0L;
RetryTask retryTask = null;
TPS tps;
public void initService () throws ConfigurationException {
queue = cfg.get ("queue", null);
if (queue == null)
throw new ConfigurationException ("queue property not specified");
sp = SpaceFactory.getSpace (cfg.get ("space"));
isp = SpaceFactory.getSpace (cfg.get ("input-space", cfg.get ("space")));
psp = SpaceFactory.getSpace (cfg.get ("persistent-space", this.toString()));
tail = initCounter (TAIL, cfg.getLong ("initial-tail", 1));
head = Math.max (initCounter (HEAD, tail), tail);
initTailLock ();
groups = new HashMap();
initParticipants (getPersist());
initStatusListeners (getPersist());
}
public void startService () throws Exception {
NameRegistrar.register (getName (), this);
recover ();
int sessions = cfg.getInt ("sessions", 1);
threads = new Thread[sessions];
if (tps != null)
tps.stop();
tps = new TPS (cfg.getBoolean ("auto-update-tps", true));
for (int i=0; i<sessions; i++) {
Thread t = new Thread (this);
t.setName (getName() + "-" + i);
t.setDaemon (false);
t.start ();
threads[i] = t;
}
if (psp.rdp (RETRY_QUEUE) != null)
checkRetryTask();
}
public void stopService () throws Exception {
NameRegistrar.unregister (getName ());
long sessions = cfg.getLong ("sessions", 1);
for (int i=0; i<sessions; i++) {
isp.out (queue, Boolean.FALSE, 60*1000);
}
for (int i=0; i<sessions; i++) {
try {
threads[i].join (60*1000);
} catch (InterruptedException e) {
getLog().warn ("Session " +i +" does not response - attempting to interrupt");
threads[i].interrupt();
}
threads[i] = null;
}
tps.stop();
}
public void queue (Serializable context) {
isp.out (queue, context);
}
public void push (Serializable context) {
isp.push (queue, context);
}
@SuppressWarnings("unused")
public String getQueueName() {
return queue;
}
public Space getSpace() {
return sp;
}
public Space getInputSpace() {
return isp;
}
public Space getPersistentSpace() {
return psp;
}
public void run () {
long id = 0;
int session;
List members = null;
Iterator iter = null;
PausedTransaction pt;
boolean abort = false;
LogEvent evt = null;
Profiler prof = null;
String threadName = Thread.currentThread().getName();
getLog().info (threadName + " start");
long startTime = 0L;
boolean paused;
synchronized (HEAD) {
session = activeSessions++;
}
while (running()) {
Serializable context = null;
paused = false;
try {
if (hasStatusListeners)
notifyStatusListeners (session, TransactionStatusEvent.State.READY, id, "", null);
Object obj = isp.in (queue);
if (obj == Boolean.FALSE)
continue; // stopService ``hack''
if (!(obj instanceof Serializable)) {
getLog().error (
"non serializable '" + obj.getClass().getName()
+ "' on queue '" + queue + "'"
);
continue;
}
context = (Serializable) obj;
if (obj instanceof Pausable) {
Pausable pausable = (Pausable) obj;
pt = pausable.getPausedTransaction();
if (pt != null) {
pt.cancelExpirationMonitor();
id = pt.id();
members = pt.members();
iter = pt.iterator();
abort = pt.isAborting();
}
} else
pt = null;
if (pt == null) {
int running = getRunningSessions();
if (maxActiveSessions > 0 && running >= maxActiveSessions) {
evt = getLog().createLogEvent ("warn",
Thread.currentThread().getName()
+ ": emergency retry, running-sessions=" + running
+ ", max-active-sessions=" + maxActiveSessions
);
evt.addMessage (obj);
psp.out (RETRY_QUEUE, obj, retryTimeout);
checkRetryTask();
continue;
}
abort = false;
id = nextId ();
members = new ArrayList ();
iter = getParticipants (DEFAULT_GROUP).iterator();
}
if (debug) {
evt = getLog().createLogEvent ("debug",
Thread.currentThread().getName()
+ ":" + Long.toString(id) +
(pt != null ? " [resuming]" : "")
);
prof = new Profiler();
startTime = System.currentTimeMillis();
}
snapshot (id, context, PREPARING);
int action = prepare (session, id, context, members, iter, abort, evt, prof);
switch (action) {
case PAUSE:
paused = true;
break;
case PREPARED:
setState (id, COMMITTING);
commit (session, id, context, members, false, evt, prof);
break;
case ABORTED:
abort (session, id, context, members, false, evt, prof);
break;
case RETRY:
psp.out (RETRY_QUEUE, context);
checkRetryTask();
break;
case NO_JOIN:
break;
}
if ((action & PAUSE) == 0) {
snapshot (id, null, DONE);
if (id == tail) {
checkTail ();
}
tps.tick();
}
} catch (Throwable t) {
if (evt == null)
getLog().fatal (t); // should never happen
else
evt.addMessage (t);
} finally {
if (hasStatusListeners) {
notifyStatusListeners (
session,
paused ? TransactionStatusEvent.State.PAUSED : TransactionStatusEvent.State.DONE,
id, "", context);
}
if (evt != null) {
evt.addMessage (
String.format ("head=%d, tail=%d, outstanding=%d, %s, elapsed=%dms",
head, tail, getOutstandingTransactions(),
tps.toString(),
(System.currentTimeMillis() - startTime)
)
);
if (prof != null)
evt.addMessage (prof);
Logger.log (evt);
evt = null;
}
}
}
getLog().info (threadName + " stop");
synchronized (HEAD) {
activeSessions--;
}
getLog().info ("stop " + Thread.currentThread() + ", active sessions=" + activeSessions);
}
public long getTail () {
return tail;
}
public long getHead () {
return head;
}
public long getInTransit () {
return head - tail;
}
public void setConfiguration (Configuration cfg)
throws ConfigurationException
{
super.setConfiguration (cfg);
debug = cfg.getBoolean ("debug");
profiler = cfg.getBoolean ("profiler", debug);
if (profiler)
debug = true; // profiler needs debug
doRecover = cfg.getBoolean ("recover", true);
retryInterval = cfg.getLong ("retry-interval", retryInterval);
retryTimeout = cfg.getLong ("retry-timeout", retryTimeout);
pauseTimeout = cfg.getLong ("pause-timeout", pauseTimeout);
maxActiveSessions = cfg.getInt ("max-active-sessions", 0);
}
public void addListener (TransactionStatusListener l) {
synchronized (statusListeners) {
statusListeners.add (l);
hasStatusListeners = true;
}
}
public void removeListener (TransactionStatusListener l) {
synchronized (statusListeners) {
statusListeners.remove (l);
hasStatusListeners = statusListeners.size() > 0;
}
}
public TPS getTPS() {
return tps;
}
protected void commit
(int session, long id, Serializable context, List members, boolean recover, LogEvent evt, Profiler prof)
{
Iterator iter = members.iterator();
while (iter.hasNext ()) {
TransactionParticipant p = (TransactionParticipant) iter.next();
if (recover && p instanceof ContextRecovery) {
context = ((ContextRecovery) p).recover (id, context, true);
if (evt != null)
evt.addMessage (" commit-recover: " + p.getClass().getName());
}
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.COMMITING, id, p.getClass().getName(), context
);
commit (p, id, context);
if (evt != null) {
evt.addMessage (" commit: " + p.getClass().getName());
if (prof != null)
prof.checkPoint (" commit: " + p.getClass().getName());
}
}
}
protected void abort
(int session, long id, Serializable context, List members, boolean recover, LogEvent evt, Profiler prof)
{
Iterator iter = members.iterator();
while (iter.hasNext ()) {
TransactionParticipant p = (TransactionParticipant) iter.next();
if (recover && p instanceof ContextRecovery) {
context = ((ContextRecovery) p).recover (id, context, false);
if (evt != null)
evt.addMessage (" abort-recover: " + p.getClass().getName());
}
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.ABORTING, id, p.getClass().getName(), context
);
abort (p, id, context);
if (evt != null) {
evt.addMessage (" abort: " + p.getClass().getName());
if (prof != null)
prof.checkPoint (" abort: " + p.getClass().getName());
}
}
}
protected int prepareForAbort
(TransactionParticipant p, long id, Serializable context)
{
try {
if (p instanceof AbortParticipant)
return ((AbortParticipant)p).prepareForAbort (id, context);
} catch (Throwable t) {
getLog().warn ("PREPARE-FOR-ABORT: " + Long.toString (id), t);
}
return ABORTED | NO_JOIN;
}
protected int prepare
(TransactionParticipant p, long id, Serializable context)
{
try {
return p.prepare (id, context);
} catch (Throwable t) {
getLog().warn ("PREPARE: " + Long.toString (id), t);
}
return ABORTED;
}
protected void commit
(TransactionParticipant p, long id, Serializable context)
{
try {
p.commit (id, context);
} catch (Throwable t) {
getLog().warn ("COMMIT: " + Long.toString (id), t);
}
}
protected void abort
(TransactionParticipant p, long id, Serializable context)
{
try {
p.abort (id, context);
} catch (Throwable t) {
getLog().warn ("ABORT: " + Long.toString (id), t);
}
}
protected int prepare
(int session, long id, Serializable context, List members, Iterator iter, boolean abort, LogEvent evt, Profiler prof)
{
boolean retry = false;
boolean pause = false;
for (int i=0; iter.hasNext (); i++) {
int action;
if (i > MAX_PARTICIPANTS) {
getLog().warn (
"loop detected - transaction " +id + " aborted."
);
return ABORTED;
}
TransactionParticipant p = (TransactionParticipant) iter.next();
if (abort) {
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.PREPARING_FOR_ABORT, id, p.getClass().getName(), context
);
action = prepareForAbort (p, id, context);
if (evt != null && (p instanceof AbortParticipant))
evt.addMessage ("prepareForAbort: " + p.getClass().getName());
} else {
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.PREPARING, id, p.getClass().getName(), context
);
action = prepare (p, id, context);
abort = (action & PREPARED) == ABORTED;
retry = (action & RETRY) == RETRY;
pause = (action & PAUSE) == PAUSE;
if (evt != null) {
evt.addMessage (" prepare: "
+ p.getClass().getName()
+ (abort ? " ABORTED" : "")
+ (retry ? " RETRY" : "")
+ (pause ? " PAUSE" : "")
+ ((action & READONLY) == READONLY ? " READONLY" : "")
+ ((action & NO_JOIN) == NO_JOIN ? " NO_JOIN" : ""));
if (prof != null)
prof.checkPoint ("prepare: " + p.getClass().getName());
}
}
if ((action & READONLY) == 0) {
snapshot (id, context);
}
if ((action & NO_JOIN) == 0) {
members.add (p);
}
if (p instanceof GroupSelector) {
String groupName = null;
try {
groupName = ((GroupSelector)p).select (id, context);
} catch (Exception e) {
if (evt != null)
evt.addMessage (" groupSelector " + p + " - " + e.getMessage());
else
getLog().error (" groupSelector: " + p + " - " + e.getMessage());
}
if (evt != null)
evt.addMessage (" groupSelector: " + groupName);
if (groupName != null) {
StringTokenizer st = new StringTokenizer (groupName, " ,");
List participants = new ArrayList();
while (st.hasMoreTokens ()) {
String grp = st.nextToken();
addGroup (id, grp);
participants.addAll (getParticipants (grp));
}
while (iter.hasNext())
participants.add (iter.next());
iter = participants.iterator();
continue;
}
}
if (pause) {
if (context instanceof Pausable) {
Pausable pausable = (Pausable) context;
long t = pausable.getTimeout();
if (t == 0)
t = pauseTimeout;
TimerTask expirationMonitor = null;
if (t > 0)
expirationMonitor = new PausedMonitor (pausable);
PausedTransaction pt = new PausedTransaction (
this, id, members, iter, abort, expirationMonitor
);
pausable.setPausedTransaction (pt);
if (expirationMonitor != null) {
synchronized (context) {
if (!pt.isResumed()) {
DefaultTimer.getTimer().schedule (
expirationMonitor, t
);
}
}
}
} else {
throw new RuntimeException ("Unable to PAUSE transaction - Context is not Pausable");
}
return PAUSE;
}
}
return members.size() == 0 ? NO_JOIN :
(abort ? (retry ? RETRY : ABORTED) : PREPARED);
}
protected List getParticipants (String groupName) {
List participants = (List) groups.get (groupName);
if (participants == null)
participants = new ArrayList();
return participants;
}
protected List getParticipants (long id) {
// Use a local copy of participant to avoid adding the
// GROUP participant to the DEFAULT_GROUP
ArrayList participantsChain = new ArrayList();
List participants = getParticipants (DEFAULT_GROUP);
// Add DEFAULT_GROUP participants
participantsChain.addAll(participants);
String key = getKey(GROUPS, id);
String grp;
// now add participants of Group
while ( (grp = (String) psp.inp (key)) != null) {
participantsChain.addAll (getParticipants (grp));
}
return participantsChain;
}
protected void initStatusListeners (Element config) throws ConfigurationException{
final Iterator iter = config.getChildren ("status-listener").iterator();
while (iter.hasNext()) {
final Element e = (Element) iter.next();
final QFactory factory = getFactory();
final TransactionStatusListener listener = (TransactionStatusListener) factory.newInstance (e.getAttributeValue ("class"));
factory.setConfiguration (listener, config);
addListener(listener);
}
}
protected void initParticipants (Element config)
throws ConfigurationException
{
groups.put (DEFAULT_GROUP, initGroup (config));
Iterator iter = config.getChildren ("group").iterator();
while (iter.hasNext()) {
Element e = (Element) iter.next();
String name = e.getAttributeValue ("name");
if (name == null)
throw new ConfigurationException ("missing group name");
if (groups.get (name) != null) {
throw new ConfigurationException (
"Group '" + name + "' already defined"
);
}
groups.put (name, initGroup (e));
}
}
protected ArrayList initGroup (Element e)
throws ConfigurationException
{
ArrayList group = new ArrayList ();
Iterator iter = e.getChildren ("participant").iterator();
while (iter.hasNext()) {
group.add (createParticipant ((Element) iter.next()));
}
return group;
}
public TransactionParticipant createParticipant (Element e)
throws ConfigurationException
{
QFactory factory = getFactory();
TransactionParticipant participant = (TransactionParticipant)
factory.newInstance (e.getAttributeValue ("class")
);
factory.setLogger (participant, e);
QFactory.invoke (participant, "setTransactionManager", this, TransactionManager.class);
factory.setConfiguration (participant, e);
return participant;
}
public int getOutstandingTransactions() {
if (isp instanceof LocalSpace)
return ((LocalSpace)sp).size(queue);
return -1;
}
protected String getKey (String prefix, long id) {
StringBuffer sb = new StringBuffer (getName());
sb.append ('.');
sb.append (prefix);
sb.append (Long.toString (id));
return sb.toString ();
}
protected long initCounter (String name, long defValue) {
Long L = (Long) psp.rdp (name);
if (L == null) {
L = defValue;
psp.out (name, L);
}
return L;
}
protected void commitOff (Space sp) {
if (sp instanceof JDBMSpace) {
((JDBMSpace) sp).setAutoCommit (false);
}
}
protected void commitOn (Space sp) {
if (sp instanceof JDBMSpace) {
JDBMSpace jsp = (JDBMSpace) sp;
jsp.commit ();
jsp.setAutoCommit (true);
}
}
protected void syncTail () {
synchronized (psp) {
commitOff (psp);
psp.inp (TAIL);
psp.out (TAIL, tail);
commitOn (psp);
}
}
protected void initTailLock () {
tailLock = TAILLOCK + "." + Integer.toString (this.hashCode());
SpaceUtil.wipe (sp, tailLock);
sp.out (tailLock, TAILLOCK);
}
protected void checkTail () {
Object lock = sp.in (tailLock);
while (tailDone()) {
// if (debug) {
// getLog().debug ("tailDone " + tail);
// }
tail++;
}
syncTail ();
sp.out (tailLock, lock);
}
protected boolean tailDone () {
String stateKey = getKey (STATE, tail);
if (DONE.equals (psp.rdp (stateKey))) {
purge (tail);
return true;
}
return false;
}
protected long nextId () {
long h;
synchronized (psp) {
commitOff (psp);
psp.in (HEAD);
h = head;
psp.out (HEAD, ++head);
commitOn (psp);
}
return h;
}
protected void snapshot (long id, Serializable context) {
snapshot (id, context, null);
}
protected void snapshot (long id, Serializable context, Integer status) {
String contextKey = getKey (CONTEXT, id);
synchronized (psp) {
commitOff (psp);
while (psp.inp (contextKey) != null)
;
if (context != null)
psp.out (contextKey, context);
if (status != null) {
String stateKey = getKey (STATE, id);
while (psp.inp (stateKey) != null)
;
psp.out (stateKey, status);
}
commitOn (psp);
}
}
protected void setState (long id, Integer state) {
String stateKey = getKey (STATE, id);
synchronized (psp) {
commitOff (psp);
while (psp.inp (stateKey) != null)
;
if (state!= null)
psp.out (stateKey, state);
commitOn (psp);
}
}
protected void addGroup (long id, String groupName) {
if (groupName != null)
psp.out (getKey (GROUPS, id), groupName);
}
protected void purge (long id) {
String stateKey = getKey (STATE, id);
String contextKey = getKey (CONTEXT, id);
String groupsKey = getKey (GROUPS, id);
synchronized (psp) {
commitOff (psp);
while (psp.inp (stateKey) != null)
;
while (psp.inp (contextKey) != null)
;
while (psp.inp (groupsKey) != null)
;
commitOn (psp);
}
}
protected void recover () {
if (doRecover) {
if (tail < head) {
getLog().info ("recover - tail=" +tail+", head="+head);
}
while (tail < head) {
recover (0, tail++);
}
} else
tail = head;
syncTail ();
}
protected void recover (int session, long id) {
LogEvent evt = getLog().createLogEvent ("recover");
Profiler prof = new Profiler();
evt.addMessage ("<id>" + id + "</id>");
try {
String stateKey = getKey (STATE, id);
String contextKey = getKey (CONTEXT, id);
Integer state = (Integer) psp.rdp (stateKey);
if (state == null) {
evt.addMessage ("unknown stateKey " + stateKey);
SpaceUtil.wipe (psp, contextKey); // just in case ...
return;
}
Serializable context = (Serializable) psp.rdp (contextKey);
if (context != null)
evt.addMessage (context);
if (DONE.equals (state)) {
evt.addMessage ("<done/>");
} else if (COMMITTING.equals (state)) {
commit (session, id, context, getParticipants (id), true, evt, prof);
} else if (PREPARING.equals (state)) {
abort (session, id, context, getParticipants (id), true, evt, prof);
}
purge (id);
} finally {
evt.addMessage (prof);
Logger.log (evt);
}
}
protected synchronized void checkRetryTask () {
if (retryTask == null) {
retryTask = new RetryTask();
new Thread(retryTask).start();
}
}
public class PausedMonitor extends TimerTask {
Pausable context;
public PausedMonitor (Pausable context) {
super();
this.context = context;
}
public void run() {
cancel();
context.getPausedTransaction().forceAbort();
context.resume();
}
}
public class RetryTask implements Runnable {
public void run() {
Thread.currentThread().setName (getName()+"-retry-task");
while (running()) {
for (Object context; (context = psp.rdp (RETRY_QUEUE)) != null;)
{
isp.out (queue, context, retryTimeout);
psp.inp (RETRY_QUEUE);
}
try {
Thread.sleep (retryInterval);
} catch (InterruptedException ignored) { }
}
}
}
public void setDebug (boolean debug) {
this.debug = debug;
}
public boolean getDebug() {
return debug;
}
public int getActiveSessions() {
return activeSessions;
}
public int getRunningSessions() {
return (int) (head - tail);
}
private void notifyStatusListeners
(int session, TransactionStatusEvent.State state, long id, String info, Serializable context)
{
TransactionStatusEvent e = new TransactionStatusEvent(session, state, id, info, context);
synchronized (statusListeners) {
for (TransactionStatusListener l : statusListeners) {
l.update (e);
}
}
}
}
|
jpos6/modules/txnmgr/src/org/jpos/transaction/TransactionManager.java
|
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2010 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.transaction;
import org.jdom.Element;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.q2.QBeanSupport;
import org.jpos.q2.QFactory;
import org.jpos.space.*;
import org.jpos.util.*;
import java.io.Serializable;
import java.util.*;
@SuppressWarnings("unchecked")
public class TransactionManager
extends QBeanSupport
implements Runnable, TransactionConstants, TransactionManagerMBean
{
public static final String HEAD = "$HEAD";
public static final String TAIL = "$TAIL";
public static final String CONTEXT = "$CONTEXT.";
public static final String STATE = "$STATE.";
public static final String GROUPS = "$GROUPS.";
public static final String TAILLOCK = "$TAILLOCK";
public static final String RETRY_QUEUE = "$RETRY_QUEUE";
public static final Integer PREPARING = 0;
public static final Integer COMMITTING = 1;
public static final Integer DONE = 2;
public static final String DEFAULT_GROUP = "";
public static final long MAX_PARTICIPANTS = 1000; // loop prevention
protected Map groups;
Space sp;
Space psp;
Space isp; // input space
String queue;
String tailLock;
Thread[] threads;
List<TransactionStatusListener> statusListeners = new ArrayList<TransactionStatusListener>();
boolean hasStatusListeners;
int activeSessions;
boolean debug;
boolean profiler;
boolean doRecover;
int maxActiveSessions;
long head, tail;
long retryInterval = 5000L;
long retryTimeout = 60000L;
long pauseTimeout = 0L;
RetryTask retryTask = null;
TPS tps;
public void initService () throws ConfigurationException {
queue = cfg.get ("queue", null);
if (queue == null)
throw new ConfigurationException ("queue property not specified");
sp = SpaceFactory.getSpace (cfg.get ("space"));
isp = SpaceFactory.getSpace (cfg.get ("input-space", cfg.get ("space")));
psp = SpaceFactory.getSpace (cfg.get ("persistent-space", this.toString()));
tail = initCounter (TAIL, cfg.getLong ("initial-tail", 1));
head = Math.max (initCounter (HEAD, tail), tail);
initTailLock ();
groups = new HashMap();
initParticipants (getPersist());
}
public void startService () throws Exception {
NameRegistrar.register (getName (), this);
recover ();
int sessions = cfg.getInt ("sessions", 1);
threads = new Thread[sessions];
if (tps != null)
tps.stop();
tps = new TPS (cfg.getBoolean ("auto-update-tps", true));
for (int i=0; i<sessions; i++) {
Thread t = new Thread (this);
t.setName (getName() + "-" + i);
t.setDaemon (false);
t.start ();
threads[i] = t;
}
if (psp.rdp (RETRY_QUEUE) != null)
checkRetryTask();
}
public void stopService () throws Exception {
NameRegistrar.unregister (getName ());
long sessions = cfg.getLong ("sessions", 1);
for (int i=0; i<sessions; i++) {
isp.out (queue, Boolean.FALSE, 60*1000);
}
for (int i=0; i<sessions; i++) {
try {
threads[i].join (60*1000);
} catch (InterruptedException e) {
getLog().warn ("Session " +i +" does not response - attempting to interrupt");
threads[i].interrupt();
}
threads[i] = null;
}
tps.stop();
}
public void queue (Serializable context) {
isp.out (queue, context);
}
public void push (Serializable context) {
isp.push (queue, context);
}
@SuppressWarnings("unused")
public String getQueueName() {
return queue;
}
public Space getSpace() {
return sp;
}
public Space getInputSpace() {
return isp;
}
public Space getPersistentSpace() {
return psp;
}
public void run () {
long id = 0;
int session;
List members = null;
Iterator iter = null;
PausedTransaction pt;
boolean abort = false;
LogEvent evt = null;
Profiler prof = null;
String threadName = Thread.currentThread().getName();
getLog().info (threadName + " start");
long startTime = 0L;
boolean paused;
synchronized (HEAD) {
session = activeSessions++;
}
while (running()) {
Serializable context = null;
paused = false;
try {
if (hasStatusListeners)
notifyStatusListeners (session, TransactionStatusEvent.State.READY, id, "", null);
Object obj = isp.in (queue);
if (obj == Boolean.FALSE)
continue; // stopService ``hack''
if (!(obj instanceof Serializable)) {
getLog().error (
"non serializable '" + obj.getClass().getName()
+ "' on queue '" + queue + "'"
);
continue;
}
context = (Serializable) obj;
if (obj instanceof Pausable) {
Pausable pausable = (Pausable) obj;
pt = pausable.getPausedTransaction();
if (pt != null) {
pt.cancelExpirationMonitor();
id = pt.id();
members = pt.members();
iter = pt.iterator();
abort = pt.isAborting();
}
} else
pt = null;
if (pt == null) {
int running = getRunningSessions();
if (maxActiveSessions > 0 && running >= maxActiveSessions) {
evt = getLog().createLogEvent ("warn",
Thread.currentThread().getName()
+ ": emergency retry, running-sessions=" + running
+ ", max-active-sessions=" + maxActiveSessions
);
evt.addMessage (obj);
psp.out (RETRY_QUEUE, obj, retryTimeout);
checkRetryTask();
continue;
}
abort = false;
id = nextId ();
members = new ArrayList ();
iter = getParticipants (DEFAULT_GROUP).iterator();
}
if (debug) {
evt = getLog().createLogEvent ("debug",
Thread.currentThread().getName()
+ ":" + Long.toString(id) +
(pt != null ? " [resuming]" : "")
);
prof = new Profiler();
startTime = System.currentTimeMillis();
}
snapshot (id, context, PREPARING);
int action = prepare (session, id, context, members, iter, abort, evt, prof);
switch (action) {
case PAUSE:
paused = true;
break;
case PREPARED:
setState (id, COMMITTING);
commit (session, id, context, members, false, evt, prof);
break;
case ABORTED:
abort (session, id, context, members, false, evt, prof);
break;
case RETRY:
psp.out (RETRY_QUEUE, context);
checkRetryTask();
break;
case NO_JOIN:
break;
}
if ((action & PAUSE) == 0) {
snapshot (id, null, DONE);
if (id == tail) {
checkTail ();
}
tps.tick();
}
} catch (Throwable t) {
if (evt == null)
getLog().fatal (t); // should never happen
else
evt.addMessage (t);
} finally {
if (hasStatusListeners) {
notifyStatusListeners (
session,
paused ? TransactionStatusEvent.State.PAUSED : TransactionStatusEvent.State.DONE,
id, "", context);
}
if (evt != null) {
evt.addMessage (
String.format ("head=%d, tail=%d, outstanding=%d, %s, elapsed=%dms",
head, tail, getOutstandingTransactions(),
tps.toString(),
(System.currentTimeMillis() - startTime)
)
);
if (prof != null)
evt.addMessage (prof);
Logger.log (evt);
evt = null;
}
}
}
getLog().info (threadName + " stop");
synchronized (HEAD) {
activeSessions--;
}
getLog().info ("stop " + Thread.currentThread() + ", active sessions=" + activeSessions);
}
public long getTail () {
return tail;
}
public long getHead () {
return head;
}
public long getInTransit () {
return head - tail;
}
public void setConfiguration (Configuration cfg)
throws ConfigurationException
{
super.setConfiguration (cfg);
debug = cfg.getBoolean ("debug");
profiler = cfg.getBoolean ("profiler", debug);
if (profiler)
debug = true; // profiler needs debug
doRecover = cfg.getBoolean ("recover", true);
retryInterval = cfg.getLong ("retry-interval", retryInterval);
retryTimeout = cfg.getLong ("retry-timeout", retryTimeout);
pauseTimeout = cfg.getLong ("pause-timeout", pauseTimeout);
maxActiveSessions = cfg.getInt ("max-active-sessions", 0);
}
public void addListener (TransactionStatusListener l) {
synchronized (statusListeners) {
statusListeners.add (l);
hasStatusListeners = true;
}
}
public void removeListener (TransactionStatusListener l) {
synchronized (statusListeners) {
statusListeners.remove (l);
hasStatusListeners = statusListeners.size() > 0;
}
}
public TPS getTPS() {
return tps;
}
protected void commit
(int session, long id, Serializable context, List members, boolean recover, LogEvent evt, Profiler prof)
{
Iterator iter = members.iterator();
while (iter.hasNext ()) {
TransactionParticipant p = (TransactionParticipant) iter.next();
if (recover && p instanceof ContextRecovery) {
context = ((ContextRecovery) p).recover (id, context, true);
if (evt != null)
evt.addMessage (" commit-recover: " + p.getClass().getName());
}
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.COMMITING, id, p.getClass().getName(), context
);
commit (p, id, context);
if (evt != null) {
evt.addMessage (" commit: " + p.getClass().getName());
if (prof != null)
prof.checkPoint (" commit: " + p.getClass().getName());
}
}
}
protected void abort
(int session, long id, Serializable context, List members, boolean recover, LogEvent evt, Profiler prof)
{
Iterator iter = members.iterator();
while (iter.hasNext ()) {
TransactionParticipant p = (TransactionParticipant) iter.next();
if (recover && p instanceof ContextRecovery) {
context = ((ContextRecovery) p).recover (id, context, false);
if (evt != null)
evt.addMessage (" abort-recover: " + p.getClass().getName());
}
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.ABORTING, id, p.getClass().getName(), context
);
abort (p, id, context);
if (evt != null) {
evt.addMessage (" abort: " + p.getClass().getName());
if (prof != null)
prof.checkPoint (" abort: " + p.getClass().getName());
}
}
}
protected int prepareForAbort
(TransactionParticipant p, long id, Serializable context)
{
try {
if (p instanceof AbortParticipant)
return ((AbortParticipant)p).prepareForAbort (id, context);
} catch (Throwable t) {
getLog().warn ("PREPARE-FOR-ABORT: " + Long.toString (id), t);
}
return ABORTED | NO_JOIN;
}
protected int prepare
(TransactionParticipant p, long id, Serializable context)
{
try {
return p.prepare (id, context);
} catch (Throwable t) {
getLog().warn ("PREPARE: " + Long.toString (id), t);
}
return ABORTED;
}
protected void commit
(TransactionParticipant p, long id, Serializable context)
{
try {
p.commit (id, context);
} catch (Throwable t) {
getLog().warn ("COMMIT: " + Long.toString (id), t);
}
}
protected void abort
(TransactionParticipant p, long id, Serializable context)
{
try {
p.abort (id, context);
} catch (Throwable t) {
getLog().warn ("ABORT: " + Long.toString (id), t);
}
}
protected int prepare
(int session, long id, Serializable context, List members, Iterator iter, boolean abort, LogEvent evt, Profiler prof)
{
boolean retry = false;
boolean pause = false;
for (int i=0; iter.hasNext (); i++) {
int action;
if (i > MAX_PARTICIPANTS) {
getLog().warn (
"loop detected - transaction " +id + " aborted."
);
return ABORTED;
}
TransactionParticipant p = (TransactionParticipant) iter.next();
if (abort) {
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.PREPARING_FOR_ABORT, id, p.getClass().getName(), context
);
action = prepareForAbort (p, id, context);
if (evt != null && (p instanceof AbortParticipant))
evt.addMessage ("prepareForAbort: " + p.getClass().getName());
} else {
if (hasStatusListeners)
notifyStatusListeners (
session, TransactionStatusEvent.State.PREPARING, id, p.getClass().getName(), context
);
action = prepare (p, id, context);
abort = (action & PREPARED) == ABORTED;
retry = (action & RETRY) == RETRY;
pause = (action & PAUSE) == PAUSE;
if (evt != null) {
evt.addMessage (" prepare: "
+ p.getClass().getName()
+ (abort ? " ABORTED" : "")
+ (retry ? " RETRY" : "")
+ (pause ? " PAUSE" : "")
+ ((action & READONLY) == READONLY ? " READONLY" : "")
+ ((action & NO_JOIN) == NO_JOIN ? " NO_JOIN" : ""));
if (prof != null)
prof.checkPoint ("prepare: " + p.getClass().getName());
}
}
if ((action & READONLY) == 0) {
snapshot (id, context);
}
if ((action & NO_JOIN) == 0) {
members.add (p);
}
if (p instanceof GroupSelector) {
String groupName = null;
try {
groupName = ((GroupSelector)p).select (id, context);
} catch (Exception e) {
if (evt != null)
evt.addMessage (" groupSelector " + p + " - " + e.getMessage());
else
getLog().error (" groupSelector: " + p + " - " + e.getMessage());
}
if (evt != null)
evt.addMessage (" groupSelector: " + groupName);
if (groupName != null) {
StringTokenizer st = new StringTokenizer (groupName, " ,");
List participants = new ArrayList();
while (st.hasMoreTokens ()) {
String grp = st.nextToken();
addGroup (id, grp);
participants.addAll (getParticipants (grp));
}
while (iter.hasNext())
participants.add (iter.next());
iter = participants.iterator();
continue;
}
}
if (pause) {
if (context instanceof Pausable) {
Pausable pausable = (Pausable) context;
long t = pausable.getTimeout();
if (t == 0)
t = pauseTimeout;
TimerTask expirationMonitor = null;
if (t > 0)
expirationMonitor = new PausedMonitor (pausable);
PausedTransaction pt = new PausedTransaction (
this, id, members, iter, abort, expirationMonitor
);
pausable.setPausedTransaction (pt);
if (expirationMonitor != null) {
synchronized (context) {
if (!pt.isResumed()) {
DefaultTimer.getTimer().schedule (
expirationMonitor, t
);
}
}
}
} else {
throw new RuntimeException ("Unable to PAUSE transaction - Context is not Pausable");
}
return PAUSE;
}
}
return members.size() == 0 ? NO_JOIN :
(abort ? (retry ? RETRY : ABORTED) : PREPARED);
}
protected List getParticipants (String groupName) {
List participants = (List) groups.get (groupName);
if (participants == null)
participants = new ArrayList();
return participants;
}
protected List getParticipants (long id) {
// Use a local copy of participant to avoid adding the
// GROUP participant to the DEFAULT_GROUP
ArrayList participantsChain = new ArrayList();
List participants = getParticipants (DEFAULT_GROUP);
// Add DEFAULT_GROUP participants
participantsChain.addAll(participants);
String key = getKey(GROUPS, id);
String grp;
// now add participants of Group
while ( (grp = (String) psp.inp (key)) != null) {
participantsChain.addAll (getParticipants (grp));
}
return participantsChain;
}
protected void initParticipants (Element config)
throws ConfigurationException
{
groups.put (DEFAULT_GROUP, initGroup (config));
Iterator iter = config.getChildren ("group").iterator();
while (iter.hasNext()) {
Element e = (Element) iter.next();
String name = e.getAttributeValue ("name");
if (name == null)
throw new ConfigurationException ("missing group name");
if (groups.get (name) != null) {
throw new ConfigurationException (
"Group '" + name + "' already defined"
);
}
groups.put (name, initGroup (e));
}
}
protected ArrayList initGroup (Element e)
throws ConfigurationException
{
ArrayList group = new ArrayList ();
Iterator iter = e.getChildren ("participant").iterator();
while (iter.hasNext()) {
group.add (createParticipant ((Element) iter.next()));
}
return group;
}
public TransactionParticipant createParticipant (Element e)
throws ConfigurationException
{
QFactory factory = getFactory();
TransactionParticipant participant = (TransactionParticipant)
factory.newInstance (e.getAttributeValue ("class")
);
factory.setLogger (participant, e);
QFactory.invoke (participant, "setTransactionManager", this, TransactionManager.class);
factory.setConfiguration (participant, e);
return participant;
}
public int getOutstandingTransactions() {
if (isp instanceof LocalSpace)
return ((LocalSpace)sp).size(queue);
return -1;
}
protected String getKey (String prefix, long id) {
StringBuffer sb = new StringBuffer (getName());
sb.append ('.');
sb.append (prefix);
sb.append (Long.toString (id));
return sb.toString ();
}
protected long initCounter (String name, long defValue) {
Long L = (Long) psp.rdp (name);
if (L == null) {
L = defValue;
psp.out (name, L);
}
return L;
}
protected void commitOff (Space sp) {
if (sp instanceof JDBMSpace) {
((JDBMSpace) sp).setAutoCommit (false);
}
}
protected void commitOn (Space sp) {
if (sp instanceof JDBMSpace) {
JDBMSpace jsp = (JDBMSpace) sp;
jsp.commit ();
jsp.setAutoCommit (true);
}
}
protected void syncTail () {
synchronized (psp) {
commitOff (psp);
psp.inp (TAIL);
psp.out (TAIL, tail);
commitOn (psp);
}
}
protected void initTailLock () {
tailLock = TAILLOCK + "." + Integer.toString (this.hashCode());
SpaceUtil.wipe (sp, tailLock);
sp.out (tailLock, TAILLOCK);
}
protected void checkTail () {
Object lock = sp.in (tailLock);
while (tailDone()) {
// if (debug) {
// getLog().debug ("tailDone " + tail);
// }
tail++;
}
syncTail ();
sp.out (tailLock, lock);
}
protected boolean tailDone () {
String stateKey = getKey (STATE, tail);
if (DONE.equals (psp.rdp (stateKey))) {
purge (tail);
return true;
}
return false;
}
protected long nextId () {
long h;
synchronized (psp) {
commitOff (psp);
psp.in (HEAD);
h = head;
psp.out (HEAD, ++head);
commitOn (psp);
}
return h;
}
protected void snapshot (long id, Serializable context) {
snapshot (id, context, null);
}
protected void snapshot (long id, Serializable context, Integer status) {
String contextKey = getKey (CONTEXT, id);
synchronized (psp) {
commitOff (psp);
while (psp.inp (contextKey) != null)
;
if (context != null)
psp.out (contextKey, context);
if (status != null) {
String stateKey = getKey (STATE, id);
while (psp.inp (stateKey) != null)
;
psp.out (stateKey, status);
}
commitOn (psp);
}
}
protected void setState (long id, Integer state) {
String stateKey = getKey (STATE, id);
synchronized (psp) {
commitOff (psp);
while (psp.inp (stateKey) != null)
;
if (state!= null)
psp.out (stateKey, state);
commitOn (psp);
}
}
protected void addGroup (long id, String groupName) {
if (groupName != null)
psp.out (getKey (GROUPS, id), groupName);
}
protected void purge (long id) {
String stateKey = getKey (STATE, id);
String contextKey = getKey (CONTEXT, id);
String groupsKey = getKey (GROUPS, id);
synchronized (psp) {
commitOff (psp);
while (psp.inp (stateKey) != null)
;
while (psp.inp (contextKey) != null)
;
while (psp.inp (groupsKey) != null)
;
commitOn (psp);
}
}
protected void recover () {
if (doRecover) {
if (tail < head) {
getLog().info ("recover - tail=" +tail+", head="+head);
}
while (tail < head) {
recover (0, tail++);
}
} else
tail = head;
syncTail ();
}
protected void recover (int session, long id) {
LogEvent evt = getLog().createLogEvent ("recover");
Profiler prof = new Profiler();
evt.addMessage ("<id>" + id + "</id>");
try {
String stateKey = getKey (STATE, id);
String contextKey = getKey (CONTEXT, id);
Integer state = (Integer) psp.rdp (stateKey);
if (state == null) {
evt.addMessage ("unknown stateKey " + stateKey);
SpaceUtil.wipe (psp, contextKey); // just in case ...
return;
}
Serializable context = (Serializable) psp.rdp (contextKey);
if (context != null)
evt.addMessage (context);
if (DONE.equals (state)) {
evt.addMessage ("<done/>");
} else if (COMMITTING.equals (state)) {
commit (session, id, context, getParticipants (id), true, evt, prof);
} else if (PREPARING.equals (state)) {
abort (session, id, context, getParticipants (id), true, evt, prof);
}
purge (id);
} finally {
evt.addMessage (prof);
Logger.log (evt);
}
}
protected synchronized void checkRetryTask () {
if (retryTask == null) {
retryTask = new RetryTask();
new Thread(retryTask).start();
}
}
public class PausedMonitor extends TimerTask {
Pausable context;
public PausedMonitor (Pausable context) {
super();
this.context = context;
}
public void run() {
cancel();
context.getPausedTransaction().forceAbort();
context.resume();
}
}
public class RetryTask implements Runnable {
public void run() {
Thread.currentThread().setName (getName()+"-retry-task");
while (running()) {
for (Object context; (context = psp.rdp (RETRY_QUEUE)) != null;)
{
isp.out (queue, context, retryTimeout);
psp.inp (RETRY_QUEUE);
}
try {
Thread.sleep (retryInterval);
} catch (InterruptedException ignored) { }
}
}
}
public void setDebug (boolean debug) {
this.debug = debug;
}
public boolean getDebug() {
return debug;
}
public int getActiveSessions() {
return activeSessions;
}
public int getRunningSessions() {
return (int) (head - tail);
}
private void notifyStatusListeners
(int session, TransactionStatusEvent.State state, long id, String info, Serializable context)
{
TransactionStatusEvent e = new TransactionStatusEvent(session, state, id, info, context);
synchronized (statusListeners) {
for (TransactionStatusListener l : statusListeners) {
l.update (e);
}
}
}
}
|
Added the ability to define status-listener in xml definition file.
Signed-off-by: Alejandro Revilla <[email protected]>
|
jpos6/modules/txnmgr/src/org/jpos/transaction/TransactionManager.java
|
Added the ability to define status-listener in xml definition file.
|
<ide><path>pos6/modules/txnmgr/src/org/jpos/transaction/TransactionManager.java
<ide>
<ide> import org.jdom.Element;
<ide> import org.jpos.core.Configuration;
<add>import org.jpos.core.Configurable;
<ide> import org.jpos.core.ConfigurationException;
<ide> import org.jpos.q2.QBeanSupport;
<ide> import org.jpos.q2.QFactory;
<ide> String queue;
<ide> String tailLock;
<ide> Thread[] threads;
<del> List<TransactionStatusListener> statusListeners = new ArrayList<TransactionStatusListener>();
<add> final List<TransactionStatusListener> statusListeners = new ArrayList<TransactionStatusListener>();
<ide> boolean hasStatusListeners;
<ide> int activeSessions;
<ide> boolean debug;
<ide>
<ide> groups = new HashMap();
<ide> initParticipants (getPersist());
<add> initStatusListeners (getPersist());
<ide> }
<ide> public void startService () throws Exception {
<ide> NameRegistrar.register (getName (), this);
<ide> }
<ide> return participantsChain;
<ide> }
<add>
<add> protected void initStatusListeners (Element config) throws ConfigurationException{
<add> final Iterator iter = config.getChildren ("status-listener").iterator();
<add> while (iter.hasNext()) {
<add> final Element e = (Element) iter.next();
<add> final QFactory factory = getFactory();
<add> final TransactionStatusListener listener = (TransactionStatusListener) factory.newInstance (e.getAttributeValue ("class"));
<add> factory.setConfiguration (listener, config);
<add> addListener(listener);
<add> }
<add> }
<add>
<ide> protected void initParticipants (Element config)
<ide> throws ConfigurationException
<ide> {
|
|
Java
|
agpl-3.0
|
159a7f34b928f76527364af3065204827359afa6
| 0 |
VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2018 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
public enum DRIdempotencyResult {
SUCCESS((byte) 0, false), // Is the expected next DR ID
DUPLICATE((byte) -1, true), // Is a duplicate DR ID seen before
GAP((byte) 1, true), // Is way in the future
AMBIGUOUS((byte) -2, false); // DR was applied to a new partition that did not have a tracker
private final byte m_id;
private final boolean m_failure;
DRIdempotencyResult(byte id, boolean failure) {
m_id = id;
m_failure = failure;
}
public byte id() {
return m_id;
}
public boolean isFailure() {
return m_failure;
}
public static DRIdempotencyResult fromID(byte id) {
if (SUCCESS.id() == id) {
return SUCCESS;
} else if (DUPLICATE.id() == id) {
return DUPLICATE;
} else if (GAP.id() == id) {
return GAP;
} else if (AMBIGUOUS.id() == id) {
return AMBIGUOUS;
} else {
throw new IllegalArgumentException("Invalid DRIdempotencyResult ID " + id);
}
}
}
|
src/frontend/org/voltdb/DRIdempotencyResult.java
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2018 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
public enum DRIdempotencyResult {
SUCCESS((byte) 0), // Is the expect next DR ID
DUPLICATE((byte) -1), // Is a duplicate DR ID seen before
GAP((byte) 1); // Is way in the future
private final byte m_id;
DRIdempotencyResult(byte id) {
m_id = id;
}
public byte id() {
return m_id;
}
public static DRIdempotencyResult fromID(byte id) {
if (SUCCESS.id() == id) {
return SUCCESS;
} else if (DUPLICATE.id() == id) {
return DUPLICATE;
} else if (GAP.id() == id) {
return GAP;
} else {
throw new IllegalArgumentException("Invalid DRIdempotencyResult ID " + id);
}
}
}
|
ENG-14537: Add AMBIGUOUS DRIdempotencyResult
ApplyBinaryLogMP will apply a binary log if it does not have a logId
for the partition. This can happen at the start of a join. That can
occur on some sites while a different result is returned by other sites.
|
src/frontend/org/voltdb/DRIdempotencyResult.java
|
ENG-14537: Add AMBIGUOUS DRIdempotencyResult
|
<ide><path>rc/frontend/org/voltdb/DRIdempotencyResult.java
<ide> package org.voltdb;
<ide>
<ide> public enum DRIdempotencyResult {
<del> SUCCESS((byte) 0), // Is the expect next DR ID
<del> DUPLICATE((byte) -1), // Is a duplicate DR ID seen before
<del> GAP((byte) 1); // Is way in the future
<add> SUCCESS((byte) 0, false), // Is the expected next DR ID
<add> DUPLICATE((byte) -1, true), // Is a duplicate DR ID seen before
<add> GAP((byte) 1, true), // Is way in the future
<add> AMBIGUOUS((byte) -2, false); // DR was applied to a new partition that did not have a tracker
<ide>
<ide> private final byte m_id;
<del> DRIdempotencyResult(byte id) {
<add> private final boolean m_failure;
<add>
<add> DRIdempotencyResult(byte id, boolean failure) {
<ide> m_id = id;
<add> m_failure = failure;
<ide> }
<ide>
<ide> public byte id() {
<ide> return m_id;
<add> }
<add>
<add> public boolean isFailure() {
<add> return m_failure;
<ide> }
<ide>
<ide> public static DRIdempotencyResult fromID(byte id) {
<ide> return DUPLICATE;
<ide> } else if (GAP.id() == id) {
<ide> return GAP;
<add> } else if (AMBIGUOUS.id() == id) {
<add> return AMBIGUOUS;
<ide> } else {
<ide> throw new IllegalArgumentException("Invalid DRIdempotencyResult ID " + id);
<ide> }
|
|
Java
|
apache-2.0
|
114d7a99bf42ce965e29a4a3a0b4a8ca15643957
| 0 |
alphadev-net/drive-mount
|
/**
* Copyright © 2014 Jan Seeger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.alphadev.fat32wrapper;
import net.alphadev.usbstorage.api.FileAttribute;
import net.alphadev.usbstorage.api.FileHandle;
import net.alphadev.usbstorage.api.FileSystemProvider;
import net.alphadev.usbstorage.api.Path;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import de.waldheinz.fs.FsDirectoryEntry;
import de.waldheinz.fs.fat.FatFile;
import de.waldheinz.fs.fat.FatFileSystem;
import de.waldheinz.fs.fat.FatLfnDirectory;
import de.waldheinz.fs.fat.FatLfnDirectoryEntry;
/**
* @author Jan Seeger <[email protected]>
*/
public class Fat32Provider implements FileSystemProvider {
private final FatFileSystem fs;
public Fat32Provider(FatFileSystem fs) {
this.fs = fs;
}
@Override
public boolean isDirectory(Path path) {
final FatLfnDirectoryEntry file = getEntry(path);
return file != null && file.isDirectory();
}
@Override
public Iterable<Path> getEntries(Path path) {
final List<Path> entries = new ArrayList<>();
FatLfnDirectory directory;
if (path.isRoot()) {
directory = fs.getRoot();
} else {
directory = getDirectoryOrNull(getEntry(path));
}
if (directory != null) {
for (FsDirectoryEntry entry : directory) {
if(entry.getName().equals(".") || entry.getName().equals("..")) {
continue;
}
Path file= Path.createWithAppended(path, entry.getName());
entries.add(file);
}
}
return entries;
}
@Override
public Object getAttribute(Path path, FileAttribute attr) {
switch (attr) {
case FILESIZE:
return getFileSize(path);
case LAST_MODIFIED:
return getLastModified(path);
default:
return null;
}
}
private long getFileSize(Path path) {
final FatFile file = getFileOrNull(path);
return file != null ? file.getLength() : 0;
}
private long getLastModified(Path path) {
final FatLfnDirectoryEntry entry = getEntry(path);
if (entry != null && entry.isFile()) {
try {
return entry.getLastModified();
} catch (IOException e) {
return 0;
}
}
return 0;
}
@Override
public FileHandle openDocument(Path path) {
final FatFile fatFile = getFileOrNull(path);
return new FileHandle() {
@Override
public InputStream readDocument() {
return new ReadingFileHandle(fatFile);
}
};
}
private FatLfnDirectoryEntry getEntry(Path path) {
FatLfnDirectory lastDir = fs.getRoot();
FatLfnDirectoryEntry lastEntry = null;
for (String segment : path.getIterator()) {
if (lastDir != null) {
lastEntry = lastDir.getEntry(segment);
lastDir = getDirectoryOrNull(lastEntry);
}
}
return lastEntry;
}
private FatFile getFileOrNull(Path path) {
final FatLfnDirectoryEntry entry = getEntry(path);
if (entry != null && entry.isFile()) {
try {
return entry.getFile();
} catch (IOException e) {
// yeah, we already checked!
}
}
return null;
}
private FatLfnDirectory getDirectoryOrNull(FatLfnDirectoryEntry entry) {
if (entry.isDirectory()) {
try {
return entry.getDirectory();
} catch (IOException e) {
// don't care just return null
}
}
return null;
}
}
|
fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java
|
/**
* Copyright © 2014 Jan Seeger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.alphadev.fat32wrapper;
import net.alphadev.usbstorage.api.FileAttribute;
import net.alphadev.usbstorage.api.FileHandle;
import net.alphadev.usbstorage.api.FileSystemProvider;
import net.alphadev.usbstorage.api.Path;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import de.waldheinz.fs.FsDirectoryEntry;
import de.waldheinz.fs.fat.FatFile;
import de.waldheinz.fs.fat.FatFileSystem;
import de.waldheinz.fs.fat.FatLfnDirectory;
import de.waldheinz.fs.fat.FatLfnDirectoryEntry;
/**
* @author Jan Seeger <[email protected]>
*/
public class Fat32Provider implements FileSystemProvider {
private final FatFileSystem fs;
public Fat32Provider(FatFileSystem fs) {
this.fs = fs;
}
@Override
public boolean isDirectory(Path path) {
final FatLfnDirectoryEntry file = getEntry(path);
return file != null && file.isDirectory();
}
@Override
public Iterable<Path> getEntries(Path path) {
final List<Path> entries = new ArrayList<>();
FatLfnDirectory directory;
if (path.isRoot()) {
directory = fs.getRoot();
} else {
directory = getDirectoryOrNull(getEntry(path));
}
if (directory != null) {
for (FsDirectoryEntry entry : directory) {
entries.add(Path.createWithAppended(path, entry.getName()));
}
}
return entries;
}
@Override
public Object getAttribute(Path path, FileAttribute attr) {
switch (attr) {
case FILESIZE:
return getFileSize(path);
case LAST_MODIFIED:
return getLastModified(path);
default:
return null;
}
}
private long getFileSize(Path path) {
final FatFile file = getFileOrNull(path);
return file != null ? file.getLength() : 0;
}
private long getLastModified(Path path) {
final FatLfnDirectoryEntry entry = getEntry(path);
if (entry != null && entry.isFile()) {
try {
return entry.getLastModified();
} catch (IOException e) {
return 0;
}
}
return 0;
}
@Override
public FileHandle openDocument(Path path) {
final FatFile fatFile = getFileOrNull(path);
return new FileHandle() {
@Override
public InputStream readDocument() {
return new ReadingFileHandle(fatFile);
}
};
}
private FatLfnDirectoryEntry getEntry(Path path) {
FatLfnDirectory lastDir = fs.getRoot();
FatLfnDirectoryEntry lastEntry = null;
for (String segment : path.getIterator()) {
if (lastDir != null) {
lastEntry = lastDir.getEntry(segment);
lastDir = getDirectoryOrNull(lastEntry);
}
}
return lastEntry;
}
private FatFile getFileOrNull(Path path) {
final FatLfnDirectoryEntry entry = getEntry(path);
if (entry != null && entry.isFile()) {
try {
return entry.getFile();
} catch (IOException e) {
// yeah, we already checked!
}
}
return null;
}
private FatLfnDirectory getDirectoryOrNull(FatLfnDirectoryEntry entry) {
if (entry.isDirectory()) {
try {
return entry.getDirectory();
} catch (IOException e) {
// don't care just return null
}
}
return null;
}
}
|
filter out directory self reference and parent directory entries when iterating directory contents.
let android saf handle navigation.
fixes #61.
|
fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java
|
filter out directory self reference and parent directory entries when iterating directory contents. let android saf handle navigation.
|
<ide><path>at32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java
<ide>
<ide> if (directory != null) {
<ide> for (FsDirectoryEntry entry : directory) {
<del> entries.add(Path.createWithAppended(path, entry.getName()));
<add> if(entry.getName().equals(".") || entry.getName().equals("..")) {
<add> continue;
<add> }
<add>
<add> Path file= Path.createWithAppended(path, entry.getName());
<add> entries.add(file);
<ide> }
<ide> }
<ide>
|
|
Java
|
agpl-3.0
|
9cd9a36542354f345458891156734cdf316cb737
| 0 |
geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit
|
/*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the GNU Affero General Public License, Version 3 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.coeus.propdev.impl.core;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.kuali.coeus.common.framework.compliance.exemption.ExemptionType;
import org.kuali.coeus.common.framework.keyword.ScienceKeyword;
import org.kuali.coeus.common.notification.impl.bo.KcNotification;
import org.kuali.coeus.common.notification.impl.bo.NotificationTypeRecipient;
import org.kuali.coeus.common.notification.impl.service.KcNotificationService;
import org.kuali.coeus.common.framework.person.PropAwardPersonRole;
import org.kuali.coeus.common.questionnaire.framework.answer.Answer;
import org.kuali.coeus.common.questionnaire.framework.answer.AnswerHeader;
import org.kuali.coeus.common.framework.compliance.core.SaveDocumentSpecialReviewEvent;
import org.kuali.coeus.propdev.impl.datavalidation.ProposalDevelopmentDataValidationConstants;
import org.kuali.coeus.propdev.impl.datavalidation.ProposalDevelopmentDataValidationItem;
import org.kuali.coeus.propdev.impl.docperm.ProposalRoleTemplateService;
import org.kuali.coeus.propdev.impl.docperm.ProposalUserRoles;
import org.kuali.coeus.propdev.impl.keyword.PropScienceKeyword;
import org.kuali.coeus.propdev.impl.notification.ProposalDevelopmentNotificationContext;
import org.kuali.coeus.propdev.impl.notification.ProposalDevelopmentNotificationRenderer;
import org.kuali.coeus.propdev.impl.person.ProposalPerson;
import org.kuali.coeus.propdev.impl.person.ProposalPersonCoiIntegrationService;
import org.kuali.coeus.common.framework.auth.perm.KcAuthorizationService;
import org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiography;
import org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiographyService;
import org.kuali.coeus.propdev.impl.specialreview.ProposalSpecialReview;
import org.kuali.coeus.propdev.impl.specialreview.ProposalSpecialReviewExemption;
import org.kuali.coeus.sys.framework.controller.KcCommonControllerService;
import org.kuali.coeus.sys.framework.controller.UifExportControllerService;
import org.kuali.coeus.sys.framework.gv.GlobalVariableService;
import org.kuali.coeus.propdev.impl.auth.perm.ProposalDevelopmentPermissionsService;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.coeus.sys.framework.validation.AuditHelper;
import org.kuali.coeus.sys.impl.validation.DataValidationItem;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.RoleConstants;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.criteria.QueryByCriteria;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.core.api.util.RiceKeyConstants;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.krad.data.DataObjectService;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.document.DocumentBase;
import org.kuali.rice.krad.document.TransactionalDocumentControllerService;
import org.kuali.rice.krad.exception.ValidationException;
import org.kuali.rice.krad.rules.rule.event.DocumentEventBase;
import org.kuali.rice.krad.service.DocumentAdHocService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.LegacyDataAdapter;
import org.kuali.rice.krad.service.PessimisticLockService;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.MessageMap;
import org.kuali.rice.krad.web.form.DialogResponse;
import org.kuali.rice.krad.web.form.DocumentFormBase;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.kuali.rice.krad.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import edu.mit.kc.coi.KcCoiLinkService;
import edu.mit.kc.infrastructure.KcMitConstants;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public abstract class ProposalDevelopmentControllerBase {
protected static final String PROPDEV_DEFAULT_VIEW_ID = "PropDev-DefaultView";
private static final String CONFIRM_MY_COI_DIALOG_ID = "PropDev-Personal-CoiQuestionDialog";
@Autowired
@Qualifier("uifExportControllerService")
private UifExportControllerService uifExportControllerService;
@Autowired
@Qualifier("kcCommonControllerService")
private KcCommonControllerService kcCommonControllerService;
@Autowired
@Qualifier("collectionControllerService")
private CollectionControllerService collectionControllerService;
@Autowired
@Qualifier("fileControllerService")
private FileControllerService fileControllerService;
@Autowired
@Qualifier("modelAndViewService")
private ModelAndViewService modelAndViewService;
@Autowired
@Qualifier("navigationControllerService")
private NavigationControllerService navigationControllerService;
@Autowired
@Qualifier("queryControllerService")
private QueryControllerService queryControllerService;
@Autowired
@Qualifier("refreshControllerService")
private RefreshControllerService refreshControllerService;
@Autowired
@Qualifier("transactionalDocumentControllerService")
private TransactionalDocumentControllerService transactionalDocumentControllerService;
@Autowired
@Qualifier("documentService")
private DocumentService documentService;
@Autowired
@Qualifier("kcAuthorizationService")
private KcAuthorizationService kraAuthorizationService;
@Autowired
@Qualifier("proposalDevelopmentService")
private ProposalDevelopmentService proposalDevelopmentService;
@Autowired
@Qualifier("proposalDevelopmentPermissionsService")
private ProposalDevelopmentPermissionsService proposalDevelopmentPermissionsService;
@Autowired
@Qualifier("legacyDataAdapter")
private LegacyDataAdapter legacyDataAdapter;
@Autowired
@Qualifier("proposalRoleTemplateService")
private ProposalRoleTemplateService proposalRoleTemplateService;
@Autowired
@Qualifier("dataObjectService")
private DataObjectService dataObjectService;
@Autowired
@Qualifier("globalVariableService")
private GlobalVariableService globalVariableService;
@Autowired
@Qualifier("proposalPersonBiographyService")
private ProposalPersonBiographyService proposalPersonBiographyService;
@Autowired
@Qualifier("documentAdHocService")
private DocumentAdHocService documentAdHocService;
@Autowired
@Qualifier("auditHelper")
private AuditHelper auditHelper;
@Autowired
@Qualifier("pessimisticLockService")
private PessimisticLockService pessimisticLockService;
@Autowired
@Qualifier("kcNotificationService")
private KcNotificationService kcNotificationService;
@Autowired
@Qualifier("parameterService")
private ParameterService parameterService;
@Autowired
@Qualifier("kualiConfigurationService")
private ConfigurationService kualiConfigurationService;
@Autowired
@Qualifier("proposalPersonCoiIntegrationService")
private ProposalPersonCoiIntegrationService proposalPersonCoiIntegrationService;
private transient boolean updatedToCoi = false;
protected DocumentFormBase createInitialForm(HttpServletRequest request) {
return new ProposalDevelopmentDocumentForm();
}
@ModelAttribute(value = "KualiForm")
public UifFormBase initForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
UifFormBase form = getKcCommonControllerService().initForm(this.createInitialForm(request), request, response);
return form;
}
private final Logger LOGGER = Logger.getLogger(ProposalDevelopmentSubmitController.class);
public KcCoiLinkService kcCoiLinkService;
public KcCoiLinkService getKcCoiLinkService() {
if (kcCoiLinkService == null) {
kcCoiLinkService = KcServiceLocator.getService(KcCoiLinkService.class);
}
return kcCoiLinkService;
}
public void setKcCoiLinkService(KcCoiLinkService kcCoiLinkService) {
this.kcCoiLinkService = kcCoiLinkService;
}
/**
* Create the original set of Proposal Users for a new Proposal Development Document.
* The creator the proposal is assigned to the AGGREGATOR role.
*/
protected void initializeProposalUsers(ProposalDevelopmentDocument doc) {
// Assign the creator of the proposal to the AGGREGATOR role.
String userId = GlobalVariables.getUserSession().getPrincipalId();
if (!kraAuthorizationService.hasDocumentLevelRole(userId, RoleConstants.AGGREGATOR, doc))
kraAuthorizationService.addDocumentLevelRole(userId, RoleConstants.AGGREGATOR, doc);
// Add the users defined in the role templates for the proposal's lead unit
proposalRoleTemplateService.addUsers(doc);
}
protected void initialSave(ProposalDevelopmentDocument proposalDevelopmentDocument) {
preSave(proposalDevelopmentDocument);
proposalDevelopmentService.initializeUnitOrganizationLocation(
proposalDevelopmentDocument);
proposalDevelopmentService.initializeProposalSiteNumbers(
proposalDevelopmentDocument);
}
protected void preSave(ProposalDevelopmentDocument proposalDevelopmentDocument) {
if (proposalDevelopmentDocument.isDefaultDocumentDescription()) {
proposalDevelopmentDocument.setDefaultDocumentDescription();
}
}
public ModelAndView save(ProposalDevelopmentDocumentForm form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
return save(form);
}
public ModelAndView save(ProposalDevelopmentDocumentForm form) throws Exception {
ProposalDevelopmentDocument proposalDevelopmentDocument = (ProposalDevelopmentDocument) form.getDocument();
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.PROP_DEV_PERMISSIONS_PAGE)) {
saveDocumentPermissions(form);
}
DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_MY_COI_DIALOG_ID);
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.KEY_PERSONNEL_PAGE) ||
StringUtils.equalsIgnoreCase(form.getPageId(),"PropDev-CertificationView-Page")){
String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
if (StringUtils.isBlank(pageId)){
if(dialogResponse!=null){
boolean confirmResetDefault = dialogResponse.getResponseAsBoolean();
if(confirmResetDefault){
String coiApplicationUrl = getKualiConfigurationService().getPropertyValueAsString(KcMitConstants.MIT_COEUS_COI_APPLICATION_URL);
if(coiApplicationUrl!=null){
return getModelAndViewService().performRedirect(form, coiApplicationUrl);
}
}else{
return getModelAndViewService().getModelAndView(form, pageId);
}
}
}
}
if (StringUtils.equalsIgnoreCase(form.getPageId(), ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID)) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).populateAttachmentReferences(form.getDevelopmentProposal());
}
if (getGlobalVariableService().getMessageMap().getErrorCount() == 0 && form.getEditableCollectionLines() != null) {
form.getEditableCollectionLines().clear();
}
if (StringUtils.equalsIgnoreCase(form.getPageId(), ProposalDevelopmentDataValidationConstants.DETAILS_PAGE_ID)) {
handleSponsorChange(proposalDevelopmentDocument);
}
preSave(proposalDevelopmentDocument);
proposalDevelopmentService.initializeUnitOrganizationLocation(
proposalDevelopmentDocument);
proposalDevelopmentService.initializeProposalSiteNumbers(
proposalDevelopmentDocument);
for (ProposalPersonBiography biography : form.getDevelopmentProposal().getPropPersonBios()) {
getProposalPersonBiographyService().prepareProposalPersonBiographyForSave(form.getDevelopmentProposal(),biography);
}
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).setOrdinalPosition(form.getDevelopmentProposal().getProposalPersons());
saveAnswerHeaders(form, form.getPageId());
getTransactionalDocumentControllerService().save(form);
if (form.isAuditActivated()){
getAuditHelper().auditConditionally(form);
}
populateAdHocRecipients(form.getProposalDevelopmentDocument());
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.CREDIT_ALLOCATION_PAGE)) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).populateCreditSplits(form);
}
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.QUESTIONS_PAGE)) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).populateQuestionnaires(form);
}
String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
ModelAndView view = null;
if (StringUtils.isNotBlank(pageId) && getGlobalVariableService().getMessageMap().hasNoErrors()) {
form.setDirtyForm(false);
view = getModelAndViewService().getModelAndView(form, pageId);
} else {
view = getModelAndViewService().getModelAndView(form);
}
if (form.getProposalDevelopmentDocument().getDevelopmentProposal() != null
&& form.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews() != null) {
for (ProposalSpecialReview specialReview : form.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews()) {
if (!specialReview.isLinkedToProtocol()) {
form.getSpecialReviewHelper().prepareProtocolLinkViewFields(specialReview);
}
}
}
if(StringUtils.isBlank(pageId) && dialogResponse == null && isUpdatedToCoi()){
form.setCoiIntegrationMessage(getKualiConfigurationService().getPropertyValueAsString(KcMitConstants.COI_QUESTION_ANSWERED));
view = getModelAndViewService().showDialog("PropDev-Personal-CoiQuestionDialog", true, form);
}
return view;
}
public ModelAndView save(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response, Class<? extends DocumentEventBase> eventClazz) throws Exception {
ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) form;
ProposalDevelopmentDocument proposalDevelopmentDocument = (ProposalDevelopmentDocument) pdForm.getDocument();
proposalDevelopmentService.initializeUnitOrganizationLocation(
proposalDevelopmentDocument);
proposalDevelopmentService.initializeProposalSiteNumbers(
proposalDevelopmentDocument);
ModelAndView view = null;
saveAnswerHeaders(pdForm,request.getParameter(UifParameters.PAGE_ID));
if (eventClazz == null) {
getTransactionalDocumentControllerService().save(form);
} else {
performCustomSave(proposalDevelopmentDocument, SaveDocumentSpecialReviewEvent.class);
}
populateAdHocRecipients(pdForm.getProposalDevelopmentDocument());
String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
if (StringUtils.isNotBlank(pageId) && getGlobalVariableService().getMessageMap().hasNoErrors()) {
form.setDirtyForm(false);
view = getModelAndViewService().getModelAndView(form, pageId);
} else {
view = getModelAndViewService().getModelAndView(form);
}
if (pdForm.getProposalDevelopmentDocument().getDevelopmentProposal() != null
&& pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews() != null) {
for (ProposalSpecialReview specialReview : pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews()) {
if (!specialReview.isLinkedToProtocol()) {
pdForm.getSpecialReviewHelper().prepareProtocolLinkViewFields(specialReview);
}
}
}
return view;
}
protected void performCustomSave(DocumentBase document, Class<? extends DocumentEventBase> eventClazz) {
try {
getDocumentService().saveDocument(document, eventClazz);
GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_MESSAGES, RiceKeyConstants.MESSAGE_SAVED);
} catch (ValidationException e) {
// if errors in map, swallow exception so screen will draw with errors
// if not then throw runtime because something bad happened
if (GlobalVariables.getMessageMap().hasNoErrors()) {
throw new RiceRuntimeException("Validation Exception with no error message.", e);
}
} catch (Exception e) {
throw new RiceRuntimeException(
"Exception trying to save document: " + document
.getDocumentNumber(), e);
}
}
protected ModelAndView navigate(ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (form.getDevelopmentProposal().getS2sOpportunity() != null && !getProposalDevelopmentService().isGrantsGovEnabledForProposal(form.getDevelopmentProposal())) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).clearOpportunity(form.getDevelopmentProposal());
}
populateAdHocRecipients(form.getProposalDevelopmentDocument());
String navigateToPageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
boolean canEdit = form.isCanEditView();
if (isNavigateToDeliveryInfoPage(navigateToPageId)) {
if (form.getDevelopmentProposal().getS2sOpportunity() != null) {
getGlobalVariableService().getMessageMap().putInfo(ProposalDevelopmentConstants.KradConstants.DELIVERY_INFO_PAGE, KeyConstants.DELIVERY_INFO_NOT_NEEDED);
}
}
if (isNavigateAwayFromAttachment(navigateToPageId, form.getPageId())) {
prepareLocks(form);
return narrativePageSave(form, canEdit);
} else if (isNavigateToAttachments(navigateToPageId) ||
isNavigateAwayFromAccess(navigateToPageId,form.getPageId()) ||
isNavigateToAccess(navigateToPageId)) {
prepareLocks(form);
}
return proposalDevelopmentPageSave(form, canEdit);
}
protected void prepareLocks(ProposalDevelopmentDocumentForm form) {
releasePessimisticLocks(form);
form.setEvaluateFlagsAndModes(true);
form.setCanEditView(null);
}
protected ModelAndView proposalDevelopmentPageSave(ProposalDevelopmentDocumentForm form, boolean canEdit) throws Exception {
ProposalDevelopmentDocument document = (ProposalDevelopmentDocument) getDocumentService().getByDocumentHeaderId(form.getDocument().getDocumentNumber());
if (canEdit) {
//when saving on page in the proposal development locking region we don't want to over write attachments that
//may have been alter concurrently. So we retrieve the latest proposal data from the db, and replace the attachment
//collections with the values from the db.
if (!StringUtils.equals(form.getPageId(),Constants.PROP_DEV_PERMISSIONS_PAGE)) {
form.getDevelopmentProposal().setNarratives(document.getDevelopmentProposal().getNarratives());
form.getDevelopmentProposal().setInstituteAttachments(document.getDevelopmentProposal().getInstituteAttachments());
form.getDevelopmentProposal().setPropPersonBios(document.getDevelopmentProposal().getPropPersonBios());
form.getDevelopmentProposal().setProposalAbstracts(document.getDevelopmentProposal().getProposalAbstracts());
form.getDocument().setNotes(document.getNotes());
form.getDocument().setDocumentHeader(document.getDocumentHeader());
}
return save(form);
} else {
form.setDocument(document);
return getNavigationControllerService().navigate(form);
}
}
protected ModelAndView narrativePageSave(ProposalDevelopmentDocumentForm form, boolean canEdit) throws Exception {
ProposalDevelopmentDocument document = (ProposalDevelopmentDocument) getDocumentService().getByDocumentHeaderId(form.getDocument().getDocumentNumber());
if (canEdit) {
if ((new ProposalDevelopmentDocumentRule().processAttachmentRules(form.getProposalDevelopmentDocument()))
&& (new ProposalDevelopmentDocumentRule().processPersonnelAttachmentDuplicates(form.getProposalDevelopmentDocument()))) {
form.getProposalDevelopmentAttachmentHelper().handleNarrativeUpdates(form, document);
form.getProposalDevelopmentAttachmentHelper().handleInstAttachmentUpdates(form, document);
form.getProposalDevelopmentAttachmentHelper().handlePersonBioUpdates(form, document);
document.getDevelopmentProposal().setProposalAbstracts(form.getDevelopmentProposal().getProposalAbstracts());
document.setNotes(form.getDocument().getNotes());
form.setDocument(document);
return save(form);
} else {
form.setCanEditView(canEdit);
return getModelAndViewService().getModelAndView(form);
}
} else {
form.setDocument(document);
return getNavigationControllerService().navigate(form);
}
}
protected boolean isNavigateToAttachments(String navigateToPageId) {
return StringUtils.equals(navigateToPageId,ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID);
}
protected boolean isNavigateToAccess(String navigateToPageId) {
return StringUtils.equals(navigateToPageId,Constants.PROP_DEV_PERMISSIONS_PAGE);
}
protected boolean isNavigateAwayFromAccess(String navigateToPageId, String pageId) {
return StringUtils.equals(pageId,Constants.PROP_DEV_PERMISSIONS_PAGE) &&
!StringUtils.equals(navigateToPageId,Constants.PROP_DEV_PERMISSIONS_PAGE);
}
protected boolean isNavigateAwayFromAttachment(String navigateToPageId, String pageId) {
return StringUtils.equals(pageId,ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID) &&
!StringUtils.equals(navigateToPageId,ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID);
}
protected boolean isNavigateToDeliveryInfoPage(String navigateToPageId) {
return StringUtils.equals(navigateToPageId, ProposalDevelopmentConstants.KradConstants.DELIVERY_INFO_PAGE);
}
protected void releasePessimisticLocks(DocumentFormBase form) {
Document document = form.getDocument();
if (!document.getPessimisticLocks().isEmpty()) {
Person user = getGlobalVariableService().getUserSession().getPerson();
document.refreshPessimisticLocks();
getPessimisticLockService().releaseAllLocksForUser(document.getPessimisticLocks(), user);
}
}
public void addEditableCollectionLine(ProposalDevelopmentDocumentForm form, String selectedCollectionPath){
if(form.getEditableCollectionLines().containsKey(selectedCollectionPath)) {
updateEditableCollectionLines(form, selectedCollectionPath);
} else {
List<String> newKeyList = new ArrayList<String>();
newKeyList.add("0");
form.getEditableCollectionLines().put(selectedCollectionPath,newKeyList);
}
}
public void updateEditableCollectionLines(ProposalDevelopmentDocumentForm form, String selectedCollectionPath){
List<String> indexes = new ArrayList<String>();
indexes.add("0");
for (String index : form.getEditableCollectionLines().get(selectedCollectionPath)) {
Integer newIndex= Integer.parseInt(index) + 1;
indexes.add(newIndex.toString());
}
form.getEditableCollectionLines().get(selectedCollectionPath).clear();
form.getEditableCollectionLines().get(selectedCollectionPath).addAll(indexes);
}
protected KcAuthorizationService getKraAuthorizationService() {
return kraAuthorizationService;
}
public void setKraAuthorizationService(KcAuthorizationService kraAuthorizationService) {
this.kraAuthorizationService = kraAuthorizationService;
}
protected ProposalDevelopmentService getProposalDevelopmentService() {
return proposalDevelopmentService;
}
public void setProposalDevelopmentService(ProposalDevelopmentService proposalDevelopmentService) {
this.proposalDevelopmentService = proposalDevelopmentService;
}
protected TransactionalDocumentControllerService getTransactionalDocumentControllerService() {
return transactionalDocumentControllerService;
}
public void setTransactionalDocumentControllerService(TransactionalDocumentControllerService transactionalDocumentControllerService) {
this.transactionalDocumentControllerService = transactionalDocumentControllerService;
}
protected DocumentService getDocumentService() {
return documentService;
}
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
protected LegacyDataAdapter getLegacyDataAdapter() {
return legacyDataAdapter;
}
public void setLegacyDataAdapter(LegacyDataAdapter legacyDataAdapter) {
this.legacyDataAdapter = legacyDataAdapter;
}
protected ProposalRoleTemplateService getProposalRoleTemplateService() {
return proposalRoleTemplateService;
}
public void setProposalRoleTemplateService(
ProposalRoleTemplateService proposalRoleTemplateService) {
this.proposalRoleTemplateService = proposalRoleTemplateService;
}
protected DataObjectService getDataObjectService() {
return dataObjectService;
}
public void setDataObjectService(DataObjectService dataObjectService) {
this.dataObjectService = dataObjectService;
}
public void saveAnswerHeaders(ProposalDevelopmentDocumentForm pdForm,String pageId) {
boolean allCertificationsWereComplete = true;
boolean allCertificationAreNowComplete = true;
setUpdatedToCoi(false);
if (StringUtils.equalsIgnoreCase(pageId, Constants.KEY_PERSONNEL_PAGE) ||
StringUtils.equalsIgnoreCase(pageId,"PropDev-CertificationView-Page")) {
for (ProposalPerson person : pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) {
if (person.getQuestionnaireHelper() != null && person.getQuestionnaireHelper().getAnswerHeaders() != null
&& !person.getQuestionnaireHelper().getAnswerHeaders().isEmpty()) {
for (AnswerHeader answerHeader : person.getQuestionnaireHelper().getAnswerHeaders()) {
boolean wasComplete = answerHeader.isCompleted();
allCertificationsWereComplete &= wasComplete;
getLegacyDataAdapter().save(answerHeader);
person.getQuestionnaireHelper().populateAnswers();
boolean isComplete = person.getQuestionnaireHelper().getAnswerHeaders().get(0).isCompleted();
allCertificationAreNowComplete &= isComplete;
if(isComplete && !wasComplete){
person.setCertifiedBy(getGlobalVariableService().getUserSession().getPrincipalId());
person.setCertifiedTime(((DateTimeService) KcServiceLocator.getService(Constants.DATE_TIME_SERVICE_NAME)).getCurrentTimestamp());
}else if(wasComplete && !isComplete){
person.setCertifiedBy(null);
person.setCertifiedTime(null);
}
if(!isUpdatedToCoi()){
setUpdatedToCoi(updateCOIOnPDCerificationComplete(pdForm,person,isComplete || wasComplete,answerHeader));
}else{
updateCOIOnPDCerificationComplete(pdForm,person,isComplete || wasComplete,answerHeader);
}
checkForCertifiedByProxy(pdForm.getDevelopmentProposal(),person,isComplete && !wasComplete,wasComplete);
}
}
}
} else if (StringUtils.equalsIgnoreCase(pageId, Constants.QUESTIONS_PAGE)) {
for (AnswerHeader answerHeader : pdForm.getQuestionnaireHelper().getAnswerHeaders()) {
getLegacyDataAdapter().save(answerHeader);
}
for (AnswerHeader answerHeader : pdForm.getS2sQuestionnaireHelper().getAnswerHeaders()) {
getLegacyDataAdapter().save(answerHeader);
}
}
boolean allowsSendCertificationCompleteNotification = getParameterService().getParameterValueAsBoolean(Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,Constants.PARAMETER_COMPONENT_DOCUMENT,ProposalDevelopmentConstants.Parameters.NOTIFY_ALL_CERTIFICATIONS_COMPLETE);
if (!allCertificationsWereComplete && allCertificationAreNowComplete && allowsSendCertificationCompleteNotification) {
ProposalDevelopmentNotificationContext context = new ProposalDevelopmentNotificationContext(pdForm.getDevelopmentProposal(),"105","All Proposal Persons Certification Completed");
((ProposalDevelopmentNotificationRenderer) context.getRenderer()).setDevelopmentProposal(pdForm.getDevelopmentProposal());
getKcNotificationService().sendNotification(context);
}
}
public boolean updateCOIOnPDCerificationComplete(ProposalDevelopmentDocumentForm pdForm, ProposalPerson person, boolean completed,AnswerHeader answerHeader) {
boolean coiQuestionsAnswered = false;
if(checkForCOIquestions(answerHeader)){
updateToCOI(pdForm,person);
}
coiQuestionsAnswered = getProposalPersonCoiIntegrationService().isCoiQuestionsAnswered(person);
if(coiQuestionsAnswered){
return coiQuestionsAnswered;
}
return coiQuestionsAnswered;
}
private void updateToCOI(ProposalDevelopmentDocumentForm pdForm, ProposalPerson person){
String userName = getGlobalVariableService().getUserSession().getPrincipalName();
try {
getKcCoiLinkService().updateCOIOnPDCerificationComplete(pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalNumber(), person.getPersonId(), userName);
} catch (SQLException e) {
LOGGER.info(Level.ALL, e);
LOGGER.warn("DBLINK is not accessible or the parameter value returning null");
}
}
private boolean checkForCOIquestions(AnswerHeader answerHeader ){
boolean hasCOIquestions = false;
String coiCertificationQuestionIds = getParameterService().getParameterValueAsString("KC-GEN", "All", "PROP_PERSON_COI_CERTIFY_QID");
List<String> coiCertificationQuestionIdList = new ArrayList<String>();
if(coiCertificationQuestionIds!=null){
String[] questionIds = coiCertificationQuestionIds.split(",");
for (String questionid : questionIds){
coiCertificationQuestionIdList.add(questionid);
}
}
for(Answer answer :answerHeader.getAnswers()){
for(String coiCertificationQuestionId : coiCertificationQuestionIdList){
if(coiCertificationQuestionId.equals(answer.getQuestionSeqId().toString())){
hasCOIquestions = true;
break;
}
}
}
return hasCOIquestions;
}
public void checkForCertifiedByProxy(DevelopmentProposal developmentProposal, ProposalPerson person, boolean recentlyCompleted,boolean wasComplete) {
boolean selfCertifyOnly = getParameterService().getParameterValueAsBoolean(Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,Constants.PARAMETER_COMPONENT_DOCUMENT,ProposalDevelopmentConstants.Parameters.KEY_PERSON_CERTIFICATION_SELF_CERTIFY_ONLY);
if (selfCertifyOnly) {
String proxyId = getGlobalVariableService().getUserSession().getPrincipalId();
if (!StringUtils.equals(person.getPersonId(), proxyId) && recentlyCompleted) {
ProposalDevelopmentNotificationContext context = new ProposalDevelopmentNotificationContext(developmentProposal,"106","Proposal Person Certification Completed");
((ProposalDevelopmentNotificationRenderer) context.getRenderer()).setDevelopmentProposal(developmentProposal);
KcNotification notification = getKcNotificationService().createNotificationObject(context);
NotificationTypeRecipient recipient = new NotificationTypeRecipient();
recipient.setPersonId(person.getPersonId());
getKcNotificationService().sendNotification(context,notification,Collections.singletonList(recipient));
}
}
}
/**
* Method calls the permissions service, where it will determine if any user permissions need to be added and/or removed.
*
* @param pdForm ProposalDevelopmentDocumentForm that contains the permissions helper
*/
public void saveDocumentPermissions(ProposalDevelopmentDocumentForm pdForm) {
List<String> editableLines = pdForm.getEditableCollectionLines().get(Constants.PERMISSION_PROPOSAL_USERS_COLLECTION_PROPERTY_KEY);
if (editableLines != null && editableLines.size() > 0) {
getGlobalVariableService().getMessageMap().putErrorForSectionId(Constants.PERMISSION_PROPOSAL_USERS_COLLECTION_ID_KEY, KeyConstants.ERROR_UNFINISHED_PERMISSIONS);
} else if (arePermissionsValid(pdForm.getProposalDevelopmentDocument(),pdForm.getWorkingUserRoles())) {
getProposalDevelopmentPermissionsService().savePermissions(pdForm.getProposalDevelopmentDocument(), getProposalDevelopmentPermissionsService().getPermissions(pdForm.getProposalDevelopmentDocument()), pdForm.getWorkingUserRoles());
}
}
protected boolean arePermissionsValid(ProposalDevelopmentDocument document, List<ProposalUserRoles> proposalUsers) {
boolean retVal = true;
for (ProposalUserRoles proposalUser : proposalUsers) {
retVal &= getProposalDevelopmentPermissionsService().validateUpdatePermissions(document,proposalUsers,proposalUser);
}
return retVal;
}
@InitBinder
protected void initBinder(WebDataBinder binder) throws Exception {
binder.registerCustomEditor(List.class, "document.developmentProposal.propScienceKeywords", new PropScienceKeywordEditor());
binder.registerCustomEditor(List.class, "document.developmentProposal.propSpecialReviews.specialReviewExemptions", new PropSpecialReviewExemptionTypeEditor());
// For add line binding
binder.registerCustomEditor(List.class, "newCollectionLines.specialReviewExemptions", new PropSpecialReviewExemptionTypeEditor());
}
protected class PropScienceKeywordEditor extends CustomCollectionEditor {
public PropScienceKeywordEditor() {
super(List.class, true);
}
protected Object convertElement(Object element) {
if (element != null && element instanceof String) {
return new PropScienceKeyword(null, getScienceKeyword(element));
}
return element;
}
public String getAsText() {
if (this.getValue() != null) {
Collection<PropScienceKeyword> keywords = (Collection<PropScienceKeyword>) this.getValue();
StringBuilder result = new StringBuilder();
for(PropScienceKeyword keyword : keywords) {
result.append(keyword.getScienceKeyword().getCode());
result.append(",");
}
if (result.length() > 0) {
return result.substring(0, result.length() - 1);
}
}
return null;
}
}
/**
* Editor to convert (to and from) a String list of exemption type codes to ProposalSpecialReviewExemption objects
*/
protected class PropSpecialReviewExemptionTypeEditor extends CustomCollectionEditor {
public PropSpecialReviewExemptionTypeEditor() {
super(List.class, true);
}
protected Object convertElement(Object element) {
if (element != null && element instanceof String) {
return new ProposalSpecialReviewExemption(null, getExemptionType(element));
}
return element;
}
public String getAsText() {
if (this.getValue() != null) {
Collection<ProposalSpecialReviewExemption> exemptions = (Collection<ProposalSpecialReviewExemption>) this.getValue();
StringBuilder result = new StringBuilder();
for(ProposalSpecialReviewExemption exemption : exemptions) {
result.append(exemption.getExemptionTypeCode());
result.append(",");
}
if (result.length() > 0) {
return result.substring(0, result.length() - 1);
}
}
return null;
}
}
protected ExemptionType getExemptionType(Object element) {
return (ExemptionType) getDataObjectService().findUnique(ExemptionType.class, QueryByCriteria.Builder.forAttribute("code", element).build());
}
public AuditHelper.ValidationState getValidationState(ProposalDevelopmentDocumentForm form) {
AuditHelper.ValidationState severityLevel = AuditHelper.ValidationState.OK;
form.setAuditActivated(true);
List<DataValidationItem> dataValidationItems = ((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService())
.populateDataValidation(form);
if(dataValidationItems != null && dataValidationItems.size() > 0 ) {
for(DataValidationItem validationItem : dataValidationItems) {
if (StringUtils.endsWith(validationItem.getSeverity(),Constants.AUDIT_ERRORS)) {
severityLevel = AuditHelper.ValidationState.ERROR;
break;
}
if (StringUtils.equals(validationItem.getSeverity(), Constants.AUDIT_WARNINGS)){
severityLevel = AuditHelper.ValidationState.WARNING;
}
}
form.setDataValidationItems(dataValidationItems);
}
getGlobalVariableService().getMessageMap().clearErrorMessages();
return severityLevel;
}
/**
* During navigation and routing the ad hoc recipients which are transient get removed. To solve this, repopulate them in the document before each save.
* This will stop the system from removing the current recipients from the database.
*
* Extra logic added to assist in avoiding the null document number issue.
*/
public void populateAdHocRecipients(ProposalDevelopmentDocument proposalDevelopmentDocument){
if (StringUtils.isEmpty(proposalDevelopmentDocument.getDocumentNumber())
&& proposalDevelopmentDocument.getDocumentHeader() != null && StringUtils.isNotEmpty(proposalDevelopmentDocument.getDocumentHeader().getDocumentNumber())){
proposalDevelopmentDocument.setDocumentNumber(proposalDevelopmentDocument.getDocumentHeader().getDocumentNumber());
}
if (StringUtils.isNotEmpty(proposalDevelopmentDocument.getDocumentNumber())){
getDocumentAdHocService().addAdHocs(proposalDevelopmentDocument);
}
}
/**
*
* If the sponsor has changed, default the key personnel role codes to COI if the role can't be found
*/
public void handleSponsorChange(ProposalDevelopmentDocument proposalDevelopmentDocument){
for (int i=0; i< proposalDevelopmentDocument.getDevelopmentProposal().getProposalPersons().size();i++){
ProposalPerson person = proposalDevelopmentDocument.getDevelopmentProposal().getProposalPersons().get(i);
if (person.getRole() == null){
person.setProposalPersonRoleId(PropAwardPersonRole.CO_INVESTIGATOR);
String propertyName = ProposalDevelopmentConstants.PropertyConstants.PROPOSAL_PERSONS;
getGlobalVariableService().getMessageMap().putInfo(propertyName + "[" + i + "].proposalPersonRoleId", KeyConstants.INFO_PERSONNEL_INVALID_ROLE, person.getDevelopmentProposal().getSponsorCode(), person.getFullName());
}
}
}
public void populateDeferredMessages(ProposalDevelopmentDocumentForm proposalDevelopmentDocumentForm){
if (proposalDevelopmentDocumentForm.getDeferredMessages() != null
&& proposalDevelopmentDocumentForm.getDeferredMessages().hasMessages()){
MessageMap messageMap = proposalDevelopmentDocumentForm.getDeferredMessages();
MessageMap currentMessageMap = getGlobalVariableService().getMessageMap();
messageMap.getErrorMessages().putAll(currentMessageMap.getErrorMessages());
messageMap.getInfoMessages().putAll(currentMessageMap.getInfoMessages());
messageMap.getWarningMessages().putAll(currentMessageMap.getWarningMessages());
getGlobalVariableService().setMessageMap(messageMap);
}
proposalDevelopmentDocumentForm.setDeferredMessages(null);
}
protected ScienceKeyword getScienceKeyword(Object element) {
return getDataObjectService().findUnique(ScienceKeyword.class, QueryByCriteria.Builder.forAttribute("code", element).build());
}
public UifExportControllerService getUifExportControllerService() {
return uifExportControllerService;
}
public void setUifExportControllerService(UifExportControllerService uifExportControllerService) {
this.uifExportControllerService = uifExportControllerService;
}
public KcCommonControllerService getKcCommonControllerService() {
return kcCommonControllerService;
}
public void setKcCommonControllerService(KcCommonControllerService kcCommonControllerService) {
this.kcCommonControllerService = kcCommonControllerService;
}
public CollectionControllerService getCollectionControllerService() {
return collectionControllerService;
}
public void setCollectionControllerService(CollectionControllerService collectionControllerService) {
this.collectionControllerService = collectionControllerService;
}
public FileControllerService getFileControllerService() {
return fileControllerService;
}
public void setFileControllerService(FileControllerService fileControllerService) {
this.fileControllerService = fileControllerService;
}
public ModelAndViewService getModelAndViewService() {
return modelAndViewService;
}
public void setModelAndViewService(ModelAndViewService modelAndViewService) {
this.modelAndViewService = modelAndViewService;
}
public NavigationControllerService getNavigationControllerService() {
return navigationControllerService;
}
public void setNavigationControllerService(NavigationControllerService navigationControllerService) {
this.navigationControllerService = navigationControllerService;
}
public QueryControllerService getQueryControllerService() {
return queryControllerService;
}
public void setQueryControllerService(QueryControllerService queryControllerService) {
this.queryControllerService = queryControllerService;
}
public RefreshControllerService getRefreshControllerService() {
return refreshControllerService;
}
public void setRefreshControllerService(RefreshControllerService refreshControllerService) {
this.refreshControllerService = refreshControllerService;
}
public GlobalVariableService getGlobalVariableService() {
return globalVariableService;
}
public void setGlobalVariableService(GlobalVariableService globalVariableService) {
this.globalVariableService = globalVariableService;
}
protected ProposalDevelopmentPermissionsService getProposalDevelopmentPermissionsService() {
return proposalDevelopmentPermissionsService;
}
public void setProposalDevelopmentPermissionsService(ProposalDevelopmentPermissionsService proposalDevelopmentPermissionsService) {
this.proposalDevelopmentPermissionsService = proposalDevelopmentPermissionsService;
}
public ProposalPersonBiographyService getProposalPersonBiographyService() {
return proposalPersonBiographyService;
}
public void setProposalPersonBiographyService(ProposalPersonBiographyService proposalPersonBiographyService) {
this.proposalPersonBiographyService = proposalPersonBiographyService;
}
public DocumentAdHocService getDocumentAdHocService() {
return documentAdHocService;
}
public void setDocumentAdHocService(DocumentAdHocService documentAdHocService) {
this.documentAdHocService = documentAdHocService;
}
public AuditHelper getAuditHelper() {
return auditHelper;
}
public void setAuditHelper(AuditHelper auditHelper) {
this.auditHelper = auditHelper;
}
public KcNotificationService getKcNotificationService() {
return kcNotificationService;
}
public void setKcNotificationService(KcNotificationService kcNotificationService) {
this.kcNotificationService = kcNotificationService;
}
public ParameterService getParameterService() {
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public PessimisticLockService getPessimisticLockService() {
return pessimisticLockService;
}
public void setPessimisticLockService(PessimisticLockService pessimisticLockService) {
this.pessimisticLockService = pessimisticLockService;
}
public boolean isUpdatedToCoi() {
return updatedToCoi;
}
public void setUpdatedToCoi(boolean updatedToCoi) {
this.updatedToCoi = updatedToCoi;
}
public ConfigurationService getKualiConfigurationService() {
return kualiConfigurationService;
}
public void setKualiConfigurationService(
ConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
public ProposalPersonCoiIntegrationService getProposalPersonCoiIntegrationService() {
return proposalPersonCoiIntegrationService;
}
public void setProposalPersonCoiIntegrationService(
ProposalPersonCoiIntegrationService proposalPersonCoiIntegrationService) {
this.proposalPersonCoiIntegrationService = proposalPersonCoiIntegrationService;
}
}
|
kcmit-impl/src/main/java/org/kuali/coeus/propdev/impl/core/ProposalDevelopmentControllerBase.java
|
/*
* Copyright 2005-2010 The Kuali Foundation
*
* Licensed under the GNU Affero General Public License, Version 3 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.coeus.propdev.impl.core;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.kuali.coeus.common.framework.compliance.exemption.ExemptionType;
import org.kuali.coeus.common.framework.keyword.ScienceKeyword;
import org.kuali.coeus.common.notification.impl.bo.KcNotification;
import org.kuali.coeus.common.notification.impl.bo.NotificationTypeRecipient;
import org.kuali.coeus.common.notification.impl.service.KcNotificationService;
import org.kuali.coeus.common.framework.person.PropAwardPersonRole;
import org.kuali.coeus.common.questionnaire.framework.answer.Answer;
import org.kuali.coeus.common.questionnaire.framework.answer.AnswerHeader;
import org.kuali.coeus.common.framework.compliance.core.SaveDocumentSpecialReviewEvent;
import org.kuali.coeus.propdev.impl.datavalidation.ProposalDevelopmentDataValidationConstants;
import org.kuali.coeus.propdev.impl.datavalidation.ProposalDevelopmentDataValidationItem;
import org.kuali.coeus.propdev.impl.docperm.ProposalRoleTemplateService;
import org.kuali.coeus.propdev.impl.docperm.ProposalUserRoles;
import org.kuali.coeus.propdev.impl.keyword.PropScienceKeyword;
import org.kuali.coeus.propdev.impl.notification.ProposalDevelopmentNotificationContext;
import org.kuali.coeus.propdev.impl.notification.ProposalDevelopmentNotificationRenderer;
import org.kuali.coeus.propdev.impl.person.ProposalPerson;
import org.kuali.coeus.propdev.impl.person.ProposalPersonCoiIntegrationService;
import org.kuali.coeus.common.framework.auth.perm.KcAuthorizationService;
import org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiography;
import org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiographyService;
import org.kuali.coeus.propdev.impl.specialreview.ProposalSpecialReview;
import org.kuali.coeus.propdev.impl.specialreview.ProposalSpecialReviewExemption;
import org.kuali.coeus.sys.framework.controller.KcCommonControllerService;
import org.kuali.coeus.sys.framework.controller.UifExportControllerService;
import org.kuali.coeus.sys.framework.gv.GlobalVariableService;
import org.kuali.coeus.propdev.impl.auth.perm.ProposalDevelopmentPermissionsService;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.coeus.sys.framework.validation.AuditHelper;
import org.kuali.coeus.sys.impl.validation.DataValidationItem;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.RoleConstants;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.criteria.QueryByCriteria;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.core.api.util.RiceKeyConstants;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.krad.data.DataObjectService;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.document.DocumentBase;
import org.kuali.rice.krad.document.TransactionalDocumentControllerService;
import org.kuali.rice.krad.exception.ValidationException;
import org.kuali.rice.krad.rules.rule.event.DocumentEventBase;
import org.kuali.rice.krad.service.DocumentAdHocService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.LegacyDataAdapter;
import org.kuali.rice.krad.service.PessimisticLockService;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.MessageMap;
import org.kuali.rice.krad.web.form.DialogResponse;
import org.kuali.rice.krad.web.form.DocumentFormBase;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.kuali.rice.krad.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import edu.mit.kc.coi.KcCoiLinkService;
import edu.mit.kc.infrastructure.KcMitConstants;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public abstract class ProposalDevelopmentControllerBase {
protected static final String PROPDEV_DEFAULT_VIEW_ID = "PropDev-DefaultView";
private static final String CONFIRM_MY_COI_DIALOG_ID = "PropDev-Personal-CoiQuestionDialog";
@Autowired
@Qualifier("uifExportControllerService")
private UifExportControllerService uifExportControllerService;
@Autowired
@Qualifier("kcCommonControllerService")
private KcCommonControllerService kcCommonControllerService;
@Autowired
@Qualifier("collectionControllerService")
private CollectionControllerService collectionControllerService;
@Autowired
@Qualifier("fileControllerService")
private FileControllerService fileControllerService;
@Autowired
@Qualifier("modelAndViewService")
private ModelAndViewService modelAndViewService;
@Autowired
@Qualifier("navigationControllerService")
private NavigationControllerService navigationControllerService;
@Autowired
@Qualifier("queryControllerService")
private QueryControllerService queryControllerService;
@Autowired
@Qualifier("refreshControllerService")
private RefreshControllerService refreshControllerService;
@Autowired
@Qualifier("transactionalDocumentControllerService")
private TransactionalDocumentControllerService transactionalDocumentControllerService;
@Autowired
@Qualifier("documentService")
private DocumentService documentService;
@Autowired
@Qualifier("kcAuthorizationService")
private KcAuthorizationService kraAuthorizationService;
@Autowired
@Qualifier("proposalDevelopmentService")
private ProposalDevelopmentService proposalDevelopmentService;
@Autowired
@Qualifier("proposalDevelopmentPermissionsService")
private ProposalDevelopmentPermissionsService proposalDevelopmentPermissionsService;
@Autowired
@Qualifier("legacyDataAdapter")
private LegacyDataAdapter legacyDataAdapter;
@Autowired
@Qualifier("proposalRoleTemplateService")
private ProposalRoleTemplateService proposalRoleTemplateService;
@Autowired
@Qualifier("dataObjectService")
private DataObjectService dataObjectService;
@Autowired
@Qualifier("globalVariableService")
private GlobalVariableService globalVariableService;
@Autowired
@Qualifier("proposalPersonBiographyService")
private ProposalPersonBiographyService proposalPersonBiographyService;
@Autowired
@Qualifier("documentAdHocService")
private DocumentAdHocService documentAdHocService;
@Autowired
@Qualifier("auditHelper")
private AuditHelper auditHelper;
@Autowired
@Qualifier("pessimisticLockService")
private PessimisticLockService pessimisticLockService;
@Autowired
@Qualifier("kcNotificationService")
private KcNotificationService kcNotificationService;
@Autowired
@Qualifier("parameterService")
private ParameterService parameterService;
@Autowired
@Qualifier("kualiConfigurationService")
private ConfigurationService kualiConfigurationService;
@Autowired
@Qualifier("proposalPersonCoiIntegrationService")
private ProposalPersonCoiIntegrationService proposalPersonCoiIntegrationService;
private transient boolean updatedToCoi = false;
protected DocumentFormBase createInitialForm(HttpServletRequest request) {
return new ProposalDevelopmentDocumentForm();
}
@ModelAttribute(value = "KualiForm")
public UifFormBase initForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
UifFormBase form = getKcCommonControllerService().initForm(this.createInitialForm(request), request, response);
return form;
}
private final Logger LOGGER = Logger.getLogger(ProposalDevelopmentSubmitController.class);
public KcCoiLinkService kcCoiLinkService;
public KcCoiLinkService getKcCoiLinkService() {
if (kcCoiLinkService == null) {
kcCoiLinkService = KcServiceLocator.getService(KcCoiLinkService.class);
}
return kcCoiLinkService;
}
public void setKcCoiLinkService(KcCoiLinkService kcCoiLinkService) {
this.kcCoiLinkService = kcCoiLinkService;
}
/**
* Create the original set of Proposal Users for a new Proposal Development Document.
* The creator the proposal is assigned to the AGGREGATOR role.
*/
protected void initializeProposalUsers(ProposalDevelopmentDocument doc) {
// Assign the creator of the proposal to the AGGREGATOR role.
String userId = GlobalVariables.getUserSession().getPrincipalId();
if (!kraAuthorizationService.hasDocumentLevelRole(userId, RoleConstants.AGGREGATOR, doc))
kraAuthorizationService.addDocumentLevelRole(userId, RoleConstants.AGGREGATOR, doc);
// Add the users defined in the role templates for the proposal's lead unit
proposalRoleTemplateService.addUsers(doc);
}
protected void initialSave(ProposalDevelopmentDocument proposalDevelopmentDocument) {
preSave(proposalDevelopmentDocument);
proposalDevelopmentService.initializeUnitOrganizationLocation(
proposalDevelopmentDocument);
proposalDevelopmentService.initializeProposalSiteNumbers(
proposalDevelopmentDocument);
}
protected void preSave(ProposalDevelopmentDocument proposalDevelopmentDocument) {
if (proposalDevelopmentDocument.isDefaultDocumentDescription()) {
proposalDevelopmentDocument.setDefaultDocumentDescription();
}
}
public ModelAndView save(ProposalDevelopmentDocumentForm form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
return save(form);
}
public ModelAndView save(ProposalDevelopmentDocumentForm form) throws Exception {
ProposalDevelopmentDocument proposalDevelopmentDocument = (ProposalDevelopmentDocument) form.getDocument();
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.PROP_DEV_PERMISSIONS_PAGE)) {
saveDocumentPermissions(form);
}
DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_MY_COI_DIALOG_ID);
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.KEY_PERSONNEL_PAGE) ||
StringUtils.equalsIgnoreCase(form.getPageId(),"PropDev-CertificationView-Page")){
String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
if (StringUtils.isBlank(pageId)){
if(dialogResponse!=null){
boolean confirmResetDefault = dialogResponse.getResponseAsBoolean();
if(confirmResetDefault){
String coiApplicationUrl = getKualiConfigurationService().getPropertyValueAsString(KcMitConstants.MIT_COEUS_COI_APPLICATION_URL);
if(coiApplicationUrl!=null){
return getModelAndViewService().performRedirect(form, coiApplicationUrl);
}
}else{
return getModelAndViewService().getModelAndView(form, pageId);
}
}
}
}
if (StringUtils.equalsIgnoreCase(form.getPageId(), ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID)) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).populateAttachmentReferences(form.getDevelopmentProposal());
}
if (getGlobalVariableService().getMessageMap().getErrorCount() == 0 && form.getEditableCollectionLines() != null) {
form.getEditableCollectionLines().clear();
}
if (StringUtils.equalsIgnoreCase(form.getPageId(), ProposalDevelopmentDataValidationConstants.DETAILS_PAGE_ID)) {
handleSponsorChange(proposalDevelopmentDocument);
}
preSave(proposalDevelopmentDocument);
proposalDevelopmentService.initializeUnitOrganizationLocation(
proposalDevelopmentDocument);
proposalDevelopmentService.initializeProposalSiteNumbers(
proposalDevelopmentDocument);
for (ProposalPersonBiography biography : form.getDevelopmentProposal().getPropPersonBios()) {
getProposalPersonBiographyService().prepareProposalPersonBiographyForSave(form.getDevelopmentProposal(),biography);
}
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).setOrdinalPosition(form.getDevelopmentProposal().getProposalPersons());
saveAnswerHeaders(form, form.getPageId());
getTransactionalDocumentControllerService().save(form);
if (form.isAuditActivated()){
getAuditHelper().auditConditionally(form);
}
populateAdHocRecipients(form.getProposalDevelopmentDocument());
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.CREDIT_ALLOCATION_PAGE)) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).populateCreditSplits(form);
}
if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.QUESTIONS_PAGE)) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).populateQuestionnaires(form);
}
String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
ModelAndView view = null;
if (StringUtils.isNotBlank(pageId) && getGlobalVariableService().getMessageMap().hasNoErrors()) {
form.setDirtyForm(false);
view = getModelAndViewService().getModelAndView(form, pageId);
} else {
view = getModelAndViewService().getModelAndView(form);
}
if (form.getProposalDevelopmentDocument().getDevelopmentProposal() != null
&& form.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews() != null) {
for (ProposalSpecialReview specialReview : form.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews()) {
if (!specialReview.isLinkedToProtocol()) {
form.getSpecialReviewHelper().prepareProtocolLinkViewFields(specialReview);
}
}
}
if(StringUtils.isBlank(pageId) && dialogResponse == null && isUpdatedToCoi()){
form.setCoiIntegrationMessage(getKualiConfigurationService().getPropertyValueAsString(KcMitConstants.COI_QUESTION_ANSWERED));
view = getModelAndViewService().showDialog("PropDev-Personal-CoiQuestionDialog", true, form);
}
return view;
}
public ModelAndView save(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response, Class<? extends DocumentEventBase> eventClazz) throws Exception {
ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) form;
ProposalDevelopmentDocument proposalDevelopmentDocument = (ProposalDevelopmentDocument) pdForm.getDocument();
proposalDevelopmentService.initializeUnitOrganizationLocation(
proposalDevelopmentDocument);
proposalDevelopmentService.initializeProposalSiteNumbers(
proposalDevelopmentDocument);
ModelAndView view = null;
saveAnswerHeaders(pdForm,request.getParameter(UifParameters.PAGE_ID));
if (eventClazz == null) {
getTransactionalDocumentControllerService().save(form);
} else {
performCustomSave(proposalDevelopmentDocument, SaveDocumentSpecialReviewEvent.class);
}
populateAdHocRecipients(pdForm.getProposalDevelopmentDocument());
String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
if (StringUtils.isNotBlank(pageId) && getGlobalVariableService().getMessageMap().hasNoErrors()) {
form.setDirtyForm(false);
view = getModelAndViewService().getModelAndView(form, pageId);
} else {
view = getModelAndViewService().getModelAndView(form);
}
if (pdForm.getProposalDevelopmentDocument().getDevelopmentProposal() != null
&& pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews() != null) {
for (ProposalSpecialReview specialReview : pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews()) {
if (!specialReview.isLinkedToProtocol()) {
pdForm.getSpecialReviewHelper().prepareProtocolLinkViewFields(specialReview);
}
}
}
return view;
}
protected void performCustomSave(DocumentBase document, Class<? extends DocumentEventBase> eventClazz) {
try {
getDocumentService().saveDocument(document, eventClazz);
GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_MESSAGES, RiceKeyConstants.MESSAGE_SAVED);
} catch (ValidationException e) {
// if errors in map, swallow exception so screen will draw with errors
// if not then throw runtime because something bad happened
if (GlobalVariables.getMessageMap().hasNoErrors()) {
throw new RiceRuntimeException("Validation Exception with no error message.", e);
}
} catch (Exception e) {
throw new RiceRuntimeException(
"Exception trying to save document: " + document
.getDocumentNumber(), e);
}
}
protected ModelAndView navigate(ProposalDevelopmentDocumentForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (form.getDevelopmentProposal().getS2sOpportunity() != null && !getProposalDevelopmentService().isGrantsGovEnabledForProposal(form.getDevelopmentProposal())) {
((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService()).clearOpportunity(form.getDevelopmentProposal());
}
populateAdHocRecipients(form.getProposalDevelopmentDocument());
String navigateToPageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
boolean canEdit = form.isCanEditView();
if (isNavigateToDeliveryInfoPage(navigateToPageId)) {
if (form.getDevelopmentProposal().getS2sOpportunity() != null) {
getGlobalVariableService().getMessageMap().putInfo(ProposalDevelopmentConstants.KradConstants.DELIVERY_INFO_PAGE, KeyConstants.DELIVERY_INFO_NOT_NEEDED);
}
}
if (isNavigateAwayFromAttachment(navigateToPageId, form.getPageId())) {
prepareLocks(form);
return narrativePageSave(form, canEdit);
} else if (isNavigateToAttachments(navigateToPageId) ||
isNavigateAwayFromAccess(navigateToPageId,form.getPageId()) ||
isNavigateToAccess(navigateToPageId)) {
prepareLocks(form);
}
return proposalDevelopmentPageSave(form, canEdit);
}
protected void prepareLocks(ProposalDevelopmentDocumentForm form) {
releasePessimisticLocks(form);
form.setEvaluateFlagsAndModes(true);
form.setCanEditView(null);
}
protected ModelAndView proposalDevelopmentPageSave(ProposalDevelopmentDocumentForm form, boolean canEdit) throws Exception {
ProposalDevelopmentDocument document = (ProposalDevelopmentDocument) getDocumentService().getByDocumentHeaderId(form.getDocument().getDocumentNumber());
if (canEdit) {
//when saving on page in the proposal development locking region we don't want to over write attachments that
//may have been alter concurrently. So we retrieve the latest proposal data from the db, and replace the attachment
//collections with the values from the db.
if (!StringUtils.equals(form.getPageId(),Constants.PROP_DEV_PERMISSIONS_PAGE)) {
form.getDevelopmentProposal().setNarratives(document.getDevelopmentProposal().getNarratives());
form.getDevelopmentProposal().setInstituteAttachments(document.getDevelopmentProposal().getInstituteAttachments());
form.getDevelopmentProposal().setPropPersonBios(document.getDevelopmentProposal().getPropPersonBios());
form.getDevelopmentProposal().setProposalAbstracts(document.getDevelopmentProposal().getProposalAbstracts());
form.getDocument().setNotes(document.getNotes());
form.getDocument().setDocumentHeader(document.getDocumentHeader());
}
return save(form);
} else {
form.setDocument(document);
return getNavigationControllerService().navigate(form);
}
}
protected ModelAndView narrativePageSave(ProposalDevelopmentDocumentForm form, boolean canEdit) throws Exception {
ProposalDevelopmentDocument document = (ProposalDevelopmentDocument) getDocumentService().getByDocumentHeaderId(form.getDocument().getDocumentNumber());
if (canEdit) {
if ((new ProposalDevelopmentDocumentRule().processAttachmentRules(form.getProposalDevelopmentDocument()))
&& (new ProposalDevelopmentDocumentRule().processPersonnelAttachmentDuplicates(form.getProposalDevelopmentDocument()))) {
form.getProposalDevelopmentAttachmentHelper().handleNarrativeUpdates(form, document);
form.getProposalDevelopmentAttachmentHelper().handleInstAttachmentUpdates(form, document);
form.getProposalDevelopmentAttachmentHelper().handlePersonBioUpdates(form, document);
document.getDevelopmentProposal().setProposalAbstracts(form.getDevelopmentProposal().getProposalAbstracts());
document.setNotes(form.getDocument().getNotes());
form.setDocument(document);
return save(form);
} else {
form.setCanEditView(canEdit);
return getModelAndViewService().getModelAndView(form);
}
} else {
form.setDocument(document);
return getNavigationControllerService().navigate(form);
}
}
protected boolean isNavigateToAttachments(String navigateToPageId) {
return StringUtils.equals(navigateToPageId,ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID);
}
protected boolean isNavigateToAccess(String navigateToPageId) {
return StringUtils.equals(navigateToPageId,Constants.PROP_DEV_PERMISSIONS_PAGE);
}
protected boolean isNavigateAwayFromAccess(String navigateToPageId, String pageId) {
return StringUtils.equals(pageId,Constants.PROP_DEV_PERMISSIONS_PAGE) &&
!StringUtils.equals(navigateToPageId,Constants.PROP_DEV_PERMISSIONS_PAGE);
}
protected boolean isNavigateAwayFromAttachment(String navigateToPageId, String pageId) {
return StringUtils.equals(pageId,ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID) &&
!StringUtils.equals(navigateToPageId,ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID);
}
protected boolean isNavigateToDeliveryInfoPage(String navigateToPageId) {
return StringUtils.equals(navigateToPageId, ProposalDevelopmentConstants.KradConstants.DELIVERY_INFO_PAGE);
}
protected void releasePessimisticLocks(DocumentFormBase form) {
Document document = form.getDocument();
if (!document.getPessimisticLocks().isEmpty()) {
Person user = getGlobalVariableService().getUserSession().getPerson();
document.refreshPessimisticLocks();
getPessimisticLockService().releaseAllLocksForUser(document.getPessimisticLocks(), user);
}
}
public void addEditableCollectionLine(ProposalDevelopmentDocumentForm form, String selectedCollectionPath){
if(form.getEditableCollectionLines().containsKey(selectedCollectionPath)) {
updateEditableCollectionLines(form, selectedCollectionPath);
} else {
List<String> newKeyList = new ArrayList<String>();
newKeyList.add("0");
form.getEditableCollectionLines().put(selectedCollectionPath,newKeyList);
}
}
public void updateEditableCollectionLines(ProposalDevelopmentDocumentForm form, String selectedCollectionPath){
List<String> indexes = new ArrayList<String>();
indexes.add("0");
for (String index : form.getEditableCollectionLines().get(selectedCollectionPath)) {
Integer newIndex= Integer.parseInt(index) + 1;
indexes.add(newIndex.toString());
}
form.getEditableCollectionLines().get(selectedCollectionPath).clear();
form.getEditableCollectionLines().get(selectedCollectionPath).addAll(indexes);
}
protected KcAuthorizationService getKraAuthorizationService() {
return kraAuthorizationService;
}
public void setKraAuthorizationService(KcAuthorizationService kraAuthorizationService) {
this.kraAuthorizationService = kraAuthorizationService;
}
protected ProposalDevelopmentService getProposalDevelopmentService() {
return proposalDevelopmentService;
}
public void setProposalDevelopmentService(ProposalDevelopmentService proposalDevelopmentService) {
this.proposalDevelopmentService = proposalDevelopmentService;
}
protected TransactionalDocumentControllerService getTransactionalDocumentControllerService() {
return transactionalDocumentControllerService;
}
public void setTransactionalDocumentControllerService(TransactionalDocumentControllerService transactionalDocumentControllerService) {
this.transactionalDocumentControllerService = transactionalDocumentControllerService;
}
protected DocumentService getDocumentService() {
return documentService;
}
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
protected LegacyDataAdapter getLegacyDataAdapter() {
return legacyDataAdapter;
}
public void setLegacyDataAdapter(LegacyDataAdapter legacyDataAdapter) {
this.legacyDataAdapter = legacyDataAdapter;
}
protected ProposalRoleTemplateService getProposalRoleTemplateService() {
return proposalRoleTemplateService;
}
public void setProposalRoleTemplateService(
ProposalRoleTemplateService proposalRoleTemplateService) {
this.proposalRoleTemplateService = proposalRoleTemplateService;
}
protected DataObjectService getDataObjectService() {
return dataObjectService;
}
public void setDataObjectService(DataObjectService dataObjectService) {
this.dataObjectService = dataObjectService;
}
public void saveAnswerHeaders(ProposalDevelopmentDocumentForm pdForm,String pageId) {
boolean allCertificationsWereComplete = true;
boolean allCertificationAreNowComplete = true;
setUpdatedToCoi(false);
if (StringUtils.equalsIgnoreCase(pageId, Constants.KEY_PERSONNEL_PAGE) ||
StringUtils.equalsIgnoreCase(pageId,"PropDev-CertificationView-Page")) {
for (ProposalPerson person : pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalPersons()) {
if (person.getQuestionnaireHelper() != null && person.getQuestionnaireHelper().getAnswerHeaders() != null
&& !person.getQuestionnaireHelper().getAnswerHeaders().isEmpty()) {
for (AnswerHeader answerHeader : person.getQuestionnaireHelper().getAnswerHeaders()) {
boolean wasComplete = answerHeader.isCompleted();
allCertificationsWereComplete &= wasComplete;
getLegacyDataAdapter().save(answerHeader);
person.getQuestionnaireHelper().populateAnswers();
boolean isComplete = person.getQuestionnaireHelper().getAnswerHeaders().get(0).isCompleted();
allCertificationAreNowComplete &= isComplete;
if(isComplete && !wasComplete){
person.setCertifiedBy(getGlobalVariableService().getUserSession().getPrincipalId());
}else if(wasComplete && !isComplete){
person.setCertifiedBy(null);
}
if(!isUpdatedToCoi()){
setUpdatedToCoi(updateCOIOnPDCerificationComplete(pdForm,person,isComplete || wasComplete,answerHeader));
}else{
updateCOIOnPDCerificationComplete(pdForm,person,isComplete || wasComplete,answerHeader);
}
checkForCertifiedByProxy(pdForm.getDevelopmentProposal(),person,isComplete && !wasComplete,wasComplete);
}
}
}
} else if (StringUtils.equalsIgnoreCase(pageId, Constants.QUESTIONS_PAGE)) {
for (AnswerHeader answerHeader : pdForm.getQuestionnaireHelper().getAnswerHeaders()) {
getLegacyDataAdapter().save(answerHeader);
}
for (AnswerHeader answerHeader : pdForm.getS2sQuestionnaireHelper().getAnswerHeaders()) {
getLegacyDataAdapter().save(answerHeader);
}
}
boolean allowsSendCertificationCompleteNotification = getParameterService().getParameterValueAsBoolean(Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,Constants.PARAMETER_COMPONENT_DOCUMENT,ProposalDevelopmentConstants.Parameters.NOTIFY_ALL_CERTIFICATIONS_COMPLETE);
if (!allCertificationsWereComplete && allCertificationAreNowComplete && allowsSendCertificationCompleteNotification) {
ProposalDevelopmentNotificationContext context = new ProposalDevelopmentNotificationContext(pdForm.getDevelopmentProposal(),"105","All Proposal Persons Certification Completed");
((ProposalDevelopmentNotificationRenderer) context.getRenderer()).setDevelopmentProposal(pdForm.getDevelopmentProposal());
getKcNotificationService().sendNotification(context);
}
}
public boolean updateCOIOnPDCerificationComplete(ProposalDevelopmentDocumentForm pdForm, ProposalPerson person, boolean completed,AnswerHeader answerHeader) {
boolean coiQuestionsAnswered = false;
if(checkForCOIquestions(answerHeader)){
updateToCOI(pdForm,person);
}
coiQuestionsAnswered = getProposalPersonCoiIntegrationService().isCoiQuestionsAnswered(person);
if(coiQuestionsAnswered){
return coiQuestionsAnswered;
}
return coiQuestionsAnswered;
}
private void updateToCOI(ProposalDevelopmentDocumentForm pdForm, ProposalPerson person){
String userName = getGlobalVariableService().getUserSession().getPrincipalName();
try {
getKcCoiLinkService().updateCOIOnPDCerificationComplete(pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getProposalNumber(), person.getPersonId(), userName);
} catch (SQLException e) {
LOGGER.info(Level.ALL, e);
LOGGER.warn("DBLINK is not accessible or the parameter value returning null");
}
}
private boolean checkForCOIquestions(AnswerHeader answerHeader ){
boolean hasCOIquestions = false;
String coiCertificationQuestionIds = getParameterService().getParameterValueAsString("KC-GEN", "All", "PROP_PERSON_COI_CERTIFY_QID");
List<String> coiCertificationQuestionIdList = new ArrayList<String>();
if(coiCertificationQuestionIds!=null){
String[] questionIds = coiCertificationQuestionIds.split(",");
for (String questionid : questionIds){
coiCertificationQuestionIdList.add(questionid);
}
}
for(Answer answer :answerHeader.getAnswers()){
for(String coiCertificationQuestionId : coiCertificationQuestionIdList){
if(coiCertificationQuestionId.equals(answer.getQuestionSeqId().toString())){
hasCOIquestions = true;
break;
}
}
}
return hasCOIquestions;
}
public void checkForCertifiedByProxy(DevelopmentProposal developmentProposal, ProposalPerson person, boolean recentlyCompleted,boolean wasComplete) {
boolean selfCertifyOnly = getParameterService().getParameterValueAsBoolean(Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT,Constants.PARAMETER_COMPONENT_DOCUMENT,ProposalDevelopmentConstants.Parameters.KEY_PERSON_CERTIFICATION_SELF_CERTIFY_ONLY);
if (selfCertifyOnly) {
String proxyId = getGlobalVariableService().getUserSession().getPrincipalId();
if (!StringUtils.equals(person.getPersonId(), proxyId) && recentlyCompleted) {
ProposalDevelopmentNotificationContext context = new ProposalDevelopmentNotificationContext(developmentProposal,"106","Proposal Person Certification Completed");
((ProposalDevelopmentNotificationRenderer) context.getRenderer()).setDevelopmentProposal(developmentProposal);
KcNotification notification = getKcNotificationService().createNotificationObject(context);
NotificationTypeRecipient recipient = new NotificationTypeRecipient();
recipient.setPersonId(person.getPersonId());
getKcNotificationService().sendNotification(context,notification,Collections.singletonList(recipient));
}
}
}
/**
* Method calls the permissions service, where it will determine if any user permissions need to be added and/or removed.
*
* @param pdForm ProposalDevelopmentDocumentForm that contains the permissions helper
*/
public void saveDocumentPermissions(ProposalDevelopmentDocumentForm pdForm) {
List<String> editableLines = pdForm.getEditableCollectionLines().get(Constants.PERMISSION_PROPOSAL_USERS_COLLECTION_PROPERTY_KEY);
if (editableLines != null && editableLines.size() > 0) {
getGlobalVariableService().getMessageMap().putErrorForSectionId(Constants.PERMISSION_PROPOSAL_USERS_COLLECTION_ID_KEY, KeyConstants.ERROR_UNFINISHED_PERMISSIONS);
} else if (arePermissionsValid(pdForm.getProposalDevelopmentDocument(),pdForm.getWorkingUserRoles())) {
getProposalDevelopmentPermissionsService().savePermissions(pdForm.getProposalDevelopmentDocument(), getProposalDevelopmentPermissionsService().getPermissions(pdForm.getProposalDevelopmentDocument()), pdForm.getWorkingUserRoles());
}
}
protected boolean arePermissionsValid(ProposalDevelopmentDocument document, List<ProposalUserRoles> proposalUsers) {
boolean retVal = true;
for (ProposalUserRoles proposalUser : proposalUsers) {
retVal &= getProposalDevelopmentPermissionsService().validateUpdatePermissions(document,proposalUsers,proposalUser);
}
return retVal;
}
@InitBinder
protected void initBinder(WebDataBinder binder) throws Exception {
binder.registerCustomEditor(List.class, "document.developmentProposal.propScienceKeywords", new PropScienceKeywordEditor());
binder.registerCustomEditor(List.class, "document.developmentProposal.propSpecialReviews.specialReviewExemptions", new PropSpecialReviewExemptionTypeEditor());
// For add line binding
binder.registerCustomEditor(List.class, "newCollectionLines.specialReviewExemptions", new PropSpecialReviewExemptionTypeEditor());
}
protected class PropScienceKeywordEditor extends CustomCollectionEditor {
public PropScienceKeywordEditor() {
super(List.class, true);
}
protected Object convertElement(Object element) {
if (element != null && element instanceof String) {
return new PropScienceKeyword(null, getScienceKeyword(element));
}
return element;
}
public String getAsText() {
if (this.getValue() != null) {
Collection<PropScienceKeyword> keywords = (Collection<PropScienceKeyword>) this.getValue();
StringBuilder result = new StringBuilder();
for(PropScienceKeyword keyword : keywords) {
result.append(keyword.getScienceKeyword().getCode());
result.append(",");
}
if (result.length() > 0) {
return result.substring(0, result.length() - 1);
}
}
return null;
}
}
/**
* Editor to convert (to and from) a String list of exemption type codes to ProposalSpecialReviewExemption objects
*/
protected class PropSpecialReviewExemptionTypeEditor extends CustomCollectionEditor {
public PropSpecialReviewExemptionTypeEditor() {
super(List.class, true);
}
protected Object convertElement(Object element) {
if (element != null && element instanceof String) {
return new ProposalSpecialReviewExemption(null, getExemptionType(element));
}
return element;
}
public String getAsText() {
if (this.getValue() != null) {
Collection<ProposalSpecialReviewExemption> exemptions = (Collection<ProposalSpecialReviewExemption>) this.getValue();
StringBuilder result = new StringBuilder();
for(ProposalSpecialReviewExemption exemption : exemptions) {
result.append(exemption.getExemptionTypeCode());
result.append(",");
}
if (result.length() > 0) {
return result.substring(0, result.length() - 1);
}
}
return null;
}
}
protected ExemptionType getExemptionType(Object element) {
return (ExemptionType) getDataObjectService().findUnique(ExemptionType.class, QueryByCriteria.Builder.forAttribute("code", element).build());
}
public AuditHelper.ValidationState getValidationState(ProposalDevelopmentDocumentForm form) {
AuditHelper.ValidationState severityLevel = AuditHelper.ValidationState.OK;
form.setAuditActivated(true);
List<DataValidationItem> dataValidationItems = ((ProposalDevelopmentViewHelperServiceImpl)form.getViewHelperService())
.populateDataValidation(form);
if(dataValidationItems != null && dataValidationItems.size() > 0 ) {
for(DataValidationItem validationItem : dataValidationItems) {
if (StringUtils.endsWith(validationItem.getSeverity(),Constants.AUDIT_ERRORS)) {
severityLevel = AuditHelper.ValidationState.ERROR;
break;
}
if (StringUtils.equals(validationItem.getSeverity(), Constants.AUDIT_WARNINGS)){
severityLevel = AuditHelper.ValidationState.WARNING;
}
}
form.setDataValidationItems(dataValidationItems);
}
getGlobalVariableService().getMessageMap().clearErrorMessages();
return severityLevel;
}
/**
* During navigation and routing the ad hoc recipients which are transient get removed. To solve this, repopulate them in the document before each save.
* This will stop the system from removing the current recipients from the database.
*
* Extra logic added to assist in avoiding the null document number issue.
*/
public void populateAdHocRecipients(ProposalDevelopmentDocument proposalDevelopmentDocument){
if (StringUtils.isEmpty(proposalDevelopmentDocument.getDocumentNumber())
&& proposalDevelopmentDocument.getDocumentHeader() != null && StringUtils.isNotEmpty(proposalDevelopmentDocument.getDocumentHeader().getDocumentNumber())){
proposalDevelopmentDocument.setDocumentNumber(proposalDevelopmentDocument.getDocumentHeader().getDocumentNumber());
}
if (StringUtils.isNotEmpty(proposalDevelopmentDocument.getDocumentNumber())){
getDocumentAdHocService().addAdHocs(proposalDevelopmentDocument);
}
}
/**
*
* If the sponsor has changed, default the key personnel role codes to COI if the role can't be found
*/
public void handleSponsorChange(ProposalDevelopmentDocument proposalDevelopmentDocument){
for (int i=0; i< proposalDevelopmentDocument.getDevelopmentProposal().getProposalPersons().size();i++){
ProposalPerson person = proposalDevelopmentDocument.getDevelopmentProposal().getProposalPersons().get(i);
if (person.getRole() == null){
person.setProposalPersonRoleId(PropAwardPersonRole.CO_INVESTIGATOR);
String propertyName = ProposalDevelopmentConstants.PropertyConstants.PROPOSAL_PERSONS;
getGlobalVariableService().getMessageMap().putInfo(propertyName + "[" + i + "].proposalPersonRoleId", KeyConstants.INFO_PERSONNEL_INVALID_ROLE, person.getDevelopmentProposal().getSponsorCode(), person.getFullName());
}
}
}
public void populateDeferredMessages(ProposalDevelopmentDocumentForm proposalDevelopmentDocumentForm){
if (proposalDevelopmentDocumentForm.getDeferredMessages() != null
&& proposalDevelopmentDocumentForm.getDeferredMessages().hasMessages()){
MessageMap messageMap = proposalDevelopmentDocumentForm.getDeferredMessages();
MessageMap currentMessageMap = getGlobalVariableService().getMessageMap();
messageMap.getErrorMessages().putAll(currentMessageMap.getErrorMessages());
messageMap.getInfoMessages().putAll(currentMessageMap.getInfoMessages());
messageMap.getWarningMessages().putAll(currentMessageMap.getWarningMessages());
getGlobalVariableService().setMessageMap(messageMap);
}
proposalDevelopmentDocumentForm.setDeferredMessages(null);
}
protected ScienceKeyword getScienceKeyword(Object element) {
return getDataObjectService().findUnique(ScienceKeyword.class, QueryByCriteria.Builder.forAttribute("code", element).build());
}
public UifExportControllerService getUifExportControllerService() {
return uifExportControllerService;
}
public void setUifExportControllerService(UifExportControllerService uifExportControllerService) {
this.uifExportControllerService = uifExportControllerService;
}
public KcCommonControllerService getKcCommonControllerService() {
return kcCommonControllerService;
}
public void setKcCommonControllerService(KcCommonControllerService kcCommonControllerService) {
this.kcCommonControllerService = kcCommonControllerService;
}
public CollectionControllerService getCollectionControllerService() {
return collectionControllerService;
}
public void setCollectionControllerService(CollectionControllerService collectionControllerService) {
this.collectionControllerService = collectionControllerService;
}
public FileControllerService getFileControllerService() {
return fileControllerService;
}
public void setFileControllerService(FileControllerService fileControllerService) {
this.fileControllerService = fileControllerService;
}
public ModelAndViewService getModelAndViewService() {
return modelAndViewService;
}
public void setModelAndViewService(ModelAndViewService modelAndViewService) {
this.modelAndViewService = modelAndViewService;
}
public NavigationControllerService getNavigationControllerService() {
return navigationControllerService;
}
public void setNavigationControllerService(NavigationControllerService navigationControllerService) {
this.navigationControllerService = navigationControllerService;
}
public QueryControllerService getQueryControllerService() {
return queryControllerService;
}
public void setQueryControllerService(QueryControllerService queryControllerService) {
this.queryControllerService = queryControllerService;
}
public RefreshControllerService getRefreshControllerService() {
return refreshControllerService;
}
public void setRefreshControllerService(RefreshControllerService refreshControllerService) {
this.refreshControllerService = refreshControllerService;
}
public GlobalVariableService getGlobalVariableService() {
return globalVariableService;
}
public void setGlobalVariableService(GlobalVariableService globalVariableService) {
this.globalVariableService = globalVariableService;
}
protected ProposalDevelopmentPermissionsService getProposalDevelopmentPermissionsService() {
return proposalDevelopmentPermissionsService;
}
public void setProposalDevelopmentPermissionsService(ProposalDevelopmentPermissionsService proposalDevelopmentPermissionsService) {
this.proposalDevelopmentPermissionsService = proposalDevelopmentPermissionsService;
}
public ProposalPersonBiographyService getProposalPersonBiographyService() {
return proposalPersonBiographyService;
}
public void setProposalPersonBiographyService(ProposalPersonBiographyService proposalPersonBiographyService) {
this.proposalPersonBiographyService = proposalPersonBiographyService;
}
public DocumentAdHocService getDocumentAdHocService() {
return documentAdHocService;
}
public void setDocumentAdHocService(DocumentAdHocService documentAdHocService) {
this.documentAdHocService = documentAdHocService;
}
public AuditHelper getAuditHelper() {
return auditHelper;
}
public void setAuditHelper(AuditHelper auditHelper) {
this.auditHelper = auditHelper;
}
public KcNotificationService getKcNotificationService() {
return kcNotificationService;
}
public void setKcNotificationService(KcNotificationService kcNotificationService) {
this.kcNotificationService = kcNotificationService;
}
public ParameterService getParameterService() {
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public PessimisticLockService getPessimisticLockService() {
return pessimisticLockService;
}
public void setPessimisticLockService(PessimisticLockService pessimisticLockService) {
this.pessimisticLockService = pessimisticLockService;
}
public boolean isUpdatedToCoi() {
return updatedToCoi;
}
public void setUpdatedToCoi(boolean updatedToCoi) {
this.updatedToCoi = updatedToCoi;
}
public ConfigurationService getKualiConfigurationService() {
return kualiConfigurationService;
}
public void setKualiConfigurationService(
ConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
public ProposalPersonCoiIntegrationService getProposalPersonCoiIntegrationService() {
return proposalPersonCoiIntegrationService;
}
public void setProposalPersonCoiIntegrationService(
ProposalPersonCoiIntegrationService proposalPersonCoiIntegrationService) {
this.proposalPersonCoiIntegrationService = proposalPersonCoiIntegrationService;
}
}
|
MITKC-913-PD - Proposal Certification is missing Answered By username
and time stamp
|
kcmit-impl/src/main/java/org/kuali/coeus/propdev/impl/core/ProposalDevelopmentControllerBase.java
|
MITKC-913-PD - Proposal Certification is missing Answered By username and time stamp
|
<ide><path>cmit-impl/src/main/java/org/kuali/coeus/propdev/impl/core/ProposalDevelopmentControllerBase.java
<ide> import org.kuali.kra.infrastructure.RoleConstants;
<ide> import org.kuali.rice.core.api.config.property.ConfigurationService;
<ide> import org.kuali.rice.core.api.criteria.QueryByCriteria;
<add>import org.kuali.rice.core.api.datetime.DateTimeService;
<ide> import org.kuali.rice.core.api.exception.RiceRuntimeException;
<ide> import org.kuali.rice.core.api.util.RiceKeyConstants;
<ide> import org.kuali.rice.coreservice.framework.parameter.ParameterService;
<ide> allCertificationAreNowComplete &= isComplete;
<ide> if(isComplete && !wasComplete){
<ide> person.setCertifiedBy(getGlobalVariableService().getUserSession().getPrincipalId());
<add> person.setCertifiedTime(((DateTimeService) KcServiceLocator.getService(Constants.DATE_TIME_SERVICE_NAME)).getCurrentTimestamp());
<add>
<ide> }else if(wasComplete && !isComplete){
<ide> person.setCertifiedBy(null);
<add> person.setCertifiedTime(null);
<ide> }
<ide> if(!isUpdatedToCoi()){
<ide> setUpdatedToCoi(updateCOIOnPDCerificationComplete(pdForm,person,isComplete || wasComplete,answerHeader));
|
|
Java
|
apache-2.0
|
9f477a136e2ec83bf3c085ac12574b4a9c16fca1
| 0 |
alsorokin/cordova-plugin-battery-status,gmegidish/cordova-plugin-battery-status,purplecabbage/cordova-plugin-battery-status,purplecabbage/cordova-plugin-battery-status,alsorokin/cordova-plugin-battery-status,alsorokin/cordova-plugin-battery-status,Cappada/cordova-plugin-battery-status,Uldax/cordova-plugin-battery-status,apache/cordova-plugin-battery-status,Uldax/cordova-plugin-battery-status,purplecabbage/cordova-plugin-battery-status,revolunet/cordova-plugin-battery-status,Cappada/cordova-plugin-battery-status,gmegidish/cordova-plugin-battery-status,Maria02/camera,corimf/cordova-plugin-battery-status,revolunet/cordova-plugin-battery-status,apache/cordova-plugin-battery-status,gmegidish/cordova-plugin-battery-status,Maria02/camera,Maria02/camera,corimf/cordova-plugin-battery-status,Maria02/camera,Cappada/cordova-plugin-battery-status,revolunet/cordova-plugin-battery-status,apache/cordova-plugin-battery-status,gmegidish/cordova-plugin-battery-status,Uldax/cordova-plugin-battery-status,revolunet/cordova-plugin-battery-status,Cappada/cordova-plugin-battery-status,alsorokin/cordova-plugin-battery-status,Uldax/cordova-plugin-battery-status,corimf/cordova-plugin-battery-status,purplecabbage/cordova-plugin-battery-status,corimf/cordova-plugin-battery-status
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.batterystatus;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class BatteryListener extends CordovaPlugin {
private static final String LOG_TAG = "BatteryManager";
BroadcastReceiver receiver;
private CallbackContext batteryCallbackContext = null;
/**
* Constructor.
*/
public BatteryListener() {
this.receiver = null;
}
/**
* Executes the request.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("start")) {
if (this.batteryCallbackContext != null) {
callbackContext.error( "Battery listener already running.");
return true;
}
this.batteryCallbackContext = callbackContext;
// We need to listen to power events to update battery status
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateBatteryInfo(intent);
}
};
webView.getContext().registerReceiver(this.receiver, intentFilter);
}
// Don't return any result now, since status results will be sent when events come in from broadcast receiver
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
else if (action.equals("stop")) {
removeBatteryListener();
this.sendUpdate(new JSONObject(), false); // release status callback in JS side
this.batteryCallbackContext = null;
callbackContext.success();
return true;
}
return false;
}
/**
* Stop battery receiver.
*/
public void onDestroy() {
removeBatteryListener();
}
/**
* Stop battery receiver.
*/
public void onReset() {
removeBatteryListener();
}
/**
* Stop the battery receiver and set it to null.
*/
private void removeBatteryListener() {
if (this.receiver != null) {
try {
webView.getContext().unregisterReceiver(this.receiver);
this.receiver = null;
} catch (Exception e) {
Log.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);
}
}
}
/**
* Creates a JSONObject with the current battery information
*
* @param batteryIntent the current battery information
* @return a JSONObject containing the battery status information
*/
private JSONObject getBatteryInfo(Intent batteryIntent) {
JSONObject obj = new JSONObject();
try {
obj.put("level", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, 0));
obj.put("isPlugged", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1) > 0 ? true : false);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return obj;
}
/**
* Updates the JavaScript side whenever the battery changes
*
* @param batteryIntent the current battery information
* @return
*/
private void updateBatteryInfo(Intent batteryIntent) {
sendUpdate(this.getBatteryInfo(batteryIntent), true);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param connection the network info to set as navigator.connection
*/
private void sendUpdate(JSONObject info, boolean keepCallback) {
if (this.batteryCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, info);
result.setKeepCallback(keepCallback);
this.batteryCallbackContext.sendPluginResult(result);
}
}
}
|
src/android/BatteryListener.java
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.batterystatus;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class BatteryListener extends CordovaPlugin {
private static final String LOG_TAG = "BatteryManager";
BroadcastReceiver receiver;
private CallbackContext batteryCallbackContext = null;
/**
* Constructor.
*/
public BatteryListener() {
this.receiver = null;
}
/**
* Executes the request.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
if (action.equals("start")) {
if (this.batteryCallbackContext != null) {
callbackContext.error( "Battery listener already running.");
return true;
}
this.batteryCallbackContext = callbackContext;
// We need to listen to power events to update battery status
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateBatteryInfo(intent);
}
};
cordova.getActivity().registerReceiver(this.receiver, intentFilter);
}
// Don't return any result now, since status results will be sent when events come in from broadcast receiver
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
else if (action.equals("stop")) {
removeBatteryListener();
this.sendUpdate(new JSONObject(), false); // release status callback in JS side
this.batteryCallbackContext = null;
callbackContext.success();
return true;
}
return false;
}
/**
* Stop battery receiver.
*/
public void onDestroy() {
removeBatteryListener();
}
/**
* Stop battery receiver.
*/
public void onReset() {
removeBatteryListener();
}
/**
* Stop the battery receiver and set it to null.
*/
private void removeBatteryListener() {
if (this.receiver != null) {
try {
this.cordova.getActivity().unregisterReceiver(this.receiver);
this.receiver = null;
} catch (Exception e) {
Log.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);
}
}
}
/**
* Creates a JSONObject with the current battery information
*
* @param batteryIntent the current battery information
* @return a JSONObject containing the battery status information
*/
private JSONObject getBatteryInfo(Intent batteryIntent) {
JSONObject obj = new JSONObject();
try {
obj.put("level", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, 0));
obj.put("isPlugged", batteryIntent.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1) > 0 ? true : false);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return obj;
}
/**
* Updates the JavaScript side whenever the battery changes
*
* @param batteryIntent the current battery information
* @return
*/
private void updateBatteryInfo(Intent batteryIntent) {
sendUpdate(this.getBatteryInfo(batteryIntent), true);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param connection the network info to set as navigator.connection
*/
private void sendUpdate(JSONObject info, boolean keepCallback) {
if (this.batteryCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, info);
result.setKeepCallback(keepCallback);
this.batteryCallbackContext.sendPluginResult(result);
}
}
}
|
CB-7976 Android: Use webView's context rather than Activity's context for intent receiver
|
src/android/BatteryListener.java
|
CB-7976 Android: Use webView's context rather than Activity's context for intent receiver
|
<ide><path>rc/android/BatteryListener.java
<ide> updateBatteryInfo(intent);
<ide> }
<ide> };
<del> cordova.getActivity().registerReceiver(this.receiver, intentFilter);
<add> webView.getContext().registerReceiver(this.receiver, intentFilter);
<ide> }
<ide>
<ide> // Don't return any result now, since status results will be sent when events come in from broadcast receiver
<ide> private void removeBatteryListener() {
<ide> if (this.receiver != null) {
<ide> try {
<del> this.cordova.getActivity().unregisterReceiver(this.receiver);
<add> webView.getContext().unregisterReceiver(this.receiver);
<ide> this.receiver = null;
<ide> } catch (Exception e) {
<ide> Log.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);
|
|
Java
|
bsd-3-clause
|
48941f2aa986d76bca437ffad1102f3150584122
| 0 |
jjfiv/chai
|
package ciir.jfoley.chai.string;
import ciir.jfoley.chai.collections.list.IntList;
import ciir.jfoley.chai.fn.TransformFn;
import gnu.trove.list.array.TCharArrayList;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.text.Normalizer;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author jfoley.
*/
public class StrUtil {
@Nonnull
public static String removeBetween(String input, String start, String end) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
while(true) {
int startPos = input.indexOf(start, lastPos);
if(startPos == -1) break;
int endPos = input.indexOf(end, startPos+start.length());
if(endPos == -1) break;
endPos += end.length();
text.append(input.substring(lastPos, startPos));
lastPos = endPos;
}
text.append(input.substring(lastPos));
return text.toString();
}
@Nonnull
public static String removeBetweenNested(String input, String start, String end) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
while(true) {
int startPos = input.indexOf(start, lastPos);
if(startPos == -1) break;
int endPos = input.indexOf(end, startPos+start.length());
if(endPos == -1) break;
// check for nesting; remove largest matching start,end sequence
while(true) {
int nextStartPos = input.indexOf(start, startPos + start.length());
if(nextStartPos == -1 || nextStartPos > endPos) {
break;
}
int nextEndPos = input.indexOf(end, endPos+end.length());
if(nextEndPos == -1) break;
endPos = nextEndPos;
}
endPos += end.length();
text.append(input.substring(lastPos, startPos));
lastPos = endPos;
}
text.append(input.substring(lastPos));
return text.toString();
}
/**
* Calls transform on every string that exists between patterns start and end on input, and returns the result.
*/
@Nonnull
public static String transformRecursively(String input, Pattern start, Pattern end, Transform fn, boolean inclusive) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
boolean hasNested = false;
while(true) {
Match startMatch = Match.find(input, start, lastPos);
if(startMatch == null) break;
Match endMatch = Match.find(input, end, startMatch.end);
if(endMatch == null) break;
// check for nesting; do inner-most computation first
while(true) {
Match nextStartMatch = Match.find(input, start, startMatch.end);
if(nextStartMatch == null || nextStartMatch.begin > endMatch.begin) {
break;
}
hasNested = true;
startMatch = nextStartMatch;
}
text.append(input.substring(lastPos, startMatch.begin));
if(inclusive) {
text.append(fn.transform(substr(input, startMatch.begin, endMatch.end)));
} else {
text.append(fn.transform(substr(input, startMatch.end, endMatch.begin)));
}
lastPos = endMatch.end;
}
text.append(input.substring(lastPos));
// go again to grab the outer ones
if(hasNested) {
return transformRecursively(text.toString(), start, end, fn, inclusive);
}
return text.toString();
}
public static String substr(String what, int begin, int end) {
if(begin > end) {
return "";
}
return what.substring(Math.max(0, begin), Math.min(end, what.length()-1));
}
/**
* Calls transform on every string that exists between patterns start and end on input, and returns the result.
* Exclusive of the matching patterns
*/
@Nonnull
public static String transformBetween(String input, Pattern start, Pattern end, Transform transform) {
return transformRecursively(input, start, end, transform, false);
}
/**
* Calls transform on every string that exists between patterns start and end on input, and returns the result.
* Inclusive of the matching patterns
*/
@Nonnull
public static String transformInclusive(String input, Pattern start, Pattern end, Transform transform) {
return transformRecursively(input, start, end, transform, true);
}
@Nonnull
public static String removeBetween(String input, Pattern start, Pattern end) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
while(true) {
Match startMatch = Match.find(input, start, lastPos);
if(startMatch == null) break;
Match endMatch = Match.find(input, end, startMatch.end);
if(endMatch == null) break;
text.append(input.substring(lastPos, startMatch.begin));
lastPos = endMatch.end;
}
text.append(input.substring(lastPos));
return text.toString();
}
@Nonnull
public static String takeBefore(String input, String delim) {
int pos = input.indexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(0, pos);
}
@Nonnull
public static String takeBeforeLast(String input, String delim) {
int pos = input.lastIndexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(0, pos);
}
@Nonnull
public static String takeBefore(String input, char delim) {
int pos = input.indexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(0, pos);
}
@Nonnull
public static String takeAfter(String input, String delim) {
int pos = input.indexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(pos + delim.length());
}
@Nonnull
public static String takeBetween(String input, String prefix, String suffix) {
return takeAfter(takeBefore(input, suffix), prefix);
}
@Nonnull
public static String preview(String input, int len) {
input = compactSpaces(input);
if(input.length() < len) {
return input;
} else {
return input.substring(0, len-2)+"..";
}
}
@Nonnull
public static String firstWord(String text) {
for(int i=0; i<text.length(); i++) {
if(Character.isWhitespace(text.charAt(i)))
return text.substring(0,i);
}
return text;
}
public static boolean looksLikeInt(String str, int numDigits) {
if(str.isEmpty()) return false;
if(str.length() > numDigits)
return false;
for(char c : str.toCharArray()) {
if(!Character.isDigit(c))
return false;
}
return true;
}
private static final int numDigitsMaxInt = Integer.toString(Integer.MAX_VALUE).length();
public static boolean looksLikeInt(String str) {
return looksLikeInt(str, numDigitsMaxInt);
}
@Nonnull
public static String removeSpaces(String input) {
StringBuilder output = new StringBuilder();
for(char c : input.toCharArray()) {
if(Character.isWhitespace(c))
continue;
output.append(c);
}
return output.toString();
}
@Nonnull
public static String filterToAscii(String input) {
StringBuilder ascii = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (input.codePointAt(i) <= 127) {
ascii.append(input.charAt(i));
}
}
return ascii.toString();
}
public static boolean isAscii(String input) {
for (int i = 0; i < input.length(); i++) {
if (input.codePointAt(i) > 127) {
return false;
}
}
return true;
}
/** Simplify input string in terms of spaces; all space characters -> ' ' and a maximum width of 1 space. */
@Nonnull
public static String compactSpaces(CharSequence input) {
StringBuilder sb = new StringBuilder();
boolean lastWasSpace = true;
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if(Character.isWhitespace(ch)) {
if(lastWasSpace) continue;
sb.append(' ');
lastWasSpace = true;
continue;
}
lastWasSpace = false;
sb.append(ch);
}
if(lastWasSpace) {
return sb.toString().trim();
}
return sb.toString();
}
/** Remove ending from input string */
@Nonnull
public static String removeBack(String input, String suffix) {
if(!input.endsWith(suffix)) return input;
return input.substring(0, input.length() - suffix.length());
}
/** Remove ending from input string */
@Nonnull
public static String removeBack(String input, int length) {
return input.substring(0, input.length() - length);
}
/** Remove prefix from input string */
public static String removeFront(String input, String prefix) {
if(!input.startsWith(prefix)) return input;
return input.substring(prefix.length());
}
/** Remove prefix and suffix from input string */
@Nonnull
public static String removeSurrounding(String input, String prefix, String suffix) {
if(!input.endsWith(suffix)) return removeFront(input, prefix);
if(!input.startsWith(prefix)) return removeBack(input, suffix);
return input.substring(prefix.length(), input.length() - suffix.length());
}
public static boolean containsAscii(String title) {
for (int i = 0; i < title.length(); i++) {
int code = title.codePointAt(i);
if(code < 128) {
return true;
}
}
return false;
}
@Nonnull
public static String indent(String message, String tabChars) {
StringBuilder sb = new StringBuilder();
for (String line : message.split("\n")) {
sb.append(tabChars).append(line).append('\n');
}
return sb.toString();
}
public static String takeAfterLast(String input, char pattern) {
int index = input.lastIndexOf(pattern);
if(index < 0) return input;
return input.substring(index+1);
}
public static StringBuilder replaceAny(String matching, String withWhat, String expr) {
StringBuilder output = new StringBuilder();
char[] original = expr.toCharArray();
for (char ch : original) {
if (matching.indexOf(ch) >= 0) {
output.append(withWhat);
} else {
output.append(ch);
}
}
return output;
}
public static Long longFromDigits(CharSequence input) {
TCharArrayList digits = new TCharArrayList();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if(Character.isDigit(c)) {
digits.add(c);
for (int j = i+1; j < input.length(); j++) {
final char nc = input.charAt(j);
if(Character.isDigit(nc)) {
digits.add(nc);
} else {
break;
}
}
break;
}
}
if(digits.isEmpty()) {
return null;
}
return Long.parseLong(new String(digits.toArray()));
}
public static boolean containsLetterOrDigit(CharSequence input) {
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if(Character.isLetterOrDigit(c)) {
return true;
}
}
return false;
}
public static String capitalize(String token) {
if(token.length() == 0) return "";
char cap = Character.toUpperCase(token.charAt(0));
if(token.length() == 1) return Character.toString(cap);
return cap + token.substring(1);
}
public static boolean isBlankOrEmpty(String line) {
if(line == null) return true;
for (int i = 0; i < line.length(); i++) {
if(!Character.isWhitespace(line.charAt(i)))
return false;
}
return true;
}
public static boolean isWhitespace(String text) {
for (int i = 0; i < text.length(); i++) {
if(!Character.isWhitespace(text.charAt(i))) return false;
}
return true;
}
public interface Transform extends TransformFn<String,String> { }
@Nonnull
public static String[] pretendTokenize(@Nonnull String input) {
String cleaned = input
.toLowerCase()
.replaceAll("<script[^>]*>[^<]*</script>", " ")
.replaceAll("<style[^>]*>[^<]*</style>", " ")
.replaceAll("<!--.*-->", "")
.replaceAll(" ", " ")
.replaceAll("<[^>]*>", " ")
.replaceAll("\\p{Punct}", " ")
.replace(']', ' ')
.replace('?', ' ')
.replaceAll("^\\p{Alnum}", " ");
return StrUtil.filterToAscii(cleaned).split("\\s+");
}
public static boolean truthy(@Nullable CharSequence seq) {
return seq != null && seq.length() > 0;
}
public static boolean falsy(@Nullable CharSequence seq) {
return !truthy(seq);
}
@Nonnull
public static String join(List<? extends CharSequence> items, CharSequence delimiter) {
if(items.size() == 1) { return items.get(0).toString(); }
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if(i != 0) sb.append(delimiter);
sb.append(items.get(i));
}
return sb.toString();
}
@Nonnull
public static String join(List<? extends CharSequence> items) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if(i != 0) sb.append(' ');
sb.append(items.get(i));
}
return sb.toString();
}
/**
* Copy the unicode code points out of a string and into a list.
* @param input a string.
* @return a list of unicode integer code points.
*/
@Nonnull
public static IntList codePoints(String input) {
IntList unicode = new IntList();
int length = input.length();
for (int offset = 0; offset < length;) {
int codePoint = input.codePointAt(offset);
offset += Character.charCount(codePoint);
unicode.add(codePoint);
}
return unicode;
}
private static Map<String,String> quoteMap = new HashMap<>();
static {
// http://en.wikipedia.org/wiki/Quotation_mark
quoteMap.put("\u2018", "'");
quoteMap.put("\u201a", "'");
quoteMap.put("\u2019", "'");
quoteMap.put("\u201c", "\"");
quoteMap.put("\u201d", "\"");
quoteMap.put("\u201e", "\"");
// convert <<,>> to "
quoteMap.put("\u00ab", "\"");
quoteMap.put("\u00bb", "\"");
// convert <,> to "
quoteMap.put("\u2039", "\"");
quoteMap.put("\u203a", "\"");
// corner marks to single-quotes
quoteMap.put("\u300c", "'");
quoteMap.put("\u300d", "'");
}
@Nonnull
public static String replaceUnicodeQuotes(String input) {
String result = input;
for (Map.Entry<String, String> kv : quoteMap.entrySet()) {
result = result.replaceAll(kv.getKey(), kv.getValue());
}
return result;
}
@Nonnull
public static String slice(@Nonnull String input, int start) {
int begin = Math.min(input.length(), Math.max(0, start));
return input.substring(begin);
}
@Nonnull
public static String slice(@Nonnull String input, int start, int end) {
int begin = Math.min(input.length(), Math.max(0, start));
int size = Math.min(input.length(), (end - begin));
return input.substring(begin, size);
}
private static Pattern diacriticMarks = Pattern.compile("\\p{InCombiningDiacriticalMarks}");
/**
* Convert all accents and tildes and other marks to normalized text for more aggressive matching.
* @param input the input pattern to convert
* @return the input without any marks.
*/
@Nonnull
public static String collapseSpecialMarks(CharSequence input) {
String normed = replaceUnicodeQuotes(Normalizer.normalize(input, Normalizer.Form.NFD));
return diacriticMarks.matcher(normed).replaceAll("");
}
public static List<String> wordWrap(String input, int width) {
ArrayList<String> output = new ArrayList<>();
final char[] chars = input.toCharArray();
final int N = input.length();
if(N < width) {
return Arrays.asList(input.split("\n"));
}
int prevLine = 0;
while(true) {
int newline = -1;
int maxspace = -1;
for (int i = 0; i <= Math.min(N-prevLine-1, width); i++) {
final char c = chars[prevLine + i];
if(c == '\n') {
newline = i;
break;
}
if(Character.isWhitespace(c) || c == '-') {
maxspace = Math.max(prevLine+i, maxspace);
}
}
// handle newlines:
if(newline >= prevLine) {
output.add(new String(chars, prevLine, newline));
prevLine = newline + 1;
continue;
}
int guess = prevLine+width;
//System.out.println(prevLine+", "+guess+", "+chars.length);
int split = -1;
if(guess >= chars.length) { // end of string.
split = chars.length;
} else {
split = maxspace;
}
Character hyphen = null;
if(split == -1 && chars[split+1] != ' ') {
hyphen = '-';
split = guess-1;
}
StringBuilder sb = new StringBuilder();
sb.append(chars, prevLine, split-prevLine);
if(hyphen != null) {
sb.append(hyphen);
prevLine = split;
} else {
prevLine = split + 1;
}
output.add(sb.toString());
if(split == chars.length) break;
}
return output;
}
}
|
src/main/java/ciir/jfoley/chai/string/StrUtil.java
|
package ciir.jfoley.chai.string;
import ciir.jfoley.chai.collections.list.IntList;
import ciir.jfoley.chai.fn.TransformFn;
import gnu.trove.list.array.TCharArrayList;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.text.Normalizer;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author jfoley.
*/
public class StrUtil {
@Nonnull
public static String removeBetween(String input, String start, String end) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
while(true) {
int startPos = input.indexOf(start, lastPos);
if(startPos == -1) break;
int endPos = input.indexOf(end, startPos+start.length());
if(endPos == -1) break;
endPos += end.length();
text.append(input.substring(lastPos, startPos));
lastPos = endPos;
}
text.append(input.substring(lastPos));
return text.toString();
}
@Nonnull
public static String removeBetweenNested(String input, String start, String end) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
while(true) {
int startPos = input.indexOf(start, lastPos);
if(startPos == -1) break;
int endPos = input.indexOf(end, startPos+start.length());
if(endPos == -1) break;
// check for nesting; remove largest matching start,end sequence
while(true) {
int nextStartPos = input.indexOf(start, startPos + start.length());
if(nextStartPos == -1 || nextStartPos > endPos) {
break;
}
int nextEndPos = input.indexOf(end, endPos+end.length());
if(nextEndPos == -1) break;
endPos = nextEndPos;
}
endPos += end.length();
text.append(input.substring(lastPos, startPos));
lastPos = endPos;
}
text.append(input.substring(lastPos));
return text.toString();
}
/**
* Calls transform on every string that exists between patterns start and end on input, and returns the result.
*/
@Nonnull
public static String transformRecursively(String input, Pattern start, Pattern end, Transform fn, boolean inclusive) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
boolean hasNested = false;
while(true) {
Match startMatch = Match.find(input, start, lastPos);
if(startMatch == null) break;
Match endMatch = Match.find(input, end, startMatch.end);
if(endMatch == null) break;
// check for nesting; do inner-most computation first
while(true) {
Match nextStartMatch = Match.find(input, start, startMatch.end);
if(nextStartMatch == null || nextStartMatch.begin > endMatch.begin) {
break;
}
hasNested = true;
startMatch = nextStartMatch;
}
text.append(input.substring(lastPos, startMatch.begin));
if(inclusive) {
text.append(fn.transform(substr(input, startMatch.begin, endMatch.end)));
} else {
text.append(fn.transform(substr(input, startMatch.end, endMatch.begin)));
}
lastPos = endMatch.end;
}
text.append(input.substring(lastPos));
// go again to grab the outer ones
if(hasNested) {
return transformRecursively(text.toString(), start, end, fn, inclusive);
}
return text.toString();
}
public static String substr(String what, int begin, int end) {
if(begin > end) {
return "";
}
return what.substring(Math.max(0, begin), Math.min(end, what.length()-1));
}
/**
* Calls transform on every string that exists between patterns start and end on input, and returns the result.
* Exclusive of the matching patterns
*/
@Nonnull
public static String transformBetween(String input, Pattern start, Pattern end, Transform transform) {
return transformRecursively(input, start, end, transform, false);
}
/**
* Calls transform on every string that exists between patterns start and end on input, and returns the result.
* Inclusive of the matching patterns
*/
@Nonnull
public static String transformInclusive(String input, Pattern start, Pattern end, Transform transform) {
return transformRecursively(input, start, end, transform, true);
}
@Nonnull
public static String removeBetween(String input, Pattern start, Pattern end) {
StringBuilder text = new StringBuilder();
int lastPos = 0;
while(true) {
Match startMatch = Match.find(input, start, lastPos);
if(startMatch == null) break;
Match endMatch = Match.find(input, end, startMatch.end);
if(endMatch == null) break;
text.append(input.substring(lastPos, startMatch.begin));
lastPos = endMatch.end;
}
text.append(input.substring(lastPos));
return text.toString();
}
@Nonnull
public static String takeBefore(String input, String delim) {
int pos = input.indexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(0, pos);
}
@Nonnull
public static String takeBeforeLast(String input, String delim) {
int pos = input.lastIndexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(0, pos);
}
@Nonnull
public static String takeBefore(String input, char delim) {
int pos = input.indexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(0, pos);
}
@Nonnull
public static String takeAfter(String input, String delim) {
int pos = input.indexOf(delim);
if(pos == -1) {
return input;
}
return input.substring(pos + delim.length());
}
@Nonnull
public static String takeBetween(String input, String prefix, String suffix) {
return takeAfter(takeBefore(input, suffix), prefix);
}
@Nonnull
public static String preview(String input, int len) {
input = compactSpaces(input);
if(input.length() < len) {
return input;
} else {
return input.substring(0, len-2)+"..";
}
}
@Nonnull
public static String firstWord(String text) {
for(int i=0; i<text.length(); i++) {
if(Character.isWhitespace(text.charAt(i)))
return text.substring(0,i);
}
return text;
}
public static boolean looksLikeInt(String str, int numDigits) {
if(str.isEmpty()) return false;
if(str.length() > numDigits)
return false;
for(char c : str.toCharArray()) {
if(!Character.isDigit(c))
return false;
}
return true;
}
private static final int numDigitsMaxInt = Integer.toString(Integer.MAX_VALUE).length();
public static boolean looksLikeInt(String str) {
return looksLikeInt(str, numDigitsMaxInt);
}
@Nonnull
public static String removeSpaces(String input) {
StringBuilder output = new StringBuilder();
for(char c : input.toCharArray()) {
if(Character.isWhitespace(c))
continue;
output.append(c);
}
return output.toString();
}
@Nonnull
public static String filterToAscii(String input) {
StringBuilder ascii = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (input.codePointAt(i) <= 127) {
ascii.append(input.charAt(i));
}
}
return ascii.toString();
}
public static boolean isAscii(String input) {
for (int i = 0; i < input.length(); i++) {
if (input.codePointAt(i) > 127) {
return false;
}
}
return true;
}
/** Simplify input string in terms of spaces; all space characters -> ' ' and a maximum width of 1 space. */
@Nonnull
public static String compactSpaces(CharSequence input) {
StringBuilder sb = new StringBuilder();
boolean lastWasSpace = true;
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if(Character.isWhitespace(ch)) {
if(lastWasSpace) continue;
sb.append(' ');
lastWasSpace = true;
continue;
}
lastWasSpace = false;
sb.append(ch);
}
if(lastWasSpace) {
return sb.toString().trim();
}
return sb.toString();
}
/** Remove ending from input string */
@Nonnull
public static String removeBack(String input, String suffix) {
if(!input.endsWith(suffix)) return input;
return input.substring(0, input.length() - suffix.length());
}
/** Remove ending from input string */
@Nonnull
public static String removeBack(String input, int length) {
return input.substring(0, input.length() - length);
}
/** Remove prefix from input string */
public static String removeFront(String input, String prefix) {
if(!input.startsWith(prefix)) return input;
return input.substring(prefix.length());
}
/** Remove prefix and suffix from input string */
@Nonnull
public static String removeSurrounding(String input, String prefix, String suffix) {
if(!input.endsWith(suffix)) return removeFront(input, prefix);
if(!input.startsWith(prefix)) return removeBack(input, suffix);
return input.substring(prefix.length(), input.length() - suffix.length());
}
public static boolean containsAscii(String title) {
for (int i = 0; i < title.length(); i++) {
int code = title.codePointAt(i);
if(code < 128) {
return true;
}
}
return false;
}
@Nonnull
public static String indent(String message, String tabChars) {
StringBuilder sb = new StringBuilder();
for (String line : message.split("\n")) {
sb.append(tabChars).append(line).append('\n');
}
return sb.toString();
}
public static String takeAfterLast(String input, char pattern) {
int index = input.lastIndexOf(pattern);
if(index < 0) return input;
return input.substring(index+1);
}
public static StringBuilder replaceAny(String matching, String withWhat, String expr) {
StringBuilder output = new StringBuilder();
char[] original = expr.toCharArray();
for (char ch : original) {
if (matching.indexOf(ch) >= 0) {
output.append(withWhat);
} else {
output.append(ch);
}
}
return output;
}
public static Long longFromDigits(CharSequence input) {
TCharArrayList digits = new TCharArrayList();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if(Character.isDigit(c)) {
digits.add(c);
for (int j = i+1; j < input.length(); j++) {
final char nc = input.charAt(j);
if(Character.isDigit(nc)) {
digits.add(nc);
} else {
break;
}
}
break;
}
}
if(digits.isEmpty()) {
return null;
}
return Long.parseLong(new String(digits.toArray()));
}
public static boolean containsLetterOrDigit(CharSequence input) {
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if(Character.isLetterOrDigit(c)) {
return true;
}
}
return false;
}
public static String capitalize(String token) {
if(token.length() == 0) return "";
char cap = Character.toUpperCase(token.charAt(0));
if(token.length() == 1) return Character.toString(cap);
return cap + token.substring(1);
}
public static boolean isBlankOrEmpty(String line) {
if(line == null) return true;
for (int i = 0; i < line.length(); i++) {
if(!Character.isWhitespace(line.charAt(i)))
return false;
}
return true;
}
public interface Transform extends TransformFn<String,String> { }
@Nonnull
public static String[] pretendTokenize(@Nonnull String input) {
String cleaned = input
.toLowerCase()
.replaceAll("<script[^>]*>[^<]*</script>", " ")
.replaceAll("<style[^>]*>[^<]*</style>", " ")
.replaceAll("<!--.*-->", "")
.replaceAll(" ", " ")
.replaceAll("<[^>]*>", " ")
.replaceAll("\\p{Punct}", " ")
.replace(']', ' ')
.replace('?', ' ')
.replaceAll("^\\p{Alnum}", " ");
return StrUtil.filterToAscii(cleaned).split("\\s+");
}
public static boolean truthy(@Nullable CharSequence seq) {
return seq != null && seq.length() > 0;
}
public static boolean falsy(@Nullable CharSequence seq) {
return !truthy(seq);
}
@Nonnull
public static String join(List<? extends CharSequence> items, CharSequence delimiter) {
if(items.size() == 1) { return items.get(0).toString(); }
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if(i != 0) sb.append(delimiter);
sb.append(items.get(i));
}
return sb.toString();
}
@Nonnull
public static String join(List<? extends CharSequence> items) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if(i != 0) sb.append(' ');
sb.append(items.get(i));
}
return sb.toString();
}
/**
* Copy the unicode code points out of a string and into a list.
* @param input a string.
* @return a list of unicode integer code points.
*/
@Nonnull
public static IntList codePoints(String input) {
IntList unicode = new IntList();
int length = input.length();
for (int offset = 0; offset < length;) {
int codePoint = input.codePointAt(offset);
offset += Character.charCount(codePoint);
unicode.add(codePoint);
}
return unicode;
}
private static Map<String,String> quoteMap = new HashMap<>();
static {
// http://en.wikipedia.org/wiki/Quotation_mark
quoteMap.put("\u2018", "'");
quoteMap.put("\u201a", "'");
quoteMap.put("\u2019", "'");
quoteMap.put("\u201c", "\"");
quoteMap.put("\u201d", "\"");
quoteMap.put("\u201e", "\"");
// convert <<,>> to "
quoteMap.put("\u00ab", "\"");
quoteMap.put("\u00bb", "\"");
// convert <,> to "
quoteMap.put("\u2039", "\"");
quoteMap.put("\u203a", "\"");
// corner marks to single-quotes
quoteMap.put("\u300c", "'");
quoteMap.put("\u300d", "'");
}
@Nonnull
public static String replaceUnicodeQuotes(String input) {
String result = input;
for (Map.Entry<String, String> kv : quoteMap.entrySet()) {
result = result.replaceAll(kv.getKey(), kv.getValue());
}
return result;
}
@Nonnull
public static String slice(@Nonnull String input, int start) {
int begin = Math.min(input.length(), Math.max(0, start));
return input.substring(begin);
}
@Nonnull
public static String slice(@Nonnull String input, int start, int end) {
int begin = Math.min(input.length(), Math.max(0, start));
int size = Math.min(input.length(), (end - begin));
return input.substring(begin, size);
}
private static Pattern diacriticMarks = Pattern.compile("\\p{InCombiningDiacriticalMarks}");
/**
* Convert all accents and tildes and other marks to normalized text for more aggressive matching.
* @param input the input pattern to convert
* @return the input without any marks.
*/
@Nonnull
public static String collapseSpecialMarks(CharSequence input) {
String normed = replaceUnicodeQuotes(Normalizer.normalize(input, Normalizer.Form.NFD));
return diacriticMarks.matcher(normed).replaceAll("");
}
public static List<String> wordWrap(String input, int width) {
ArrayList<String> output = new ArrayList<>();
final char[] chars = input.toCharArray();
final int N = input.length();
if(N < width) {
return Arrays.asList(input.split("\n"));
}
int prevLine = 0;
while(true) {
int newline = -1;
int maxspace = -1;
for (int i = 0; i <= Math.min(N-prevLine-1, width); i++) {
final char c = chars[prevLine + i];
if(c == '\n') {
newline = i;
break;
}
if(Character.isWhitespace(c) || c == '-') {
maxspace = Math.max(prevLine+i, maxspace);
}
}
// handle newlines:
if(newline >= prevLine) {
output.add(new String(chars, prevLine, newline));
prevLine = newline + 1;
continue;
}
int guess = prevLine+width;
//System.out.println(prevLine+", "+guess+", "+chars.length);
int split = -1;
if(guess >= chars.length) { // end of string.
split = chars.length;
} else {
split = maxspace;
}
Character hyphen = null;
if(split == -1 && chars[split+1] != ' ') {
hyphen = '-';
split = guess-1;
}
StringBuilder sb = new StringBuilder();
sb.append(chars, prevLine, split-prevLine);
if(hyphen != null) {
sb.append(hyphen);
prevLine = split;
} else {
prevLine = split + 1;
}
output.add(sb.toString());
if(split == chars.length) break;
}
return output;
}
}
|
StrUtil.isWhitespace
|
src/main/java/ciir/jfoley/chai/string/StrUtil.java
|
StrUtil.isWhitespace
|
<ide><path>rc/main/java/ciir/jfoley/chai/string/StrUtil.java
<ide> return true;
<ide> }
<ide>
<add> public static boolean isWhitespace(String text) {
<add> for (int i = 0; i < text.length(); i++) {
<add> if(!Character.isWhitespace(text.charAt(i))) return false;
<add> }
<add> return true;
<add> }
<add>
<ide> public interface Transform extends TransformFn<String,String> { }
<ide>
<ide> @Nonnull
|
|
Java
|
apache-2.0
|
dafcc7d42fcb7d71b8d02e163a6f98a9f6142991
| 0 |
vjr/snappydata,vjr/snappydata,vjr/snappydata,vjr/snappydata
|
package io.snappydata.util.com.clearspring.analytics.stream;
/*
* Copyright (C) 2011 Clearspring Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.clearspring.analytics.util.DoublyLinkedList;
import com.clearspring.analytics.util.ListNode2;
import com.clearspring.analytics.util.Pair;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Based on the <i>Space-Saving</i> algorithm and the <i>Stream-Summary</i> data
* structure as described in: <i>Efficient Computation of Frequent and Top-k
* Elements in Data Streams</i> by Metwally, Agrawal, and Abbadi
*
* @param <T> type of data in the stream to be summarized
*/
public class StreamSummary<T> implements ITopK<T> {
protected class Bucket {
protected final DoublyLinkedList<Counter<T>> counterList;
private final long count;
public Bucket(long count) {
this.count = count;
this.counterList = new DoublyLinkedList<>();
}
}
protected final int capacity;
private final HashMap<T, ListNode2<Counter<T>>> counterMap;
protected final DoublyLinkedList<Bucket> bucketList;
/**
* @param capacity maximum size (larger capacities improve accuracy)
*/
public StreamSummary(int capacity) {
this.capacity = capacity;
counterMap = new HashMap<>();
bucketList = new DoublyLinkedList<>();
}
public int getCapacity() {
return capacity;
}
/**
* Algorithm: <i>Space-Saving</i>
*
* @param item stream element (<i>e</i>)
* @return false if item was already in the stream summary, true otherwise
*/
@Override
public boolean offer(T item) {
return offer(item, 1);
}
/**
* Algorithm: <i>Space-Saving</i>
*
* @param item stream element (<i>e</i>)
* @return false if item was already in the stream summary, true otherwise
*/
@Override
public boolean offer(T item, int incrementCount) {
return offerReturnAll(item, incrementCount).left;
}
/**
* @param item stream element (<i>e</i>)
* @return item dropped from summary if an item was dropped, null otherwise
*/
public T offerReturnDropped(T item, int incrementCount) {
return offerReturnAll(item, incrementCount).right;
}
/**
* @param item stream element (<i>e</i>)
* @return Pair<isNewItem, itemDropped> where isNewItem is the return
* value of offer() and itemDropped is null if no item was dropped
*/
public Pair<Boolean, T> offerReturnAll(T item, int incrementCount) {
ListNode2<Counter<T>> counterNode = counterMap.get(item);
boolean isNewItem = (counterNode == null);
T droppedItem = null;
if (isNewItem) {
if (size() < capacity) {
counterNode = bucketList.enqueue(new Bucket(0)).getValue().counterList
.add(new Counter<>(bucketList.tail(), item));
} else {
Bucket min = bucketList.first();
counterNode = min.counterList.tail();
Counter<T> counter = counterNode.getValue();
droppedItem = counter.item;
counterMap.remove(droppedItem);
counter.item = item;
counter.error = min.count;
}
counterMap.put(item, counterNode);
}
incrementCounter(counterNode, incrementCount);
return new Pair<>(isNewItem, droppedItem);
}
protected void incrementCounter(ListNode2<Counter<T>> counterNode,
int incrementCount) {
Counter<T> counter = counterNode.getValue(); // count_i
ListNode2<Bucket> oldNode = counter.bucketNode;
Bucket bucket = oldNode.getValue(); // Let Bucket_i be the bucket of count_i
bucket.counterList.remove(counterNode); // Detach count_i from Bucket_i's
// child-list
counter.count = counter.count + incrementCount;
// Finding the right bucket for count_i
// Because we allow a single call to increment count more than once, this
// may not be the adjacent bucket.
ListNode2<Bucket> bucketNodePrev = oldNode;
ListNode2<Bucket> bucketNodeNext = bucketNodePrev.getNext();
while (bucketNodeNext != null) {
Bucket bucketNext = bucketNodeNext.getValue(); // Let Bucket_i^+ be
// Bucket_i's neighbor of larger value
if (counter.count == bucketNext.count) {
bucketNext.counterList.add(counterNode); // Attach count_i to
// Bucket_i^+'s child-list
break;
} else if (counter.count > bucketNext.count) {
bucketNodePrev = bucketNodeNext;
bucketNodeNext = bucketNodePrev.getNext(); // Continue hunting for an
// appropriate bucket
} else {
// A new bucket has to be created
bucketNodeNext = null;
}
}
if (bucketNodeNext == null) {
Bucket bucketNext = new Bucket(counter.count);
bucketNext.counterList.add(counterNode);
bucketNodeNext = bucketList.addAfter(bucketNodePrev, bucketNext);
}
counter.bucketNode = bucketNodeNext;
// Cleaning up
if (bucket.counterList.isEmpty()) { // If Bucket_i's child-list is empty
bucketList.remove(oldNode); // Detach Bucket_i from the Stream-Summary
}
}
@Override
public List<T> peek(int k) {
List<T> topK = new ArrayList<>(k);
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
.getPrev()) {
Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
if (topK.size() == k) {
return topK;
}
topK.add(c.item);
}
}
return topK;
}
public List<Counter<T>> topK(int k) {
List<Counter<T>> topK = new ArrayList<>(k);
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null;
bNode = bNode.getPrev()) {
Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
if (topK.size() == k) {
return topK;
}
topK.add(c);
}
}
return topK;
}
/**
* @return number of items stored
*/
public int size() {
return counterMap.size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null;
bNode = bNode.getPrev()) {
Bucket b = bNode.getValue();
sb.append('{');
sb.append(b.count);
sb.append(":[");
for (Counter<T> c : b.counterList) {
sb.append('{');
sb.append(c.item);
sb.append(':');
sb.append(c.error);
sb.append("},");
}
if (b.counterList.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]},");
}
if (bucketList.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(']');
return sb.toString();
}
public static <T> void write(Kryo kryo, Output output, StreamSummary<T> obj) {
output.writeInt(obj.capacity);
output.writeInt(obj.size());
for (ListNode2<StreamSummary<T>.Bucket> bNode = obj.bucketList.tail();
bNode != null; bNode = bNode.getNext()) {
StreamSummary<T>.Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
kryo.writeObject(output, c);
}
}
}
public static <T> StreamSummary<T> read(Kryo kryo, Input input) {
int capacity = input.readInt();
int size = input.readInt();
StreamSummary<T> deser = new StreamSummary<>(capacity);
StreamSummary<T>.Bucket currentBucket = null;
ListNode2<StreamSummary<T>.Bucket> currentBucketNode = null;
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked")
Counter<T> c = (Counter<T>)kryo.readObject(input, Counter.class);
if (currentBucket == null || c.count != currentBucket.count) {
currentBucket = deser.new Bucket(c.count);
currentBucketNode = deser.bucketList.add(currentBucket);
}
c.bucketNode = currentBucketNode;
deser.counterMap.put(c.item, currentBucket.counterList.add(c));
}
return deser;
}
}
|
snappy-core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/StreamSummary.java
|
package io.snappydata.util.com.clearspring.analytics.stream;
/*
* Copyright (C) 2011 Clearspring Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.clearspring.analytics.util.DoublyLinkedList;
import com.clearspring.analytics.util.ListNode2;
import com.clearspring.analytics.util.Pair;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Based on the <i>Space-Saving</i> algorithm and the <i>Stream-Summary</i> data
* structure as described in: <i>Efficient Computation of Frequent and Top-k
* Elements in Data Streams</i> by Metwally, Agrawal, and Abbadi
*
* @param <T>
* type of data in the stream to be summarized
*/
public class StreamSummary<T> implements ITopK<T> {
protected class Bucket {
protected final DoublyLinkedList<Counter<T>> counterList;
private final long count;
public Bucket(long count) {
this.count = count;
this.counterList = new DoublyLinkedList<Counter<T>>();
}
}
protected final int capacity;
private final HashMap<T, ListNode2<Counter<T>>> counterMap;
protected final DoublyLinkedList<Bucket> bucketList;
/**
* @param capacity
* maximum size (larger capacities improve accuracy)
*/
public StreamSummary(int capacity) {
this.capacity = capacity;
counterMap = new HashMap<T, ListNode2<Counter<T>>>();
bucketList = new DoublyLinkedList<Bucket>();
}
public int getCapacity() {
return capacity;
}
/**
* Algorithm: <i>Space-Saving</i>
*
* @param item
* stream element (<i>e</i>)
* @return false if item was already in the stream summary, true otherwise
*/
@Override
public boolean offer(T item) {
return offer(item, 1);
}
/**
* Algorithm: <i>Space-Saving</i>
*
* @param item
* stream element (<i>e</i>)
* @return false if item was already in the stream summary, true otherwise
*/
@Override
public boolean offer(T item, int incrementCount) {
return offerReturnAll(item, incrementCount).left;
}
/**
* @param item
* stream element (<i>e</i>)
* @return item dropped from summary if an item was dropped, null otherwise
*/
public T offerReturnDropped(T item, int incrementCount) {
return offerReturnAll(item, incrementCount).right;
}
/**
* @param item
* stream element (<i>e</i>)
* @return Pair<isNewItem, itemDropped> where isNewItem is the return value of
* offer() and itemDropped is null if no item was dropped
*/
public Pair<Boolean, T> offerReturnAll(T item, int incrementCount) {
ListNode2<Counter<T>> counterNode = counterMap.get(item);
boolean isNewItem = (counterNode == null);
T droppedItem = null;
if (isNewItem) {
if (size() < capacity) {
counterNode = bucketList.enqueue(new Bucket(0)).getValue().counterList
.add(new Counter<T>(bucketList.tail(), item));
} else {
Bucket min = bucketList.first();
counterNode = min.counterList.tail();
Counter<T> counter = counterNode.getValue();
droppedItem = counter.item;
counterMap.remove(droppedItem);
counter.item = item;
counter.error = min.count;
}
counterMap.put(item, counterNode);
}
incrementCounter(counterNode, incrementCount);
return new Pair<Boolean, T>(isNewItem, droppedItem);
}
protected void incrementCounter(ListNode2<Counter<T>> counterNode,
int incrementCount) {
Counter<T> counter = counterNode.getValue(); // count_i
ListNode2<Bucket> oldNode = counter.bucketNode;
Bucket bucket = oldNode.getValue(); // Let Bucket_i be the bucket of count_i
bucket.counterList.remove(counterNode); // Detach count_i from Bucket_i's
// child-list
counter.count = counter.count + incrementCount;
// Finding the right bucket for count_i
// Because we allow a single call to increment count more than once, this
// may not be the adjacent bucket.
ListNode2<Bucket> bucketNodePrev = oldNode;
ListNode2<Bucket> bucketNodeNext = bucketNodePrev.getNext();
while (bucketNodeNext != null) {
Bucket bucketNext = bucketNodeNext.getValue(); // Let Bucket_i^+ be
// Bucket_i's neighbor of
// larger value
if (counter.count == bucketNext.count) {
bucketNext.counterList.add(counterNode); // Attach count_i to
// Bucket_i^+'s child-list
break;
} else if (counter.count > bucketNext.count) {
bucketNodePrev = bucketNodeNext;
bucketNodeNext = bucketNodePrev.getNext(); // Continue hunting for an
// appropriate bucket
} else {
// A new bucket has to be created
bucketNodeNext = null;
}
}
if (bucketNodeNext == null) {
Bucket bucketNext = new Bucket(counter.count);
bucketNext.counterList.add(counterNode);
bucketNodeNext = bucketList.addAfter(bucketNodePrev, bucketNext);
}
counter.bucketNode = bucketNodeNext;
// Cleaning up
if (bucket.counterList.isEmpty()) // If Bucket_i's child-list is empty
{
bucketList.remove(oldNode); // Detach Bucket_i from the Stream-Summary
}
}
@Override
public List<T> peek(int k) {
List<T> topK = new ArrayList<T>(k);
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
.getPrev()) {
Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
if (topK.size() == k) {
return topK;
}
topK.add(c.item);
}
}
return topK;
}
public List<Counter<T>> topK(int k) {
List<Counter<T>> topK = new ArrayList<Counter<T>>(k);
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
.getPrev()) {
Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
if (topK.size() == k) {
return topK;
}
topK.add(c);
}
}
return topK;
}
/**
* @return number of items stored
*/
public int size() {
return counterMap.size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
.getPrev()) {
Bucket b = bNode.getValue();
sb.append('{');
sb.append(b.count);
sb.append(":[");
for (Counter<T> c : b.counterList) {
sb.append('{');
sb.append(c.item);
sb.append(':');
sb.append(c.error);
sb.append("},");
}
if (b.counterList.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]},");
}
if (bucketList.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(']');
return sb.toString();
}
public static <T> void write(Kryo kryo, Output output, StreamSummary<T> obj) {
output.writeInt(obj.capacity);
output.writeInt(obj.size());
for (ListNode2<StreamSummary<T>.Bucket> bNode = obj.bucketList.tail(); bNode != null; bNode = bNode
.getNext()) {
StreamSummary<T>.Bucket b = bNode.getValue();
for (Counter<T> c : b.counterList) {
kryo.writeObject(output, c);
}
}
}
public static <T> StreamSummary<T> read(Kryo kryo, Input input) {
int capacity = input.readInt();
int size = input.readInt();
StreamSummary<T> deser = new StreamSummary<T>(capacity);
StreamSummary<T>.Bucket currentBucket = null;
ListNode2<StreamSummary<T>.Bucket> currentBucketNode = null;
for (int i = 0; i < size; i++) {
Counter<T> c = (Counter<T>) kryo.readObject(input, Counter.class);
if (currentBucket == null || c.count != currentBucket.count) {
currentBucket = deser.new Bucket(c.count);
currentBucketNode = deser.bucketList.add(currentBucket);
}
c.bucketNode = currentBucketNode;
deser.counterMap.put(c.item, currentBucket.counterList.add(c));
}
return deser;
}
}
|
correcting unchecked warnings in StreamSummary
|
snappy-core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/StreamSummary.java
|
correcting unchecked warnings in StreamSummary
|
<ide><path>nappy-core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/StreamSummary.java
<ide> * structure as described in: <i>Efficient Computation of Frequent and Top-k
<ide> * Elements in Data Streams</i> by Metwally, Agrawal, and Abbadi
<ide> *
<del> * @param <T>
<del> * type of data in the stream to be summarized
<add> * @param <T> type of data in the stream to be summarized
<ide> */
<ide> public class StreamSummary<T> implements ITopK<T> {
<ide>
<ide>
<ide> public Bucket(long count) {
<ide> this.count = count;
<del> this.counterList = new DoublyLinkedList<Counter<T>>();
<add> this.counterList = new DoublyLinkedList<>();
<ide> }
<ide> }
<ide>
<ide> protected final DoublyLinkedList<Bucket> bucketList;
<ide>
<ide> /**
<del> * @param capacity
<del> * maximum size (larger capacities improve accuracy)
<add> * @param capacity maximum size (larger capacities improve accuracy)
<ide> */
<ide> public StreamSummary(int capacity) {
<ide> this.capacity = capacity;
<del> counterMap = new HashMap<T, ListNode2<Counter<T>>>();
<del> bucketList = new DoublyLinkedList<Bucket>();
<add> counterMap = new HashMap<>();
<add> bucketList = new DoublyLinkedList<>();
<ide>
<ide> }
<ide>
<ide> /**
<ide> * Algorithm: <i>Space-Saving</i>
<ide> *
<del> * @param item
<del> * stream element (<i>e</i>)
<add> * @param item stream element (<i>e</i>)
<ide> * @return false if item was already in the stream summary, true otherwise
<ide> */
<ide> @Override
<ide> /**
<ide> * Algorithm: <i>Space-Saving</i>
<ide> *
<del> * @param item
<del> * stream element (<i>e</i>)
<add> * @param item stream element (<i>e</i>)
<ide> * @return false if item was already in the stream summary, true otherwise
<ide> */
<ide> @Override
<ide> }
<ide>
<ide> /**
<del> * @param item
<del> * stream element (<i>e</i>)
<add> * @param item stream element (<i>e</i>)
<ide> * @return item dropped from summary if an item was dropped, null otherwise
<ide> */
<ide> public T offerReturnDropped(T item, int incrementCount) {
<ide> }
<ide>
<ide> /**
<del> * @param item
<del> * stream element (<i>e</i>)
<del> * @return Pair<isNewItem, itemDropped> where isNewItem is the return value of
<del> * offer() and itemDropped is null if no item was dropped
<add> * @param item stream element (<i>e</i>)
<add> * @return Pair<isNewItem, itemDropped> where isNewItem is the return
<add> * value of offer() and itemDropped is null if no item was dropped
<ide> */
<ide> public Pair<Boolean, T> offerReturnAll(T item, int incrementCount) {
<ide> ListNode2<Counter<T>> counterNode = counterMap.get(item);
<ide>
<ide> if (size() < capacity) {
<ide> counterNode = bucketList.enqueue(new Bucket(0)).getValue().counterList
<del> .add(new Counter<T>(bucketList.tail(), item));
<add> .add(new Counter<>(bucketList.tail(), item));
<ide> } else {
<ide> Bucket min = bucketList.first();
<ide> counterNode = min.counterList.tail();
<ide>
<ide> incrementCounter(counterNode, incrementCount);
<ide>
<del> return new Pair<Boolean, T>(isNewItem, droppedItem);
<add> return new Pair<>(isNewItem, droppedItem);
<ide> }
<ide>
<ide> protected void incrementCounter(ListNode2<Counter<T>> counterNode,
<del> int incrementCount) {
<add> int incrementCount) {
<ide> Counter<T> counter = counterNode.getValue(); // count_i
<ide> ListNode2<Bucket> oldNode = counter.bucketNode;
<ide> Bucket bucket = oldNode.getValue(); // Let Bucket_i be the bucket of count_i
<ide> bucket.counterList.remove(counterNode); // Detach count_i from Bucket_i's
<del> // child-list
<add> // child-list
<ide> counter.count = counter.count + incrementCount;
<ide>
<ide> // Finding the right bucket for count_i
<ide> ListNode2<Bucket> bucketNodeNext = bucketNodePrev.getNext();
<ide> while (bucketNodeNext != null) {
<ide> Bucket bucketNext = bucketNodeNext.getValue(); // Let Bucket_i^+ be
<del> // Bucket_i's neighbor of
<del> // larger value
<add> // Bucket_i's neighbor of larger value
<ide> if (counter.count == bucketNext.count) {
<ide> bucketNext.counterList.add(counterNode); // Attach count_i to
<del> // Bucket_i^+'s child-list
<add> // Bucket_i^+'s child-list
<ide> break;
<ide> } else if (counter.count > bucketNext.count) {
<ide> bucketNodePrev = bucketNodeNext;
<ide> bucketNodeNext = bucketNodePrev.getNext(); // Continue hunting for an
<del> // appropriate bucket
<add> // appropriate bucket
<ide> } else {
<ide> // A new bucket has to be created
<ide> bucketNodeNext = null;
<ide> counter.bucketNode = bucketNodeNext;
<ide>
<ide> // Cleaning up
<del> if (bucket.counterList.isEmpty()) // If Bucket_i's child-list is empty
<del> {
<add> if (bucket.counterList.isEmpty()) { // If Bucket_i's child-list is empty
<ide> bucketList.remove(oldNode); // Detach Bucket_i from the Stream-Summary
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public List<T> peek(int k) {
<del> List<T> topK = new ArrayList<T>(k);
<add> List<T> topK = new ArrayList<>(k);
<ide>
<ide> for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
<ide> .getPrev()) {
<ide> }
<ide>
<ide> public List<Counter<T>> topK(int k) {
<del> List<Counter<T>> topK = new ArrayList<Counter<T>>(k);
<del>
<del> for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
<del> .getPrev()) {
<add> List<Counter<T>> topK = new ArrayList<>(k);
<add>
<add> for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null;
<add> bNode = bNode.getPrev()) {
<ide> Bucket b = bNode.getValue();
<ide> for (Counter<T> c : b.counterList) {
<ide> if (topK.size() == k) {
<ide> public String toString() {
<ide> StringBuilder sb = new StringBuilder();
<ide> sb.append('[');
<del> for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode
<del> .getPrev()) {
<add> for (ListNode2<Bucket> bNode = bucketList.head(); bNode != null;
<add> bNode = bNode.getPrev()) {
<ide> Bucket b = bNode.getValue();
<ide> sb.append('{');
<ide> sb.append(b.count);
<ide> public static <T> void write(Kryo kryo, Output output, StreamSummary<T> obj) {
<ide> output.writeInt(obj.capacity);
<ide> output.writeInt(obj.size());
<del> for (ListNode2<StreamSummary<T>.Bucket> bNode = obj.bucketList.tail(); bNode != null; bNode = bNode
<del> .getNext()) {
<add> for (ListNode2<StreamSummary<T>.Bucket> bNode = obj.bucketList.tail();
<add> bNode != null; bNode = bNode.getNext()) {
<ide> StreamSummary<T>.Bucket b = bNode.getValue();
<ide> for (Counter<T> c : b.counterList) {
<ide> kryo.writeObject(output, c);
<ide> public static <T> StreamSummary<T> read(Kryo kryo, Input input) {
<ide> int capacity = input.readInt();
<ide> int size = input.readInt();
<del> StreamSummary<T> deser = new StreamSummary<T>(capacity);
<add> StreamSummary<T> deser = new StreamSummary<>(capacity);
<ide> StreamSummary<T>.Bucket currentBucket = null;
<ide> ListNode2<StreamSummary<T>.Bucket> currentBucketNode = null;
<ide>
<ide> for (int i = 0; i < size; i++) {
<del> Counter<T> c = (Counter<T>) kryo.readObject(input, Counter.class);
<add> @SuppressWarnings("unchecked")
<add> Counter<T> c = (Counter<T>)kryo.readObject(input, Counter.class);
<ide> if (currentBucket == null || c.count != currentBucket.count) {
<ide> currentBucket = deser.new Bucket(c.count);
<ide> currentBucketNode = deser.bucketList.add(currentBucket);
<ide> }
<ide> return deser;
<ide> }
<del>
<ide> }
|
|
Java
|
mit
|
e1fc158a27e574183f597fde1db20a785b4a56de
| 0 |
taxi-wind/logbook,kyuntx/logbookpn,taxi-wind/logbook
|
/**
* No Rights Reserved.
* This program and the accompanying materials
* are made available under the terms of the Public Domain.
*/
package logbook.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.CheckForNull;
import logbook.config.bean.AppConfigBean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
/**
* 旧設定ファイルを新設定ファイル(xml形式)に移行するクラス
*
*/
public class ConfigMigration {
/** ロガー */
private static final Logger LOG = LogManager.getLogger(ConfigMigration.class);
/** 文字コード(Shift_JIS) */
private static final Charset CHARSET = Charset.forName("MS932");
/** アプリケーション設定ファイル */
private static final File APP_CONFIG_FILE = new File("./config/internal.txt");
/** 艦娘設定ファイル */
private static final File SHIP_CONFIG_FILE = new File("./config/ship.txt");
public static void migration() {
try {
// アプリケーション設定ファイルを移行します
if (APP_CONFIG_FILE.exists()) {
// 旧設定ファイルを読み込む
Properties properties = readconfig(APP_CONFIG_FILE);
MigrationApplicationConfig config = new MigrationApplicationConfig(properties);
// 新設定ファイル
AppConfigBean bean = AppConfig.get();
// 新設定ファイルに値を設定する
bean.setListenPort(config.getListenPort());
bean.setWidth(config.getWidth());
bean.setHeight(config.getHeight());
bean.setOnTop(config.getOnTop() == SWT.ON_TOP);
bean.setMinimumLayout(config.getMinimumLayout());
bean.setSoundLevel(config.getSoundLevel());
bean.setAlpha(config.getAlpha());
bean.setReportPath(config.getReportPath());
bean.setCheckUpdate(config.getCheckUpdate());
bean.setHideWindow(config.getHideWindow());
bean.setNoticeDeckmission(config.getNoticeDeckmission());
bean.setNoticeNdock(config.getNoticeNdock());
bean.setCapturePath(config.getCapturePath());
bean.setImageFormat(config.getImageFormat());
Point location = config.getLocation();
if (location != null) {
bean.setLocationX(location.x);
bean.setLocationY(location.y);
}
bean.setStoreJson(config.getStoreJson());
bean.setStoreJsonPath(config.getStoreJsonPath());
// 新設定ファイルを保存する
AppConfig.store();
// 旧設定ファイルを削除する
APP_CONFIG_FILE.delete();
}
// 艦娘設定ファイル を削除します
if (SHIP_CONFIG_FILE.exists()) {
SHIP_CONFIG_FILE.delete();
}
} catch (Exception e) {
LOG.fatal("設定ファイルの移行に失敗しました", e);
}
}
/**
* 設定ファイルを読み込みます
*
* @param file File
* @return 設定ファイル
*/
private static Properties readconfig(File file) {
Properties properties = new Properties() {
@Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
@Override
public synchronized Enumeration<Object> elements() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
try {
if (file.exists()) {
InputStream in = new FileInputStream(file);
try {
InputStreamReader reader = new InputStreamReader(in, CHARSET);
try {
properties.load(reader);
} finally {
reader.close();
}
} finally {
in.close();
}
}
} catch (Exception e) {
LOG.fatal("設定ファイルの読み込みに失敗しました", e);
}
return properties;
}
/**
* 旧形式の設定ファイルを読み込むクラス
*
*/
private static final class MigrationApplicationConfig {
/** プロパティーファイル */
private final Properties properties;
/**
* コンストラクタ
*/
public MigrationApplicationConfig(Properties properties) {
this.properties = properties;
}
/**
* ポート番号を取得する
*
* @return ポート番号
*/
public int getListenPort() {
return Integer.parseInt(this.properties.getProperty("listen_port", "8888"));
}
/**
* ウインドウサイズ(width)を取得する
*
* @return ウインドウサイズ(width)
*/
public int getWidth() {
return Integer.parseInt(this.properties.getProperty("width", "280"));
}
/**
* ウインドウサイズ(height)を取得する
*
* @return ウインドウサイズ(height)
*/
public int getHeight() {
return Integer.parseInt(this.properties.getProperty("height", "420"));
}
/**
* 最前面に表示を取得する
*
* @return 最前面に表示
*/
public int getOnTop() {
return "1".equals(this.properties.getProperty("on_top", "1")) ? SWT.ON_TOP : SWT.NONE;
}
/**
* 縮小表示を取得する
*
* @return 縮小表示に表示
*/
public boolean getMinimumLayout() {
return "1".equals(this.properties.getProperty("minimum_layout", "0"));
}
/**
* 音量を取得する
*
* @return 音量
*/
public float getSoundLevel() {
return ((float) Integer.parseInt(this.properties.getProperty("sound_level", "85"))) / 100;
}
/**
* 透明度を取得する
*
* @return 音量
*/
public int getAlpha() {
return Integer.parseInt(this.properties.getProperty("alpha", "255"));
}
/**
* 報告書の保存先を取得する
*
* @return
*/
public String getReportPath() {
return this.properties.getProperty("report_store_path", new File("").getAbsolutePath());
}
/**
* アップデートチェックを取得する
*
* @return アップデートチェック
*/
public boolean getCheckUpdate() {
return "1".equals(this.properties.getProperty("check_update", "1"));
}
/**
* タスクトレイに格納を取得する
*
* @return タスクトレイに格納
*/
public boolean getHideWindow() {
return "1".equals(this.properties.getProperty("hide_window", "0"));
}
/**
* 遠征-1分前に通知するを取得する
*
* @return
*/
public boolean getNoticeDeckmission() {
return "1".equals(this.properties.getProperty("notice_deckmission", "1"));
}
/**
* 入渠-1分前に通知するを取得する
*
* @return
*/
public boolean getNoticeNdock() {
return "1".equals(this.properties.getProperty("notice_ndock", "1"));
}
/**
* 画面キャプチャ-保存先を取得する
*
* @return
*/
public String getCapturePath() {
return this.properties.getProperty("image_store_path", new File("").getAbsolutePath());
}
/**
* 画面キャプチャ-フォーマットを取得する
*
* @return
*/
public String getImageFormat() {
return this.properties.getProperty("image_format", "jpg");
}
/**
* ウインドウ位置を取得する
*
* @return
*/
@CheckForNull
public Point getLocation() {
String location = this.properties.getProperty("location");
if (location != null) {
String[] point = location.split(",");
int x = Integer.parseInt(point[0]);
int y = Integer.parseInt(point[1]);
return new Point(x, y);
}
return null;
}
/**
* 開発者オプション-JSONを保存するを取得する
*
* @return JSONを保存する
*/
public boolean getStoreJson() {
return "1".equals(this.properties.getProperty("store_json", "0"));
}
/**
* 開発者オプション-JSONの保存先を取得する
*
* @return JSONの保存先
*/
public String getStoreJsonPath() {
return this.properties.getProperty("store_json_path", "./json/");
}
}
}
|
main/logbook/config/ConfigMigration.java
|
/**
* No Rights Reserved.
* This program and the accompanying materials
* are made available under the terms of the Public Domain.
*/
package logbook.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.CheckForNull;
import logbook.config.bean.AppConfigBean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
/**
* 旧設定ファイルを新設定ファイル(xml形式)に移行するクラス
*
*/
public class ConfigMigration {
/** ロガー */
private static final Logger LOG = LogManager.getLogger(ConfigMigration.class);
/** 文字コード(Shift_JIS) */
private static final Charset CHARSET = Charset.forName("MS932");
/** アプリケーション設定ファイル */
private static final File APP_CONFIG_FILE = new File("./config/internal.txt");
/** 艦娘設定ファイル */
private static final File SHIP_CONFIG_FILE = new File("./config/ship.txt");
public static void migration() {
try {
// アプリケーション設定ファイルを移行します
if (APP_CONFIG_FILE.exists()) {
// 旧設定ファイルを読み込む
Properties properties = readconfig(APP_CONFIG_FILE);
MigrationApplicationConfig config = new MigrationApplicationConfig(properties);
// 新設定ファイル
AppConfigBean bean = AppConfig.get();
// 新設定ファイルに値を設定する
bean.setListenPort(config.getListenPort());
bean.setWidth(config.getWidth());
bean.setHeight(config.getHeight());
bean.setOnTop(config.getOnTop() == SWT.ON_TOP);
bean.setMinimumLayout(config.getMinimumLayout());
bean.setSoundLevel(config.getSoundLevel());
bean.setAlpha(config.getAlpha());
bean.setReportPath(config.getReportPath());
bean.setCheckUpdate(config.getCheckUpdate());
bean.setHideWindow(config.getHideWindow());
bean.setNoticeDeckmission(config.getNoticeDeckmission());
bean.setNoticeNdock(config.getNoticeNdock());
bean.setCapturePath(config.getCapturePath());
bean.setImageFormat(config.getImageFormat());
Point location = config.getLocation();
if (location != null) {
bean.setLocationX(location.x);
bean.setLocationY(location.y);
}
bean.setStoreJson(config.getStoreJson());
bean.setStoreJsonPath(config.getStoreJsonPath());
// 新設定ファイルを保存する
AppConfig.store();
// 旧設定ファイルを削除する
APP_CONFIG_FILE.delete();
}
// 艦娘設定ファイル を削除します
if (SHIP_CONFIG_FILE.exists()) {
SHIP_CONFIG_FILE.delete();
}
} catch (Exception e) {
}
}
/**
* 設定ファイルを読み込みます
*
* @param file File
* @return 設定ファイル
*/
private static Properties readconfig(File file) {
Properties properties = new Properties() {
@Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
@Override
public synchronized Enumeration<Object> elements() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
try {
if (file.exists()) {
InputStream in = new FileInputStream(file);
try {
InputStreamReader reader = new InputStreamReader(in, CHARSET);
try {
properties.load(reader);
} finally {
reader.close();
}
} finally {
in.close();
}
}
} catch (Exception e) {
LOG.fatal("設定ファイルの読み込みに失敗しました", e);
}
return properties;
}
/**
* 旧形式の設定ファイルを読み込むクラス
*
*/
private static final class MigrationApplicationConfig {
/** プロパティーファイル */
private final Properties properties;
/**
* コンストラクタ
*/
public MigrationApplicationConfig(Properties properties) {
this.properties = properties;
}
/**
* ポート番号を取得する
*
* @return ポート番号
*/
public int getListenPort() {
return Integer.parseInt(this.properties.getProperty("listen_port", "8888"));
}
/**
* ウインドウサイズ(width)を取得する
*
* @return ウインドウサイズ(width)
*/
public int getWidth() {
return Integer.parseInt(this.properties.getProperty("width", "280"));
}
/**
* ウインドウサイズ(height)を取得する
*
* @return ウインドウサイズ(height)
*/
public int getHeight() {
return Integer.parseInt(this.properties.getProperty("height", "420"));
}
/**
* 最前面に表示を取得する
*
* @return 最前面に表示
*/
public int getOnTop() {
return "1".equals(this.properties.getProperty("on_top", "1")) ? SWT.ON_TOP : SWT.NONE;
}
/**
* 縮小表示を取得する
*
* @return 縮小表示に表示
*/
public boolean getMinimumLayout() {
return "1".equals(this.properties.getProperty("minimum_layout", "0"));
}
/**
* 音量を取得する
*
* @return 音量
*/
public float getSoundLevel() {
return ((float) Integer.parseInt(this.properties.getProperty("sound_level", "85"))) / 100;
}
/**
* 透明度を取得する
*
* @return 音量
*/
public int getAlpha() {
return Integer.parseInt(this.properties.getProperty("alpha", "255"));
}
/**
* 報告書の保存先を取得する
*
* @return
*/
public String getReportPath() {
return this.properties.getProperty("report_store_path", new File("").getAbsolutePath());
}
/**
* アップデートチェックを取得する
*
* @return アップデートチェック
*/
public boolean getCheckUpdate() {
return "1".equals(this.properties.getProperty("check_update", "1"));
}
/**
* タスクトレイに格納を取得する
*
* @return タスクトレイに格納
*/
public boolean getHideWindow() {
return "1".equals(this.properties.getProperty("hide_window", "0"));
}
/**
* 遠征-1分前に通知するを取得する
*
* @return
*/
public boolean getNoticeDeckmission() {
return "1".equals(this.properties.getProperty("notice_deckmission", "1"));
}
/**
* 入渠-1分前に通知するを取得する
*
* @return
*/
public boolean getNoticeNdock() {
return "1".equals(this.properties.getProperty("notice_ndock", "1"));
}
/**
* 画面キャプチャ-保存先を取得する
*
* @return
*/
public String getCapturePath() {
return this.properties.getProperty("image_store_path", new File("").getAbsolutePath());
}
/**
* 画面キャプチャ-フォーマットを取得する
*
* @return
*/
public String getImageFormat() {
return this.properties.getProperty("image_format", "jpg");
}
/**
* ウインドウ位置を取得する
*
* @return
*/
@CheckForNull
public Point getLocation() {
String location = this.properties.getProperty("location");
if (location != null) {
String[] point = location.split(",");
int x = Integer.parseInt(point[0]);
int y = Integer.parseInt(point[1]);
return new Point(x, y);
}
return null;
}
/**
* 開発者オプション-JSONを保存するを取得する
*
* @return JSONを保存する
*/
public boolean getStoreJson() {
return "1".equals(this.properties.getProperty("store_json", "0"));
}
/**
* 開発者オプション-JSONの保存先を取得する
*
* @return JSONの保存先
*/
public String getStoreJsonPath() {
return this.properties.getProperty("store_json_path", "./json/");
}
}
}
|
git-svn-id: http://kancolle.sanaechan.net/svn/logbook/trunk/logbook@203 3035174a-c96b-47e4-9b1c-47eacedfc7e2
|
main/logbook/config/ConfigMigration.java
|
<ide><path>ain/logbook/config/ConfigMigration.java
<ide> SHIP_CONFIG_FILE.delete();
<ide> }
<ide> } catch (Exception e) {
<del>
<add> LOG.fatal("設定ファイルの移行に失敗しました", e);
<ide> }
<ide> }
<ide>
|
||
Java
|
mit
|
7217656267c08d009f75e2a18d8e6ce3fa9ef28b
| 0 |
thyrlian/ScreenshotsNanny
|
package com.basgeekball.screenshotsnanny.helper;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.Log;
import java.util.Locale;
import static com.basgeekball.screenshotsnanny.core.Constants.LOG_TAG;
public class LanguageSwitcher {
private LanguageSwitcher() {
}
public static void change(Context context, String language) {
if (context != null) {
Resources resources = context.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
configuration.locale = new Locale(language.toLowerCase());
resources.updateConfiguration(configuration, displayMetrics);
Log.i(LOG_TAG, "⚙ Language is set to: " + language.toUpperCase());
}
}
}
|
library/src/main/java/com/basgeekball/screenshotsnanny/helper/LanguageSwitcher.java
|
package com.basgeekball.screenshotsnanny.helper;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import java.util.Locale;
public class LanguageSwitcher {
private LanguageSwitcher() {
}
public static void change(Context context, String language) {
if (context != null) {
Resources resources = context.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
configuration.locale = new Locale(language.toLowerCase());
resources.updateConfiguration(configuration, displayMetrics);
}
}
}
|
Add log to LanguageSwitcher
|
library/src/main/java/com/basgeekball/screenshotsnanny/helper/LanguageSwitcher.java
|
Add log to LanguageSwitcher
|
<ide><path>ibrary/src/main/java/com/basgeekball/screenshotsnanny/helper/LanguageSwitcher.java
<ide> import android.content.res.Configuration;
<ide> import android.content.res.Resources;
<ide> import android.util.DisplayMetrics;
<add>import android.util.Log;
<ide>
<ide> import java.util.Locale;
<add>
<add>import static com.basgeekball.screenshotsnanny.core.Constants.LOG_TAG;
<ide>
<ide> public class LanguageSwitcher {
<ide>
<ide> Configuration configuration = resources.getConfiguration();
<ide> configuration.locale = new Locale(language.toLowerCase());
<ide> resources.updateConfiguration(configuration, displayMetrics);
<add> Log.i(LOG_TAG, "⚙ Language is set to: " + language.toUpperCase());
<ide> }
<ide> }
<ide>
|
|
Java
|
mit
|
13fe93a0c9bf50111b7c496f9a3d219ff9716c53
| 0 |
balazspete/multi-hop-train-journey-booking
|
package communication.protocols;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import node.company.TransactionContentGenerator;
import transaction.SudoTransactionContent;
import transaction.TransactionContent;
import transaction.TransactionCoordinator;
import transaction.TransactionCoordinator.TransactionStage;
import transaction.TransactionCoordinatorManager;
import transaction.Vault;
import transaction.WriteOnlyLock;
import communication.messages.BookingMessage;
import communication.messages.BookingReplyMessage;
import communication.messages.Message;
import data.system.NodeInfo;
import data.trainnetwork.BookableSection;
import data.trainnetwork.Seat;
import data.trainnetwork.Section;
/**
* Protocol to handle requests to pre-book seats
* @author Balazs Pete
*
*/
public class PreBookingProtocol implements Protocol {
private TransactionCoordinatorManager<String, Vault<BookableSection>, Set<Seat>> transactionCoordinators;
private Vault<Map<String, Vault<BookableSection>>> sections;
private HashSet<NodeInfo> nodes;
private WriteOnlyLock<Integer> monitor;
public PreBookingProtocol(
TransactionCoordinatorManager<String, Vault<BookableSection>, Set<Seat>> transactionCoordinators,
Vault<Map<String, Vault<BookableSection>>> sections,
HashSet<NodeInfo> nodes,
WriteOnlyLock<Integer> monitor) {
this.transactionCoordinators = transactionCoordinators;
this.sections = sections;
this.nodes = nodes;
this.monitor = monitor;
}
@Override
public String getAcceptedMessageType() {
return "BookingMessage:" + BookingMessage.Action.PREBOOK;
}
@Override
@SuppressWarnings("unchecked")
public Message processMessage(Message message) {
HashSet<Section> sections = (HashSet<Section>) message.getContents();
SudoTransactionContent<String, Vault<BookableSection>, Set<Seat>> content
= TransactionContentGenerator.getSeatPreBookingContent(sections);
TransactionCoordinator<String, Vault<BookableSection>, Set<Seat>> coordinator
= new TransactionCoordinator<String, Vault<BookableSection>, Set<Seat>>(content, this.sections, nodes, monitor);
transactionCoordinators.put(coordinator.getTransactionId(), coordinator);
TransactionStage stage;
// No need to wait for TransactionStatus.DONE, it's okay to reply when the transaction is in COMMIT or ABORT stage
while ((stage = coordinator.getStage()) == TransactionStage.COMMIT || stage == TransactionStage.ABORT) {
try {
// Wait until notified or timed out
System.out.println("gonna wait for transaction end");
coordinator.wait(5000);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
HashSet<Seat> returnedData = new HashSet<Seat>(content.getReturnedData());
BookingReplyMessage reply = new BookingReplyMessage();
reply.setContents(returnedData);
System.out.println("content: " + returnedData);
return reply;
}
@Override
public boolean hasReply() {
return true;
}
}
|
src/communication/protocols/PreBookingProtocol.java
|
package communication.protocols;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import node.company.TransactionContentGenerator;
import transaction.SudoTransactionContent;
import transaction.TransactionContent;
import transaction.TransactionCoordinator;
import transaction.TransactionCoordinator.TransactionStage;
import transaction.TransactionCoordinatorManager;
import transaction.Vault;
import transaction.WriteOnlyLock;
import communication.messages.BookingMessage;
import communication.messages.Message;
import data.system.NodeInfo;
import data.trainnetwork.BookableSection;
import data.trainnetwork.Seat;
import data.trainnetwork.Section;
/**
* Protocol to handle requests to pre-book seats
* @author Balazs Pete
*
*/
public class PreBookingProtocol implements Protocol {
private TransactionCoordinatorManager<String, Vault<BookableSection>, Set<Seat>> transactionCoordinators;
private Vault<Map<String, Vault<BookableSection>>> sections;
private HashSet<NodeInfo> nodes;
private WriteOnlyLock<Integer> monitor;
public PreBookingProtocol(
TransactionCoordinatorManager<String, Vault<BookableSection>, Set<Seat>> transactionCoordinators,
Vault<Map<String, Vault<BookableSection>>> sections,
HashSet<NodeInfo> nodes,
WriteOnlyLock<Integer> monitor) {
this.transactionCoordinators = transactionCoordinators;
this.sections = sections;
this.nodes = nodes;
this.monitor = monitor;
}
@Override
public String getAcceptedMessageType() {
return "BookingMessage:" + BookingMessage.Action.PREBOOK;
}
@Override
@SuppressWarnings("unchecked")
public Message processMessage(Message message) {
// TODO Auto-generated method stub
HashSet<Section> sections = (HashSet<Section>) message.getContents();
SudoTransactionContent<String, Vault<BookableSection>, Set<Seat>> content = TransactionContentGenerator.getSeatPreBookingContent(sections);
TransactionCoordinator<String, Vault<BookableSection>, Set<Seat>> coordinator
= new TransactionCoordinator<String, Vault<BookableSection>, Set<Seat>>(content, this.sections, nodes, monitor);
transactionCoordinators.put(coordinator.getTransactionId(), coordinator);
TransactionStage stage;
// No need to wait for TransactionStatus.DONE, it's okay to reply when the transaction is in COMMIT or ABORT stage
while ((stage = coordinator.getStage()) == TransactionStage.COMMIT || stage == TransactionStage.ABORT) {
try {
// Wait until notified or timed out
coordinator.wait(5000);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
return null;
}
@Override
public boolean hasReply() {
return true;
}
}
|
Add reply and some debugging statements to ReBookingProtocol
|
src/communication/protocols/PreBookingProtocol.java
|
Add reply and some debugging statements to ReBookingProtocol
|
<ide><path>rc/communication/protocols/PreBookingProtocol.java
<ide> import transaction.Vault;
<ide> import transaction.WriteOnlyLock;
<ide> import communication.messages.BookingMessage;
<add>import communication.messages.BookingReplyMessage;
<ide> import communication.messages.Message;
<ide> import data.system.NodeInfo;
<ide> import data.trainnetwork.BookableSection;
<ide> @Override
<ide> @SuppressWarnings("unchecked")
<ide> public Message processMessage(Message message) {
<del> // TODO Auto-generated method stub
<del>
<ide> HashSet<Section> sections = (HashSet<Section>) message.getContents();
<del> SudoTransactionContent<String, Vault<BookableSection>, Set<Seat>> content = TransactionContentGenerator.getSeatPreBookingContent(sections);
<add> SudoTransactionContent<String, Vault<BookableSection>, Set<Seat>> content
<add> = TransactionContentGenerator.getSeatPreBookingContent(sections);
<ide> TransactionCoordinator<String, Vault<BookableSection>, Set<Seat>> coordinator
<ide> = new TransactionCoordinator<String, Vault<BookableSection>, Set<Seat>>(content, this.sections, nodes, monitor);
<ide>
<ide> while ((stage = coordinator.getStage()) == TransactionStage.COMMIT || stage == TransactionStage.ABORT) {
<ide> try {
<ide> // Wait until notified or timed out
<add> System.out.println("gonna wait for transaction end");
<ide> coordinator.wait(5000);
<ide> } catch (InterruptedException e) {
<ide> System.err.println(e.getMessage());
<ide> }
<ide> }
<ide>
<del> return null;
<add> HashSet<Seat> returnedData = new HashSet<Seat>(content.getReturnedData());
<add> BookingReplyMessage reply = new BookingReplyMessage();
<add> reply.setContents(returnedData);
<add>
<add> System.out.println("content: " + returnedData);
<add>
<add> return reply;
<ide> }
<ide>
<ide> @Override
|
|
JavaScript
|
mit
|
8cc4b8772f5fa496d9885d648d34faf185c65c1d
| 0 |
chrisgame/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,esbanarango/ember-power-select,Dremora/ember-power-select,esbanarango/ember-power-select,Dremora/ember-power-select,cibernox/ember-power-select,cibernox/ember-power-select,cibernox/ember-power-select
|
import Ember from 'ember';
function generatePromise() {
return new Ember.RSVP.Promise((resolve) => {
setTimeout(() => resolve(['one', 'two', 'three']), 5000);
});
}
export default Ember.Controller.extend({
names: ['Stefan', 'Miguel', 'Tomster', 'Pluto'],
emptyList: [],
promise: null,
actions: {
refreshCollection() {
this.set('promise', generatePromise());
}
}
});
|
tests/dummy/app/controllers/docs/the-list.js
|
import Ember from 'ember';
function generatePromise() {
return new Ember.RSVP.Promise((resolve) => {
setTimeout(() => resolve(['one', 'two', 'three']), 5000);
});
};
export default Ember.Controller.extend({
names: ['Stefan', 'Miguel', 'Tomster', 'Pluto'],
emptyList: [],
promise: null,
actions: {
refreshCollection() {
this.set('promise', generatePromise());
}
}
});
|
Fix jshint
|
tests/dummy/app/controllers/docs/the-list.js
|
Fix jshint
|
<ide><path>ests/dummy/app/controllers/docs/the-list.js
<ide> return new Ember.RSVP.Promise((resolve) => {
<ide> setTimeout(() => resolve(['one', 'two', 'three']), 5000);
<ide> });
<del>};
<add>}
<ide>
<ide> export default Ember.Controller.extend({
<ide> names: ['Stefan', 'Miguel', 'Tomster', 'Pluto'],
|
|
Java
|
apache-2.0
|
8c81e56ba30ad536d6d29214cf9948f7297b4d4c
| 0 |
joinAero/AndroidWebServ,joinAero/AndroidWebServ
|
package net.asfun.jangod.lib.tag;
import java.util.HashMap;
import java.util.Map;
import net.asfun.jangod.base.Context;
import net.asfun.jangod.interpret.InterpretException;
import net.asfun.jangod.interpret.JangodInterpreter;
import net.asfun.jangod.lib.TagLibrary;
import net.asfun.jangod.parse.TokenParser;
import android.app.Instrumentation;
import android.test.InstrumentationTestCase;
import android.util.Log;
public class TagTest extends InstrumentationTestCase {
static final String TAG = "TagTest";
Instrumentation mInstru;
JangodInterpreter interpreter;
@Override
protected void setUp() throws Exception {
mInstru = getInstrumentation();
Map<String, Object> data = new HashMap<String, Object>();
data.put("var1", "app_name");
data.put("var2", "result_view");
Context context = new Context();
context.initBindings(data, Context.SCOPE_GLOBAL);
interpreter = new JangodInterpreter(context);
}
public void testResStrTag() throws Exception {
Log.e(TAG, "testResStrTag");
mInstru.runOnMainSync(new Runnable() {
@Override
public void run() {
TagLibrary.addTag(new ResStrTag());
String script = "{% rstr var1 %} is {% rstr 'app_name' %}";
try {
assertEquals("WebServ is WebServ", eval(script));
} catch (InterpretException e) {
}
}
});
}
public void testResColorTag() throws Exception {
Log.e(TAG, "testResColorTag");
mInstru.runOnMainSync(new Runnable() {
@Override
public void run() {
TagLibrary.addTag(new ResColorTag());
String script = "{% rcolor var2 %} or {% rcolor 'result_view' %}";
try {
Log.e(TAG, eval(script));
assertEquals("#b0000000 or #b0000000", eval(script));
} catch (InterpretException e) {
}
}
});
}
public void testUUIDTag() throws Exception {
Log.e(TAG, "testUUIDTag");
TagLibrary.addTag(new UUIDTag());
String script = "{% uuid %} or {% uuid %}";
Log.e(TAG, eval(script));
}
private String eval(String script) throws InterpretException {
TokenParser parser = new TokenParser(script);
try {
return interpreter.render(parser);
} catch (InterpretException e) {
throw e;
}
}
@Override
protected void tearDown() throws Exception {
interpreter = null;
}
}
|
src/test/net/asfun/jangod/lib/tag/TagTest.java
|
package net.asfun.jangod.lib.tag;
import java.util.HashMap;
import java.util.Map;
import net.asfun.jangod.base.Context;
import net.asfun.jangod.interpret.InterpretException;
import net.asfun.jangod.interpret.JangodInterpreter;
import net.asfun.jangod.lib.TagLibrary;
import net.asfun.jangod.parse.TokenParser;
import android.test.AndroidTestCase;
import android.util.Log;
public class TagTest extends AndroidTestCase {
static final String TAG = "TagTest";
JangodInterpreter interpreter;
@Override
protected void setUp() throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
data.put("var1", "app_name");
data.put("var2", "bg");
Context context = new Context();
context.initBindings(data, Context.SCOPE_GLOBAL);
interpreter = new JangodInterpreter(context);
}
public void testResStrTag() throws Exception {
Log.e(TAG, "testResStrTag");
TagLibrary.addTag(new ResStrTag());
String script = "{% rstr var1 %} is {% rstr 'app_name' %}";
assertEquals("WifiShare is WifiShare", eval(script));
}
public void testResColorTag() throws Exception {
Log.e(TAG, "testResColorTag");
TagLibrary.addTag(new ResColorTag());
String script = "{% rcolor var2 %} or {% rcolor 'bg' %}";
Log.e(TAG, eval(script));
assertEquals("#fffffbde or #fffffbde", eval(script));
}
public void testUUIDTag() throws Exception {
Log.e(TAG, "testUUIDTag");
TagLibrary.addTag(new UUIDTag());
String script = "{% uuid %} or {% uuid %}";
Log.e(TAG, eval(script));
}
private String eval(String script) throws InterpretException {
TokenParser parser = new TokenParser(script);
try {
return interpreter.render(parser);
} catch (InterpretException e) {
throw e;
}
}
@Override
protected void tearDown() throws Exception {
interpreter = null;
}
}
|
fix the old tag test
|
src/test/net/asfun/jangod/lib/tag/TagTest.java
|
fix the old tag test
|
<ide><path>rc/test/net/asfun/jangod/lib/tag/TagTest.java
<ide> import net.asfun.jangod.interpret.JangodInterpreter;
<ide> import net.asfun.jangod.lib.TagLibrary;
<ide> import net.asfun.jangod.parse.TokenParser;
<del>import android.test.AndroidTestCase;
<add>import android.app.Instrumentation;
<add>import android.test.InstrumentationTestCase;
<ide> import android.util.Log;
<ide>
<del>public class TagTest extends AndroidTestCase {
<add>public class TagTest extends InstrumentationTestCase {
<ide>
<ide> static final String TAG = "TagTest";
<add>
<add> Instrumentation mInstru;
<ide>
<ide> JangodInterpreter interpreter;
<ide>
<ide> @Override
<ide> protected void setUp() throws Exception {
<add> mInstru = getInstrumentation();
<ide>
<ide> Map<String, Object> data = new HashMap<String, Object>();
<ide> data.put("var1", "app_name");
<del> data.put("var2", "bg");
<add> data.put("var2", "result_view");
<ide>
<ide> Context context = new Context();
<ide> context.initBindings(data, Context.SCOPE_GLOBAL);
<ide>
<ide> public void testResStrTag() throws Exception {
<ide> Log.e(TAG, "testResStrTag");
<del> TagLibrary.addTag(new ResStrTag());
<del> String script = "{% rstr var1 %} is {% rstr 'app_name' %}";
<del> assertEquals("WifiShare is WifiShare", eval(script));
<add> mInstru.runOnMainSync(new Runnable() {
<add> @Override
<add> public void run() {
<add> TagLibrary.addTag(new ResStrTag());
<add> String script = "{% rstr var1 %} is {% rstr 'app_name' %}";
<add> try {
<add> assertEquals("WebServ is WebServ", eval(script));
<add> } catch (InterpretException e) {
<add> }
<add> }
<add> });
<ide> }
<ide>
<ide> public void testResColorTag() throws Exception {
<ide> Log.e(TAG, "testResColorTag");
<del> TagLibrary.addTag(new ResColorTag());
<del> String script = "{% rcolor var2 %} or {% rcolor 'bg' %}";
<del> Log.e(TAG, eval(script));
<del> assertEquals("#fffffbde or #fffffbde", eval(script));
<add> mInstru.runOnMainSync(new Runnable() {
<add> @Override
<add> public void run() {
<add> TagLibrary.addTag(new ResColorTag());
<add> String script = "{% rcolor var2 %} or {% rcolor 'result_view' %}";
<add> try {
<add> Log.e(TAG, eval(script));
<add> assertEquals("#b0000000 or #b0000000", eval(script));
<add> } catch (InterpretException e) {
<add> }
<add> }
<add> });
<ide> }
<ide>
<ide> public void testUUIDTag() throws Exception {
|
|
Java
|
apache-2.0
|
e4027195cf5a41121f0ad77f0e926e3cfa235f7c
| 0 |
mglukhikh/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,caot/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,kdwink/intellij-community,samthor/intellij-community,izonder/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,caot/intellij-community,ernestp/consulo,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,amith01994/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,slisson/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,holmes/intellij-community,fnouama/intellij-community,allotria/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,allotria/intellij-community,izonder/intellij-community,consulo/consulo,kool79/intellij-community,TangHao1987/intellij-community,signed/intellij-community,Distrotech/intellij-community,signed/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,petteyg/intellij-community,apixandru/intellij-community,xfournet/intellij-community,slisson/intellij-community,semonte/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,adedayo/intellij-community,slisson/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,izonder/intellij-community,Distrotech/intellij-community,holmes/intellij-community,kool79/intellij-community,asedunov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ernestp/consulo,ahb0327/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,holmes/intellij-community,signed/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ernestp/consulo,clumsy/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,signed/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,samthor/intellij-community,fnouama/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,signed/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,izonder/intellij-community,samthor/intellij-community,clumsy/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,diorcety/intellij-community,caot/intellij-community,slisson/intellij-community,supersven/intellij-community,ibinti/intellij-community,FHannes/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,blademainer/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,clumsy/intellij-community,kdwink/intellij-community,holmes/intellij-community,supersven/intellij-community,fnouama/intellij-community,adedayo/intellij-community,xfournet/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,caot/intellij-community,semonte/intellij-community,semonte/intellij-community,caot/intellij-community,asedunov/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ernestp/consulo,semonte/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,signed/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,samthor/intellij-community,caot/intellij-community,ftomassetti/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,holmes/intellij-community,slisson/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,apixandru/intellij-community,apixandru/intellij-community,blademainer/intellij-community,samthor/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,kool79/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ahb0327/intellij-community,allotria/intellij-community,izonder/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,allotria/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,izonder/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,caot/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,samthor/intellij-community,petteyg/intellij-community,retomerz/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,retomerz/intellij-community,slisson/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,dslomov/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,fitermay/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,blademainer/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,petteyg/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,samthor/intellij-community,kool79/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vladmm/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,caot/intellij-community,signed/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,semonte/intellij-community,jagguli/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,gnuhub/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,samthor/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,supersven/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,blademainer/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,da1z/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,jagguli/intellij-community,consulo/consulo,izonder/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,retomerz/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,vladmm/intellij-community,jagguli/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fitermay/intellij-community,supersven/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,FHannes/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,consulo/consulo,holmes/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,xfournet/intellij-community,fnouama/intellij-community,semonte/intellij-community,kool79/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,kool79/intellij-community,semonte/intellij-community,slisson/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ernestp/consulo,fnouama/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,holmes/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,semonte/intellij-community,da1z/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,asedunov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,consulo/consulo,ibinti/intellij-community,wreckJ/intellij-community,caot/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,kool79/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ibinti/intellij-community,apixandru/intellij-community,signed/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,caot/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,xfournet/intellij-community,signed/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,signed/intellij-community,consulo/consulo,hurricup/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,izonder/intellij-community,allotria/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,FHannes/intellij-community,retomerz/intellij-community,FHannes/intellij-community,clumsy/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,apixandru/intellij-community,adedayo/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,da1z/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,consulo/consulo,holmes/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,fnouama/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,hurricup/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,allotria/intellij-community,semonte/intellij-community,allotria/intellij-community,akosyakov/intellij-community,kool79/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,FHannes/intellij-community,hurricup/intellij-community,robovm/robovm-studio
|
package org.jetbrains.io;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.*;
import org.jetbrains.annotations.NotNull;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.Executor;
import static org.jboss.netty.channel.Channels.pipeline;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class WebServer {
private final NioServerSocketChannelFactory channelFactory;
private final List<ChannelFutureListener> closingListeners = ContainerUtil.createEmptyCOWList();
private final ChannelGroup openChannels = new DefaultChannelGroup("web-server");
private static final Logger LOG = Logger.getInstance(WebServer.class);
public WebServer() {
final Application application = ApplicationManager.getApplication();
final Executor pooledThreadExecutor = new Executor() {
@Override
public void execute(@NotNull Runnable command) {
application.executeOnPooledThread(command);
}
};
channelFactory = new NioServerSocketChannelFactory(pooledThreadExecutor, pooledThreadExecutor, 2);
}
public boolean isRunning() {
return !openChannels.isEmpty();
}
public void start(int port, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, int portsCount, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, portsCount, false, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
start(port, 1, false, pipelineConsumers);
}
public int start(int firstPort, int portsCount, boolean tryAnyPort, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
if (isRunning()) {
throw new IllegalStateException("server already started");
}
ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setPipelineFactory(new ChannelPipelineFactoryImpl(pipelineConsumers, new DefaultHandler(openChannels)));
return bind(firstPort, portsCount, tryAnyPort, bootstrap);
}
// IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
// but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports and any request to us will be intercepted
// so, we bind to 127.0.0.1 and 0.0.0.0
private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
for (int i = 0; i < portsCount; i++) {
int port = firstPort + i;
try {
openChannels.add(bootstrap.bind(new InetSocketAddress(port)));
if (!SystemInfo.isLinux) {
openChannels.add(bootstrap.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port)));
}
return port;
}
catch (ChannelException e) {
if (!openChannels.isEmpty()) {
openChannels.close();
openChannels.clear();
}
if (portsCount == 1) {
throw e;
}
else if (!tryAnyPort && i == (portsCount - 1)) {
LOG.error(e);
}
}
catch (UnknownHostException e) {
LOG.error(e);
}
}
if (tryAnyPort) {
try {
Channel channel = bootstrap.bind(new InetSocketAddress(0));
openChannels.add(channel);
return ((InetSocketAddress)channel.getLocalAddress()).getPort();
}
catch (ChannelException e) {
LOG.error(e);
}
}
return -1;
}
public void stop() {
try {
for (ChannelFutureListener listener : closingListeners) {
try {
listener.operationComplete(null);
}
catch (Exception e) {
LOG.error(e);
}
}
}
finally {
try {
openChannels.close().awaitUninterruptibly();
}
finally {
channelFactory.releaseExternalResources();
}
}
}
public void addClosingListener(ChannelFutureListener listener) {
closingListeners.add(listener);
}
public Runnable createShutdownTask() {
return new Runnable() {
@Override
public void run() {
if (isRunning()) {
stop();
}
}
};
}
public void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(createShutdownTask()));
}
public static void removePluggableHandlers(ChannelPipeline pipeline) {
for (String name : pipeline.getNames()) {
if (name.startsWith("pluggable_")) {
pipeline.remove(name);
}
}
}
private static class ChannelPipelineFactoryImpl implements ChannelPipelineFactory {
private final Computable<Consumer<ChannelPipeline>[]> pipelineConsumers;
private final DefaultHandler defaultHandler;
public ChannelPipelineFactoryImpl(Computable<Consumer<ChannelPipeline>[]> pipelineConsumers, DefaultHandler defaultHandler) {
this.pipelineConsumers = pipelineConsumers;
this.defaultHandler = defaultHandler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline(new HttpRequestDecoder(), new HttpChunkAggregator(1048576), new HttpResponseEncoder());
for (Consumer<ChannelPipeline> consumer : pipelineConsumers.compute()) {
try {
consumer.consume(pipeline);
}
catch (Throwable e) {
LOG.error(e);
}
}
pipeline.addLast("defaultHandler", defaultHandler);
return pipeline;
}
}
@ChannelHandler.Sharable
private static class DefaultHandler extends SimpleChannelUpstreamHandler {
private final ChannelGroup openChannels;
public DefaultHandler(ChannelGroup openChannels) {
this.openChannels = openChannels;
}
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent e) {
openChannels.add(e.getChannel());
}
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception {
if (e.getMessage() instanceof HttpRequest) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
}
}
}
|
platform/platform-impl/src/org/jetbrains/io/WebServer.java
|
package org.jetbrains.io;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.Executor;
import static org.jboss.netty.channel.Channels.pipeline;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class WebServer {
private final NioServerSocketChannelFactory channelFactory;
private final List<ChannelFutureListener> closingListeners = ContainerUtil.createEmptyCOWList();
private final ChannelGroup openChannels = new DefaultChannelGroup("web-server");
private static final Logger LOG = Logger.getInstance(WebServer.class);
public WebServer() {
final Application application = ApplicationManager.getApplication();
final Executor pooledThreadExecutor = new Executor() {
@Override
public void execute(Runnable command) {
application.executeOnPooledThread(command);
}
};
channelFactory = new NioServerSocketChannelFactory(pooledThreadExecutor, pooledThreadExecutor, 2);
}
public boolean isRunning() {
return !openChannels.isEmpty();
}
public void start(int port, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, int portsCount, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, portsCount, false, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
start(port, 1, false, pipelineConsumers);
}
public int start(int firstPort, int portsCount, boolean tryAnyPort, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
if (isRunning()) {
throw new IllegalStateException("server already started");
}
ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setPipelineFactory(new ChannelPipelineFactoryImpl(pipelineConsumers, new DefaultHandler(openChannels)));
return bind(firstPort, portsCount, tryAnyPort, bootstrap);
}
// IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
// but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports and any request to us will be intercepted
// so, we bind to 127.0.0.1 and 0.0.0.0
private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
for (int i = 0; i < portsCount; i++) {
int port = firstPort + i;
try {
openChannels.add(bootstrap.bind(new InetSocketAddress(port)));
if (!SystemInfo.isLinux) {
openChannels.add(bootstrap.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port)));
}
return port;
}
catch (ChannelException e) {
if (!openChannels.isEmpty()) {
openChannels.close();
openChannels.clear();
}
if (portsCount == 1) {
throw e;
}
else if (!tryAnyPort && i == (portsCount - 1)) {
LOG.error(e);
}
}
catch (UnknownHostException e) {
LOG.error(e);
}
}
if (tryAnyPort) {
try {
Channel channel = bootstrap.bind(new InetSocketAddress(0));
openChannels.add(channel);
return ((InetSocketAddress)channel.getLocalAddress()).getPort();
}
catch (ChannelException e) {
LOG.error(e);
}
}
return -1;
}
public void stop() {
try {
for (ChannelFutureListener listener : closingListeners) {
try {
listener.operationComplete(null);
}
catch (Exception e) {
LOG.error(e);
}
}
}
finally {
try {
openChannels.close().awaitUninterruptibly();
}
finally {
channelFactory.releaseExternalResources();
}
}
}
public void addClosingListener(ChannelFutureListener listener) {
closingListeners.add(listener);
}
public Runnable createShutdownTask() {
return new Runnable() {
@Override
public void run() {
if (isRunning()) {
stop();
}
}
};
}
public void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(createShutdownTask()));
}
public static void removePluggableHandlers(ChannelPipeline pipeline) {
for (String name : pipeline.getNames()) {
if (name.startsWith("pluggable_")) {
pipeline.remove(name);
}
}
}
private static class ChannelPipelineFactoryImpl implements ChannelPipelineFactory {
private final Computable<Consumer<ChannelPipeline>[]> pipelineConsumers;
private final DefaultHandler defaultHandler;
public ChannelPipelineFactoryImpl(Computable<Consumer<ChannelPipeline>[]> pipelineConsumers, DefaultHandler defaultHandler) {
this.pipelineConsumers = pipelineConsumers;
this.defaultHandler = defaultHandler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline(new HttpRequestDecoder(), new HttpChunkAggregator(1048576), new HttpResponseEncoder());
for (Consumer<ChannelPipeline> consumer : pipelineConsumers.compute()) {
try {
consumer.consume(pipeline);
}
catch (Throwable e) {
LOG.error(e);
}
}
pipeline.addLast("defaultHandler", defaultHandler);
return pipeline;
}
}
@ChannelHandler.Sharable
private static class DefaultHandler extends SimpleChannelUpstreamHandler {
private final ChannelGroup openChannels;
public DefaultHandler(ChannelGroup openChannels) {
this.openChannels = openChannels;
}
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent e) {
openChannels.add(e.getChannel());
}
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception {
if (e.getMessage() instanceof HttpRequest) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
}
}
}
|
nullability
|
platform/platform-impl/src/org/jetbrains/io/WebServer.java
|
nullability
|
<ide><path>latform/platform-impl/src/org/jetbrains/io/WebServer.java
<ide> import org.jboss.netty.channel.group.DefaultChannelGroup;
<ide> import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
<ide> import org.jboss.netty.handler.codec.http.*;
<add>import org.jetbrains.annotations.NotNull;
<ide>
<ide> import java.net.InetAddress;
<ide> import java.net.InetSocketAddress;
<ide> final Application application = ApplicationManager.getApplication();
<ide> final Executor pooledThreadExecutor = new Executor() {
<ide> @Override
<del> public void execute(Runnable command) {
<add> public void execute(@NotNull Runnable command) {
<ide> application.executeOnPooledThread(command);
<ide> }
<ide> };
|
|
JavaScript
|
mit
|
d29c98f6d0f85203fb079d5f729f9d88148be6d6
| 0 |
Clarifai/lambdafai
|
var _ = require('lodash');
var async = require('async');
var aws = require('aws-sdk');
var callbacks = require('./callbacks');
var glob = require('glob');
var fs = require('fs');
var JSZip = new require('jszip');
var path = require('path');
var utils = require('../internal/utils');
var MB = 1024 * 1024;
// Files to ignore when packing up the Lambda zipfile.
var IGNORE_PATTERNS = [
'build/**', // Ignore build artifacts
'spec/**', // Ignore tests
'test/**', // Ignore tests
'node_modules/gulp*/**', // Ignore build system
'node_modules/aws-sdk/**', // Automatically available on Lambda
];
// File containing the Lambda handler.
var ENTRY_POINT_FILE = '../bootstrap/lambdafai-entry-point.js';
var LambdaDeployer = function(app) {
this.lambda = new aws.Lambda();
this.iam = new aws.IAM();
this.app = app;
};
LambdaDeployer.prototype.deploy = function(environment, lambdaName, callback) {
var self = this;
var lambdasToDeploy = self.app.lambdas.filter(function(x) {
return !lambdaName || x.name == lambdaName;
});
console.log('Found ' + lambdasToDeploy.length + ' lambdas to deploy');
var zipFile = buildZipFile();
async.eachSeries(lambdasToDeploy, function(lambda, next) {
self._deployLambda(zipFile, lambda, environment, next);
}, callback);
};
LambdaDeployer.prototype.promote = function(sourceEnv, targetEnv, callback) {
var self = this;
async.waterfall([
function collectFromVersions(next) {
self._collectVersions(sourceEnv, false, function(err, versions) {
self.newVersions = versions;
next(err);
});
},
function collectToVersions(next) {
self._collectVersions(targetEnv, true, function(err, versions) {
self.oldVersions = versions;
next(err);
});
},
function diff(next) {
self._computeDiff();
next();
},
function apply(next) {
if (self.diff.length > 0) {
console.log('\nApplying changes to environment: ' + targetEnv);
} else {
console.log('\nNo changes necessary.');
}
async.eachSeries(self.diff, function(entry, cb) {
self._updateAlias(targetEnv, entry, cb);
}, next);
},
], callbacks.stripData(callback));
};
// Deployment:
LambdaDeployer.prototype._deployLambda = function(zipFile, lambda, environment, callback) {
var self = this;
var functionName = self.app.name + '-' + lambda.name;
utils.logBanner();
console.log('Deploying "' + functionName + '" to environment "' + environment + '"');
var description = 'Lambdafai ' + new Date().toDateString();
var version;
async.waterfall([
function upload(next) {
console.log('Uploading to ' + functionName + ' Lambda function');
self.lambda.updateFunctionCode({
FunctionName: functionName,
ZipFile: zipFile,
Publish: true,
}, next);
},
function createAlias(info, next) {
version = info.Version;
console.log('Published version ' + version + '. Mapping alias "' + environment + '"');
self.lambda.createAlias({
FunctionName: functionName,
FunctionVersion: version,
Name: environment,
Description: description,
}, callbacks.ignoreErrors('*', next));
},
function updateAlias(info, next) {
self.lambda.updateAlias({
FunctionName: functionName,
Name: environment,
Description: description,
FunctionVersion: version,
}, next);
},
], callback);
};
function buildZipFile() {
// Add paths to the zip file:
var paths = glob.sync('**', { ignore: IGNORE_PATTERNS });
var zip = new JSZip();
var numFiles = 0;
_.forEach(paths, function(path) {
if (fs.lstatSync(path).isDirectory()) {
zip.folder(path);
} else {
zip.file(path, fs.readFileSync(path));
numFiles++;
}
});
// Figure out the path of the currently running script. We will require this script when running
// on Lambda to configure the app.
var indexPath = path.relative(process.cwd(), process.argv[1]);
var entry = fs.readFileSync(path.join(__dirname, ENTRY_POINT_FILE), 'utf8');
entry = entry.replace('$INDEX', indexPath);
zip.file(path.basename(ENTRY_POINT_FILE), new Buffer(entry, 'utf8'));
// Generate the zipfile.
var zipFile = zip.generate({
type: 'nodebuffer',
compression: 'DEFLATE',
});
console.log('Zipped ' + numFiles + ' files, ' + (zipFile.length / MB).toFixed(2) + ' MB');
return zipFile;
}
// Promotion:
LambdaDeployer.prototype._collectVersions = function(environment, allowMissing, callback) {
var self = this;
var versions = {};
async.eachSeries(self.app.lambdas, function(lambda, next) {
var functionName = self.app.name + '-' + lambda.name;
self.lambda.getAlias({ FunctionName: functionName, Name: environment }, function(err, alias) {
if (alias) {
versions[functionName] = alias.FunctionVersion;
} else if (err && err.code == 'ResourceNotFoundException') {
console.log('Alias not found: ' + environment);
if (allowMissing) {
versions[functionName] = 0;
err = null;
}
}
next(err);
});
}, function(err) {
callback(err, versions);
});
};
LambdaDeployer.prototype._computeDiff = function() {
var self = this;
self.diff = [];
_.forEach(self.app.lambdas, function(lambda) {
var name = self.app.name + '-' + lambda.name;
var oldVersion = self.oldVersions[name] || 0;
var newVersion = self.newVersions[name];
if (oldVersion !== newVersion) {
self.diff.push({ name: name, oldVersion: oldVersion, newVersion: newVersion });
}
});
};
LambdaDeployer.prototype._updateAlias = function(alias, diff, callback) {
if (diff.oldVersion === 0) {
console.log(' ' + diff.name + ': Create alias "' + alias + '" for version ' + diff.newVersion);
this.lambda.createAlias({
FunctionName: diff.name,
Name: alias,
FunctionVersion: diff.newVersion,
}, callback);
} else {
console.log(' ' + diff.name + ': Update alias "' + alias + '" for version ' + diff.newVersion);
this.lambda.updateAlias({
FunctionName: diff.name,
Name: alias,
FunctionVersion: diff.newVersion,
}, callback);
}
};
module.exports = LambdaDeployer;
|
lib/internal/lambda-deployer.js
|
var _ = require('lodash');
var async = require('async');
var aws = require('aws-sdk');
var callbacks = require('./callbacks');
var glob = require('glob');
var fs = require('fs');
var JSZip = new require('jszip');
var path = require('path');
var utils = require('../internal/utils');
var MB = 1024 * 1024;
// Files to ignore when packing up the Lambda zipfile.
var IGNORE_PATTERNS = [
'build/**', // Ignore build artifacts
'spec/**', // Ignore tests
'test/**', // Ignore tests
'node_modules/gulp*/**', // Ignore build system
'node_modules/aws-sdk/**', // Automatically available on Lambda
];
// File containing the Lambda handler.
var ENTRY_POINT_FILE = '../bootstrap/lambdafai-entry-point.js';
var LambdaDeployer = function(app) {
this.lambda = new aws.Lambda();
this.iam = new aws.IAM();
this.app = app;
};
LambdaDeployer.prototype.deploy = function(environment, lambdaName, callback) {
var self = this;
var lambdasToDeploy = self.app.lambdas.filter(function(x) {
return !lambdaName || x.name == lambdaName;
});
console.log('Found ' + lambdasToDeploy.length + ' lambdas to deploy');
async.eachSeries(lambdasToDeploy, function(lambda, next) {
self._deployLambda(lambda, environment, next);
}, callback);
};
LambdaDeployer.prototype.promote = function(sourceEnv, targetEnv, callback) {
var self = this;
async.waterfall([
function collectFromVersions(next) {
self._collectVersions(sourceEnv, false, function(err, versions) {
self.newVersions = versions;
next(err);
});
},
function collectToVersions(next) {
self._collectVersions(targetEnv, true, function(err, versions) {
self.oldVersions = versions;
next(err);
});
},
function diff(next) {
self._computeDiff();
next();
},
function apply(next) {
if (self.diff.length > 0) {
console.log('\nApplying changes to environment: ' + targetEnv);
} else {
console.log('\nNo changes necessary.');
}
async.eachSeries(self.diff, function(entry, cb) {
self._updateAlias(targetEnv, entry, cb);
}, next);
},
], callbacks.stripData(callback));
};
// Deployment:
LambdaDeployer.prototype._deployLambda = function(lambda, environment, callback) {
var self = this;
var functionName = self.app.name + '-' + lambda.name;
utils.logBanner();
console.log('Deploying "' + functionName + '" to environment "' + environment + '"');
var description = 'Lambdafai ' + new Date().toDateString();
var zipFile = buildZipFile();
var version;
async.waterfall([
function upload(next) {
console.log('Uploading to ' + functionName + ' Lambda function');
self.lambda.updateFunctionCode({
FunctionName: functionName,
ZipFile: zipFile,
Publish: true,
}, next);
},
function createAlias(info, next) {
version = info.Version;
console.log('Published version ' + version + '. Mapping alias "' + environment + '"');
self.lambda.createAlias({
FunctionName: functionName,
FunctionVersion: version,
Name: environment,
Description: description,
}, callbacks.ignoreErrors('*', next));
},
function updateAlias(info, next) {
self.lambda.updateAlias({
FunctionName: functionName,
Name: environment,
Description: description,
FunctionVersion: version,
}, next);
},
], callback);
};
function buildZipFile() {
// Add paths to the zip file:
var paths = glob.sync('**', { ignore: IGNORE_PATTERNS });
var zip = new JSZip();
var numFiles = 0;
_.forEach(paths, function(path) {
if (fs.lstatSync(path).isDirectory()) {
zip.folder(path);
} else {
zip.file(path, fs.readFileSync(path));
numFiles++;
}
});
// Figure out the path of the currently running script. We will require this script when running
// on Lambda to configure the app.
var indexPath = path.relative(process.cwd(), process.argv[1]);
var entry = fs.readFileSync(path.join(__dirname, ENTRY_POINT_FILE), 'utf8');
entry = entry.replace('$INDEX', indexPath);
zip.file(path.basename(ENTRY_POINT_FILE), new Buffer(entry, 'utf8'));
// Generate the zipfile.
var zipFile = zip.generate({
type: 'nodebuffer',
compression: 'DEFLATE',
});
console.log('Zipped ' + numFiles + ' files, ' + (zipFile.length / MB).toFixed(2) + ' MB');
return zipFile;
}
// Promotion:
LambdaDeployer.prototype._collectVersions = function(environment, allowMissing, callback) {
var self = this;
var versions = {};
async.eachSeries(self.app.lambdas, function(lambda, next) {
var functionName = self.app.name + '-' + lambda.name;
self.lambda.getAlias({ FunctionName: functionName, Name: environment }, function(err, alias) {
if (alias) {
versions[functionName] = alias.FunctionVersion;
} else if (err && err.code == 'ResourceNotFoundException') {
console.log('Alias not found: ' + environment);
if (allowMissing) {
versions[functionName] = 0;
err = null;
}
}
next(err);
});
}, function(err) {
callback(err, versions);
});
};
LambdaDeployer.prototype._computeDiff = function() {
var self = this;
self.diff = [];
_.forEach(self.app.lambdas, function(lambda) {
var name = self.app.name + '-' + lambda.name;
var oldVersion = self.oldVersions[name] || 0;
var newVersion = self.newVersions[name];
if (oldVersion !== newVersion) {
self.diff.push({ name: name, oldVersion: oldVersion, newVersion: newVersion });
}
});
};
LambdaDeployer.prototype._updateAlias = function(alias, diff, callback) {
if (diff.oldVersion === 0) {
console.log(' ' + diff.name + ': Create alias "' + alias + '" for version ' + diff.newVersion);
this.lambda.createAlias({
FunctionName: diff.name,
Name: alias,
FunctionVersion: diff.newVersion,
}, callback);
} else {
console.log(' ' + diff.name + ': Update alias "' + alias + '" for version ' + diff.newVersion);
this.lambda.updateAlias({
FunctionName: diff.name,
Name: alias,
FunctionVersion: diff.newVersion,
}, callback);
}
};
module.exports = LambdaDeployer;
|
We deploy the same zipfile to every Lambda. Only build it once.
|
lib/internal/lambda-deployer.js
|
We deploy the same zipfile to every Lambda. Only build it once.
|
<ide><path>ib/internal/lambda-deployer.js
<ide> return !lambdaName || x.name == lambdaName;
<ide> });
<ide> console.log('Found ' + lambdasToDeploy.length + ' lambdas to deploy');
<add> var zipFile = buildZipFile();
<ide> async.eachSeries(lambdasToDeploy, function(lambda, next) {
<del> self._deployLambda(lambda, environment, next);
<add> self._deployLambda(zipFile, lambda, environment, next);
<ide> }, callback);
<ide> };
<ide>
<ide>
<ide> // Deployment:
<ide>
<del>LambdaDeployer.prototype._deployLambda = function(lambda, environment, callback) {
<add>LambdaDeployer.prototype._deployLambda = function(zipFile, lambda, environment, callback) {
<ide> var self = this;
<ide> var functionName = self.app.name + '-' + lambda.name;
<ide> utils.logBanner();
<ide> console.log('Deploying "' + functionName + '" to environment "' + environment + '"');
<ide>
<ide> var description = 'Lambdafai ' + new Date().toDateString();
<del> var zipFile = buildZipFile();
<ide> var version;
<ide>
<ide> async.waterfall([
|
|
Java
|
bsd-3-clause
|
022490f8020d733734c200ef7efd4975c5edb00f
| 0 |
credentials/irma_mno_server
|
package org.irmacard.mno.web;
import org.irmacard.credentials.info.CredentialIdentifier;
import org.irmacard.credentials.info.InfoException;
import org.irmacard.mno.common.DriverDemographicInfo;
import org.irmacard.mno.common.EDLDataMessage;
import org.irmacard.mno.common.EnrollmentStartMessage;
import org.irmacard.mno.common.PassportVerificationResultMessage;
import org.jmrtd.lds.MRZInfo;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
@Path("v2/dl")
public class DLEnrollmentResource extends GenericEnrollmentResource<EDLDataMessage> {
@GET
@Path("/start")
@Produces(MediaType.APPLICATION_JSON)
@Override
public EnrollmentStartMessage start() {
return super.start();
}
@POST
@Path("/verify-document")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Override
public PassportVerificationResultMessage verifyDocument(EDLDataMessage documentData)
throws InfoException {
return super.verifyDocument(documentData);
}
@Override
protected HashMap<CredentialIdentifier, HashMap<String, String>> getCredentialList(EnrollmentSession session)
throws InfoException { // TODO
HashMap<CredentialIdentifier, HashMap<String, String>> credentials = new HashMap<>();
EDLDataMessage data = session.getEDLDataMessage();
DriverDemographicInfo driver = data.getDriverDemographicInfo();
SimpleDateFormat bacDateFormat = new SimpleDateFormat("yyMMdd");
SimpleDateFormat hrDateFormat = new SimpleDateFormat("MMM d, y"); // Matches Android's default date format
Date dob;
Date expiry;
try {
dob = bacDateFormat.parse(driver.getDob());
expiry = bacDateFormat.parse(driver.getDoe());
} catch (ParseException e) {
e.printStackTrace();
throw new InfoException("Failed to parse dates", e);
}
int[] lowAges = {12,16,18,21};
credentials.put(new CredentialIdentifier(SCHEME_MANAGER, ISSUER, "ageLower"), ageAttributes(lowAges, dob));
int[] highAges = {50, 60, 65, 75};
credentials.put(new CredentialIdentifier(SCHEME_MANAGER, ISSUER, "ageHigher"), ageAttributes(highAges, dob));
return null;
}
}
|
src/main/java/org/irmacard/mno/web/DLEnrollmentResource.java
|
package org.irmacard.mno.web;
import org.irmacard.credentials.info.CredentialIdentifier;
import org.irmacard.credentials.info.InfoException;
import org.irmacard.mno.common.EDLDataMessage;
import org.irmacard.mno.common.EnrollmentStartMessage;
import org.irmacard.mno.common.PassportVerificationResultMessage;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
public class DLEnrollmentResource extends GenericEnrollmentResource<EDLDataMessage> {
@GET
@Path("/start")
@Produces(MediaType.APPLICATION_JSON)
@Override
public EnrollmentStartMessage start() {
return super.start();
}
@POST
@Path("/verify-dl")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Override
public PassportVerificationResultMessage verifyDocument(EDLDataMessage documentData)
throws InfoException {
return super.verifyDocument(documentData);
}
@Override
protected HashMap<CredentialIdentifier, HashMap<String, String>> getCredentialList(EnrollmentSession session)
throws InfoException { // TODO
return null;
}
}
|
WIP on DL credential computing
|
src/main/java/org/irmacard/mno/web/DLEnrollmentResource.java
|
WIP on DL credential computing
|
<ide><path>rc/main/java/org/irmacard/mno/web/DLEnrollmentResource.java
<ide>
<ide> import org.irmacard.credentials.info.CredentialIdentifier;
<ide> import org.irmacard.credentials.info.InfoException;
<add>import org.irmacard.mno.common.DriverDemographicInfo;
<ide> import org.irmacard.mno.common.EDLDataMessage;
<ide> import org.irmacard.mno.common.EnrollmentStartMessage;
<ide> import org.irmacard.mno.common.PassportVerificationResultMessage;
<add>import org.jmrtd.lds.MRZInfo;
<ide>
<ide> import javax.ws.rs.*;
<ide> import javax.ws.rs.core.MediaType;
<add>import java.text.ParseException;
<add>import java.text.SimpleDateFormat;
<add>import java.util.Date;
<ide> import java.util.HashMap;
<ide>
<add>@Path("v2/dl")
<ide> public class DLEnrollmentResource extends GenericEnrollmentResource<EDLDataMessage> {
<ide> @GET
<ide> @Path("/start")
<ide> return super.start();
<ide> }
<ide>
<del>
<ide> @POST
<del> @Path("/verify-dl")
<add> @Path("/verify-document")
<ide> @Consumes(MediaType.APPLICATION_JSON)
<ide> @Produces(MediaType.APPLICATION_JSON)
<ide> @Override
<ide> @Override
<ide> protected HashMap<CredentialIdentifier, HashMap<String, String>> getCredentialList(EnrollmentSession session)
<ide> throws InfoException { // TODO
<add> HashMap<CredentialIdentifier, HashMap<String, String>> credentials = new HashMap<>();
<add> EDLDataMessage data = session.getEDLDataMessage();
<add> DriverDemographicInfo driver = data.getDriverDemographicInfo();
<add>
<add> SimpleDateFormat bacDateFormat = new SimpleDateFormat("yyMMdd");
<add> SimpleDateFormat hrDateFormat = new SimpleDateFormat("MMM d, y"); // Matches Android's default date format
<add> Date dob;
<add> Date expiry;
<add>
<add> try {
<add> dob = bacDateFormat.parse(driver.getDob());
<add> expiry = bacDateFormat.parse(driver.getDoe());
<add> } catch (ParseException e) {
<add> e.printStackTrace();
<add> throw new InfoException("Failed to parse dates", e);
<add> }
<add>
<add> int[] lowAges = {12,16,18,21};
<add> credentials.put(new CredentialIdentifier(SCHEME_MANAGER, ISSUER, "ageLower"), ageAttributes(lowAges, dob));
<add>
<add> int[] highAges = {50, 60, 65, 75};
<add> credentials.put(new CredentialIdentifier(SCHEME_MANAGER, ISSUER, "ageHigher"), ageAttributes(highAges, dob));
<add>
<ide> return null;
<ide> }
<ide> }
|
|
Java
|
bsd-3-clause
|
cf5a3c197c9acaaef448c124e2d33c2c80073d7c
| 0 |
lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon
|
/*
* $Id: PdfTools.java,v 1.18 2007-07-24 00:16:42 thib_gc Exp $
*/
/*
Copyright (c) 2000-2007 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.devtools;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.cli.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.*;
import org.lockss.filter.pdf.*;
import org.lockss.filter.pdf.DocumentTransformUtil.*;
import org.lockss.filter.pdf.PageTransformUtil.IdentityPageTransform;
import org.lockss.util.*;
import org.pdfbox.cos.*;
import org.pdfbox.pdfwriter.ContentStreamWriter;
import org.pdfbox.pdmodel.common.PDStream;
import org.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
/**
* <p>Tools to inspect the contents of PDF documents.</p>
* @author Thib Guicherd-Callin
*/
public class PdfTools {
private static final String HELP_DESCR = "display this usage message";
protected static final char HELP_CHAR = 'h';
protected static final String HELP_STR = "help";
public static class DumpAnnotations extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
Iterator iter = pdfPage.getAnnotationIterator();
for (int ann = 0 ; iter.hasNext() ; ++ann) {
PDAnnotation annotation = (PDAnnotation)iter.next();
dump("Contents", annotation.getContents());
dump("Rectangle", annotation.getRectangle());
console.println();
}
return true;
}
}
public static class DumpBoxes extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
PdfTools.dump("Art box", pdfPage.getArtBox());
PdfTools.dump("Bleed box", pdfPage.getBleedBox());
PdfTools.dump("Crop box", pdfPage.getCropBox());
PdfTools.dump("Media box", pdfPage.getMediaBox());
PdfTools.dump("Trim box", pdfPage.getTrimBox());
return super.transform(pdfPage);
}
}
public static class DumpMetadata extends IdentityDocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
console.println("Number of pages: " + pdfDocument.getNumberOfPages());
dump("Creation date", pdfDocument.getCreationDate().getTime());
dump("Modification date", pdfDocument.getModificationDate().getTime());
dump("Author", pdfDocument.getAuthor());
dump("Creator", pdfDocument.getCreator());
dump("Keywords", pdfDocument.getKeywords());
dump("Producer", pdfDocument.getProducer());
dump("Subject", pdfDocument.getSubject());
dump("Title", pdfDocument.getTitle());
console.println("Metadata (as string):"); // newline; typically large
console.println(pdfDocument.getMetadataAsString());
return super.transform(pdfDocument);
}
}
public static class DumpNumberedPageStream extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
Iterator tokens = pdfPage.getStreamTokenIterator();
for (int tok = 0 ; tokens.hasNext() ; ++tok) {
console.println(Integer.toString(tok) + "\t" + tokens.next().toString());
}
return super.transform(pdfPage);
}
}
public static class DumpPageDictionary extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
dump(pdfPage.getDictionary());
return super.transform(pdfPage);
}
}
public static class DumpPageStream extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
for (Iterator tokens = pdfPage.getStreamTokenIterator() ; tokens.hasNext() ; ) {
console.println("\t" + tokens.next().toString());
}
return super.transform(pdfPage);
}
}
public static class DumpTrailer extends IdentityDocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
dump(pdfDocument.getTrailer());
return super.transform(pdfDocument);
}
}
public static class ReiteratePageStream implements PageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
PDStream resultStream = pdfPage.getPdfDocument().makePdStream();
OutputStream outputStream = resultStream.createOutputStream();
ContentStreamWriter tokenWriter = new ContentStreamWriter(outputStream);
tokenWriter.writeTokens(pdfPage.getStreamTokens());
pdfPage.setContents(resultStream);
return true;
}
}
public static class SplitDocumentTransform extends DocumentTransformDecorator {
protected String suffix;
public SplitDocumentTransform(String suffix,
DocumentTransform documentTransform) {
super(documentTransform);
this.suffix = suffix;
}
public boolean transform(PdfDocument pdfDocument) throws IOException {
if (!splitOutput(suffix)) {
return false;
}
boolean ret = documentTransform.transform(pdfDocument);
console.println();
if (!joinOutput(suffix)) {
return false;
}
return ret;
}
}
public static class SplitPageTransform extends PageTransformWrapper {
protected String suffix;
public SplitPageTransform(String suffix,
PageTransform pageTransform) {
super(pageTransform);
this.suffix = suffix;
}
public boolean transform(PdfDocument pdfDocument) throws IOException {
if (!splitOutput(suffix)) {
return false;
}
boolean ret = true;
for (Iterator iter = pdfDocument.getPageIterator() ; iter.hasNext() ; ) {
ret = pageTransform.transform((PdfPage)iter.next());
console.println();
if (!ret) {
break;
}
}
if (!joinOutput(suffix)) {
return false;
}
return ret;
}
}
protected static final String ANNOTATIONS = "-annotations";
protected static final String APPLY = "-apply";
protected static OutputDocumentTransform applyTransform;
protected static boolean argAnnotations;
protected static boolean argApply;
protected static String argApplyValue;
protected static boolean argBoxes;
protected static boolean argIn;
protected static String argInBase;
protected static String argInValue;
protected static boolean argLog;
protected static String argLogValue;
protected static boolean argMetadata;
protected static boolean argNumberedPageStream;
protected static boolean argOut;
protected static String argOutValue;
protected static boolean argPageStream;
protected static boolean argQuiet;
protected static boolean argRewrite;
protected static boolean argTrailer;
protected static final String BOXES = "-boxes";
protected static PrintStream console;
protected static boolean doTransform;
protected static String doTransformString;
protected static final String HELP = "-help";
protected static final String HELP_SHORT = "-h";
protected static final String IN = "-in";
protected static final String LOG = "-log";
protected static final String METADATA = "-metadata";
protected static final String NUMBEREDPAGESTREAM = "-numberedpagestream";
protected static final String OUT = "-out";
protected static final String PAGESTREAM = "-pagestream";
protected static InputStream pdfInputStream;
protected static OutputStream pdfOutputStream;
protected static final String QUIET = "-quiet";
protected static PrintStream rememberConsole;
protected static FileOutputStream rememberFileOutputStream;
protected static final String REWRITE = "-rewrite";
protected static final String TRAILER = "-trailer";
protected static final String USAGE = "-usage";
protected static final String USAGE_MESSAGE =
"\tant run-tool -Dclass=" + PdfTools.class.getName() + "\n" +
"\t\t-Dargs=\"-in in.pdf [options/commands...]\"\n" +
"Help\n" +
" -h -help -usage Displays this message\n" +
"Commands\n" +
" -annotations Dumps the annotations for each page to a file\n" +
" -boxes Dumps the bounding boxes for each page to a file\n" +
" -metadata Dumps the document metadata to a file\n" +
" -numberedpagestream Dumps a numbered list of tokens for each page to a file\n" +
" -pagestream Dumps a list of tokens for each page to a file\n" +
" -trailer Dumps the document trailer dictionary to a file\n" +
"Transforms\n" +
" -apply my.package.MyTransform Applies the given document or page transform\n" +
" to the input (output file: -out out.pdf)\n" +
" -rewrite Rewrites the input, usually in a cleaner and\n" +
" more verbose way (output file: -out out.pdf)\n" +
"Output\n" +
" -quiet Suppresses command output to the console\n" +
" -log log.txt Copies command output to the given file\n" +
"Unimplemented\n" +
" -pagedictionary\n";
// public static void main(String[] args) throws IOException {
// try {
// if (!( parseHelp(args)
// && parseArgs(args)
// && validateArgs()
// && setUpInputOutput()
// && applyTransforms())) {
// System.exit(1);
// }
// }
// finally {
// tearDownInputOutput();
// }
// }
protected static boolean applyTransforms() throws IOException {
AggregateDocumentTransform documentTransform = new AggregateDocumentTransform();
if (argAnnotations) {
documentTransform.add(new SplitPageTransform(ANNOTATIONS, new DumpAnnotations()));
}
if (argBoxes) {
documentTransform.add(new SplitPageTransform(BOXES, new DumpBoxes()));
}
if (argMetadata) {
documentTransform.add(new SplitDocumentTransform(METADATA, new DumpMetadata()));
}
if (argNumberedPageStream) {
documentTransform.add(new SplitPageTransform(NUMBEREDPAGESTREAM, new DumpNumberedPageStream()));
}
if (argPageStream) {
documentTransform.add(new SplitPageTransform(PAGESTREAM, new DumpPageStream()));
}
if (argTrailer) {
documentTransform.add(new SplitDocumentTransform(TRAILER, new DumpTrailer()));
}
PdfDocument pdfDocument = null;
try {
pdfDocument = new PdfDocument(pdfInputStream);
if (!documentTransform.transform(pdfDocument)) {
System.err.println("Transform unsuccessful (first phase)");
return false;
}
if (doTransform) {
if (!applyTransform.transform(pdfDocument, pdfOutputStream)) {
System.err.println("Transform unsuccessful (second phase)");
return false;
}
}
return true;
}
catch (IOException ioe) {
System.err.println("Transform failed");
ioe.printStackTrace(System.err);
return false;
}
finally {
PdfDocument.close(pdfDocument);
}
}
protected static void dump(COSDictionary dictionary) {
for (Iterator keys = dictionary.keyList().iterator() ; keys.hasNext() ; ) {
COSName key = (COSName)keys.next();
console.println(key.getName() + "\t" + dictionary.getItem(key).toString());
}
}
protected static void dump(String name, Object obj) {
if (obj != null) {
console.println(name + ": " + obj.toString());
}
}
protected static void dump(String name, String str) {
if (str != null && !str.equals("")) {
console.println(name + ": " + str);
}
}
protected static boolean joinOutput(String suffix) {
String fileName = argInBase + suffix + ".txt";
try {
console = rememberConsole;
rememberConsole = null;
rememberFileOutputStream.close();
rememberFileOutputStream = null;
return true;
}
catch (IOException ioe) {
System.err.println("Error: could not close an output stream to " + fileName);
ioe.printStackTrace(System.err);
return false;
}
}
protected static boolean parseArgs(String[] args) {
for (int arg = 0 ; arg < args.length ; ++arg) {
if (false) {
// Copy/paste hack
}
else if (args[arg].equals(ANNOTATIONS)) {
argAnnotations = true;
}
else if (args[arg].equals(APPLY)) {
argApply = true;
argApplyValue = args[++arg];
}
else if (args[arg].equals(BOXES)) {
argBoxes = true;
}
else if (args[arg].equals(IN)) {
argIn = true;
argInValue = args[++arg];
}
else if (args[arg].equals(LOG)) {
argLog = true;
argLogValue = args[++arg];
}
else if (args[arg].equals(METADATA)) {
argMetadata = true;
}
else if (args[arg].equals(NUMBEREDPAGESTREAM)) {
argNumberedPageStream = true;
}
else if (args[arg].equals(OUT)) {
argOut = true;
argOutValue = args[++arg];
}
else if (args[arg].equals(PAGESTREAM)) {
argPageStream = true;
}
else if (args[arg].equals(QUIET)) {
argQuiet = true;
}
else if (args[arg].equals(REWRITE)) {
argRewrite = true;
}
else if (args[arg].equals(TRAILER)) {
argTrailer = true;
}
else {
System.err.println("Unknown option: " + args[arg]);
return false;
}
}
return true;
}
protected static boolean parseHelp(String[] args) {
if ( args.length == 0
|| ( args.length == 1
&& ( args[0].equals(HELP_SHORT)
|| args[0].equals(HELP)
|| args[0].equals(USAGE)))) {
System.err.println(USAGE_MESSAGE);
return false;
}
return true;
}
protected static boolean setUpInputOutput() {
if (argInValue.endsWith(".pdf")) {
argInBase = argInValue.substring(0, argInValue.length() - ".pdf".length());
}
else {
argInBase = argInValue;
}
// Set up PDF input
try {
pdfInputStream = new FileInputStream(argInValue);
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: input file not found");
fnfe.printStackTrace(System.err);
return false;
}
// Set up PDF output
if (argOut) {
try {
if (argOutValue.startsWith("-")) { // this functionality
argOutValue = argInBase + argOutValue + ".pdf"; // is currently
} // undocumented
pdfOutputStream = new FileOutputStream(argOutValue);
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: could not set up output stream");
fnfe.printStackTrace(System.err);
return false;
}
}
else {
pdfOutputStream = new NullOutputStream();
}
// Set up console output
// ...first, the actual console output
if (argQuiet) {
console = new PrintStream(new NullOutputStream());
}
else {
console = System.out;
}
// ...then, the indirect output
if (argLog) {
try {
FileOutputStream logOutputStream = new FileOutputStream(argLogValue);
TeeOutputStream teeOutputStream = new TeeOutputStream(console, logOutputStream);
console = new PrintStream(teeOutputStream);
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: could not set up log output stream");
fnfe.printStackTrace(System.err);
return false;
}
}
// Done
return true;
}
protected static boolean splitOutput(String suffix) {
String fileName = argInBase + suffix + ".txt";
try {
rememberFileOutputStream = new FileOutputStream(fileName);
TeeOutputStream teeOutputStream = new TeeOutputStream(console, rememberFileOutputStream);
rememberConsole = console;
console = new PrintStream(teeOutputStream);
return true;
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: could not create an output stream for " + fileName);
fnfe.printStackTrace(System.err);
return false;
}
}
protected static void tearDownInputOutput() {
IOUtils.closeQuietly(pdfInputStream);
IOUtils.closeQuietly(pdfOutputStream);
IOUtils.closeQuietly(console);
}
protected static boolean validateArgs() {
// Cannot have APPLY and REWRITE at the same time
if (argApply && argRewrite) {
System.err.println("Error: cannot specify " + APPLY + " and " + REWRITE + " at the same time.");
return false;
}
// Remember that a transform is requested
if (argApply || argRewrite) {
doTransform = true;
doTransformString = argApply ? APPLY : REWRITE;
}
// IN must be specified
if (!argIn) {
if (doTransform) {
System.err.println("Error: cannot specify " + doTransformString + " without " + IN);
}
else {
System.err.println("Error: must specify " + IN);
}
return false;
}
// OUT must be specified if and only if a transform is requested
if (!argOut && doTransform) {
System.err.println("Error: cannot specify " + doTransformString + " without " + OUT);
return false;
}
if (argOut && !doTransform) {
System.err.println("Error: cannot specify " + OUT + " without " + APPLY + " or " + REWRITE);
return false;
}
if (doTransform) {
if (argApply) {
try {
Class transformClass = Class.forName(argApplyValue);
Object transform = transformClass.newInstance();
if (transform instanceof OutputDocumentTransform) {
applyTransform = (OutputDocumentTransform)transform;
}
else if (transform instanceof DocumentTransform) {
applyTransform = new SimpleOutputDocumentTransform((DocumentTransform)transform);
}
else if (transform instanceof PageTransform) {
applyTransform = new SimpleOutputDocumentTransform(new TransformEachPage((PageTransform)transform));
}
else {
throw new ClassCastException(transform.getClass().getName());
}
}
catch (ClassNotFoundException cnfe) {
System.err.println("Error: could not load " + argApplyValue);
cnfe.printStackTrace(System.err);
return false;
}
catch (InstantiationException ie) {
System.err.println("Error: could not instantiate " + argApplyValue);
ie.printStackTrace(System.err);
return false;
}
catch (IllegalAccessException iae) {
System.err.println("Error: could not access " + argApplyValue);
iae.printStackTrace(System.err);
return false;
}
catch (ClassCastException cce) {
System.err.println("Error: " + argApplyValue + " is not a transform type");
cce.printStackTrace(System.err);
return false;
}
}
else /* argRewrite */ {
applyTransform = new SimpleOutputDocumentTransform(new TransformEachPage(new ReiteratePageStream()));
}
}
// Done
return true;
}
protected static Options prepareOptions() {
Options options = new Options();
OptionGroup leadingGroup = new OptionGroup();
OptionBuilder.withDescription(HELP_DESCR);
OptionBuilder.withLongOpt(HELP_STR);
leadingGroup.addOption(OptionBuilder.create(HELP_CHAR));
OptionBuilder.hasArg();
OptionBuilder.withArgName("inputfile");
OptionBuilder.withDescription("specifies the input file");
OptionBuilder.withLongOpt("input");
leadingGroup.addOption(OptionBuilder.create('i'));
leadingGroup.setRequired(true);
options.addOptionGroup(leadingGroup);
OptionGroup transformGroup = new OptionGroup();
OptionBuilder.isRequired();
OptionBuilder.hasArg();
OptionBuilder.withArgName("transformclass");
OptionBuilder.withDescription("apply a transform");
OptionBuilder.withLongOpt("apply");
transformGroup.addOption(OptionBuilder.create('a'));
OptionBuilder.withDescription("rewrite the input file");
OptionBuilder.withLongOpt("rewrite");
transformGroup.addOption(OptionBuilder.create('r'));
options.addOptionGroup(transformGroup);
OptionBuilder.withDescription("dump the annotations of each page");
OptionBuilder.withLongOpt("page-annotations");
options.addOption(OptionBuilder.create('A'));
OptionBuilder.withDescription("dump the boxes of each page");
OptionBuilder.withLongOpt("page-boxes");
options.addOption(OptionBuilder.create('B'));
OptionBuilder.withDescription("duplicate all output to the console");
OptionBuilder.withLongOpt("console");
options.addOption(OptionBuilder.create('c'));
OptionBuilder.withDescription("dump the dictionary of each page");
OptionBuilder.withLongOpt("page-dictionaries");
options.addOption(OptionBuilder.create('D'));
OptionBuilder.withDescription("dump the document metadata");
OptionBuilder.withLongOpt("metadata");
options.addOption(OptionBuilder.create('m'));
OptionBuilder.withDescription("dump the token stream of each page with numbers");
OptionBuilder.withLongOpt("numbered-page-streams");
options.addOption(OptionBuilder.create('N'));
OptionBuilder.hasArg();
OptionBuilder.withArgName("outputfile");
OptionBuilder.withDescription("specifies the output file");
OptionBuilder.withLongOpt("output");
options.addOption(OptionBuilder.create('o'));
OptionBuilder.withDescription("dump the token stream of each page");
OptionBuilder.withLongOpt("page-streams");
options.addOption(OptionBuilder.create('S'));
OptionBuilder.withDescription("dump the document trailer");
OptionBuilder.withLongOpt("trailer");
options.addOption(OptionBuilder.create('t'));
OptionBuilder.withDescription("produce verbose output");
OptionBuilder.withLongOpt("verbose");
options.addOption(OptionBuilder.create('v'));
return options;
}
public static void main(String[] args) {
try {
// Parse the command line
Options options = prepareOptions();
CommandLineParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
// Display the usage message
if (commandLine.hasOption(HELP_CHAR)) {
new HelpFormatter().printHelp("java " + PdfTools.class.getName(), options, true);
return;
}
PdfTools pdfTools = new PdfTools();
pdfTools.processCommandLine(commandLine);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
protected CommandLine commandLine;
protected synchronized void processCommandLine(CommandLine commandLine) {
this.commandLine = commandLine;
validateCommandLine();
}
protected void validateCommandLine() {
}
}
|
tools/src/org/lockss/devtools/PdfTools.java
|
/*
* $Id: PdfTools.java,v 1.17 2007-07-24 00:11:13 thib_gc Exp $
*/
/*
Copyright (c) 2000-2007 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.devtools;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.cli.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.*;
import org.lockss.filter.pdf.*;
import org.lockss.filter.pdf.DocumentTransformUtil.*;
import org.lockss.filter.pdf.PageTransformUtil.IdentityPageTransform;
import org.lockss.util.*;
import org.pdfbox.cos.*;
import org.pdfbox.pdfwriter.ContentStreamWriter;
import org.pdfbox.pdmodel.common.PDStream;
import org.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
/**
* <p>Tools to inspect the contents of PDF documents.</p>
* @author Thib Guicherd-Callin
*/
public class PdfTools {
private static final String HELP_DESCR = "display this usage message";
protected static final char HELP_CHAR = 'h';
protected static final String HELP_STR = "help";
public static class DumpAnnotations extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
Iterator iter = pdfPage.getAnnotationIterator();
for (int ann = 0 ; iter.hasNext() ; ++ann) {
PDAnnotation annotation = (PDAnnotation)iter.next();
dump("Contents", annotation.getContents());
dump("Rectangle", annotation.getRectangle());
console.println();
}
return true;
}
}
public static class DumpBoxes extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
PdfTools.dump("Art box", pdfPage.getArtBox());
PdfTools.dump("Bleed box", pdfPage.getBleedBox());
PdfTools.dump("Crop box", pdfPage.getCropBox());
PdfTools.dump("Media box", pdfPage.getMediaBox());
PdfTools.dump("Trim box", pdfPage.getTrimBox());
return super.transform(pdfPage);
}
}
public static class DumpMetadata extends IdentityDocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
console.println("Number of pages: " + pdfDocument.getNumberOfPages());
dump("Creation date", pdfDocument.getCreationDate().getTime());
dump("Modification date", pdfDocument.getModificationDate().getTime());
dump("Author", pdfDocument.getAuthor());
dump("Creator", pdfDocument.getCreator());
dump("Keywords", pdfDocument.getKeywords());
dump("Producer", pdfDocument.getProducer());
dump("Subject", pdfDocument.getSubject());
dump("Title", pdfDocument.getTitle());
console.println("Metadata (as string):"); // newline; typically large
console.println(pdfDocument.getMetadataAsString());
return super.transform(pdfDocument);
}
}
public static class DumpNumberedPageStream extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
Iterator tokens = pdfPage.getStreamTokenIterator();
for (int tok = 0 ; tokens.hasNext() ; ++tok) {
console.println(Integer.toString(tok) + "\t" + tokens.next().toString());
}
return super.transform(pdfPage);
}
}
public static class DumpPageDictionary extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
dump(pdfPage.getDictionary());
return super.transform(pdfPage);
}
}
public static class DumpPageStream extends IdentityPageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
for (Iterator tokens = pdfPage.getStreamTokenIterator() ; tokens.hasNext() ; ) {
console.println("\t" + tokens.next().toString());
}
return super.transform(pdfPage);
}
}
public static class DumpTrailer extends IdentityDocumentTransform {
public boolean transform(PdfDocument pdfDocument) throws IOException {
dump(pdfDocument.getTrailer());
return super.transform(pdfDocument);
}
}
public static class ReiteratePageStream implements PageTransform {
public boolean transform(PdfPage pdfPage) throws IOException {
PDStream resultStream = pdfPage.getPdfDocument().makePdStream();
OutputStream outputStream = resultStream.createOutputStream();
ContentStreamWriter tokenWriter = new ContentStreamWriter(outputStream);
tokenWriter.writeTokens(pdfPage.getStreamTokens());
pdfPage.setContents(resultStream);
return true;
}
}
public static class SplitDocumentTransform extends DocumentTransformDecorator {
protected String suffix;
public SplitDocumentTransform(String suffix,
DocumentTransform documentTransform) {
super(documentTransform);
this.suffix = suffix;
}
public boolean transform(PdfDocument pdfDocument) throws IOException {
if (!splitOutput(suffix)) {
return false;
}
boolean ret = documentTransform.transform(pdfDocument);
console.println();
if (!joinOutput(suffix)) {
return false;
}
return ret;
}
}
public static class SplitPageTransform extends PageTransformWrapper {
protected String suffix;
public SplitPageTransform(String suffix,
PageTransform pageTransform) {
super(pageTransform);
this.suffix = suffix;
}
public boolean transform(PdfDocument pdfDocument) throws IOException {
if (!splitOutput(suffix)) {
return false;
}
boolean ret = true;
for (Iterator iter = pdfDocument.getPageIterator() ; iter.hasNext() ; ) {
ret = pageTransform.transform((PdfPage)iter.next());
console.println();
if (!ret) {
break;
}
}
if (!joinOutput(suffix)) {
return false;
}
return ret;
}
}
protected static final String ANNOTATIONS = "-annotations";
protected static final String APPLY = "-apply";
protected static OutputDocumentTransform applyTransform;
protected static boolean argAnnotations;
protected static boolean argApply;
protected static String argApplyValue;
protected static boolean argBoxes;
protected static boolean argIn;
protected static String argInBase;
protected static String argInValue;
protected static boolean argLog;
protected static String argLogValue;
protected static boolean argMetadata;
protected static boolean argNumberedPageStream;
protected static boolean argOut;
protected static String argOutValue;
protected static boolean argPageStream;
protected static boolean argQuiet;
protected static boolean argRewrite;
protected static boolean argTrailer;
protected static final String BOXES = "-boxes";
protected static PrintStream console;
protected static boolean doTransform;
protected static String doTransformString;
protected static final String HELP = "-help";
protected static final String HELP_SHORT = "-h";
protected static final String IN = "-in";
protected static final String LOG = "-log";
protected static final String METADATA = "-metadata";
protected static final String NUMBEREDPAGESTREAM = "-numberedpagestream";
protected static final String OUT = "-out";
protected static final String PAGESTREAM = "-pagestream";
protected static InputStream pdfInputStream;
protected static OutputStream pdfOutputStream;
protected static final String QUIET = "-quiet";
protected static PrintStream rememberConsole;
protected static FileOutputStream rememberFileOutputStream;
protected static final String REWRITE = "-rewrite";
protected static final String TRAILER = "-trailer";
protected static final String USAGE = "-usage";
protected static final String USAGE_MESSAGE =
"\tant run-tool -Dclass=" + PdfTools.class.getName() + "\n" +
"\t\t-Dargs=\"-in in.pdf [options/commands...]\"\n" +
"Help\n" +
" -h -help -usage Displays this message\n" +
"Commands\n" +
" -annotations Dumps the annotations for each page to a file\n" +
" -boxes Dumps the bounding boxes for each page to a file\n" +
" -metadata Dumps the document metadata to a file\n" +
" -numberedpagestream Dumps a numbered list of tokens for each page to a file\n" +
" -pagestream Dumps a list of tokens for each page to a file\n" +
" -trailer Dumps the document trailer dictionary to a file\n" +
"Transforms\n" +
" -apply my.package.MyTransform Applies the given document or page transform\n" +
" to the input (output file: -out out.pdf)\n" +
" -rewrite Rewrites the input, usually in a cleaner and\n" +
" more verbose way (output file: -out out.pdf)\n" +
"Output\n" +
" -quiet Suppresses command output to the console\n" +
" -log log.txt Copies command output to the given file\n" +
"Unimplemented\n" +
" -pagedictionary\n";
// public static void main(String[] args) throws IOException {
// try {
// if (!( parseHelp(args)
// && parseArgs(args)
// && validateArgs()
// && setUpInputOutput()
// && applyTransforms())) {
// System.exit(1);
// }
// }
// finally {
// tearDownInputOutput();
// }
// }
protected static boolean applyTransforms() throws IOException {
AggregateDocumentTransform documentTransform = new AggregateDocumentTransform();
if (argAnnotations) {
documentTransform.add(new SplitPageTransform(ANNOTATIONS, new DumpAnnotations()));
}
if (argBoxes) {
documentTransform.add(new SplitPageTransform(BOXES, new DumpBoxes()));
}
if (argMetadata) {
documentTransform.add(new SplitDocumentTransform(METADATA, new DumpMetadata()));
}
if (argNumberedPageStream) {
documentTransform.add(new SplitPageTransform(NUMBEREDPAGESTREAM, new DumpNumberedPageStream()));
}
if (argPageStream) {
documentTransform.add(new SplitPageTransform(PAGESTREAM, new DumpPageStream()));
}
if (argTrailer) {
documentTransform.add(new SplitDocumentTransform(TRAILER, new DumpTrailer()));
}
PdfDocument pdfDocument = null;
try {
pdfDocument = new PdfDocument(pdfInputStream);
if (!documentTransform.transform(pdfDocument)) {
System.err.println("Transform unsuccessful (first phase)");
return false;
}
if (doTransform) {
if (!applyTransform.transform(pdfDocument, pdfOutputStream)) {
System.err.println("Transform unsuccessful (second phase)");
return false;
}
}
return true;
}
catch (IOException ioe) {
System.err.println("Transform failed");
ioe.printStackTrace(System.err);
return false;
}
finally {
PdfDocument.close(pdfDocument);
}
}
protected static void dump(COSDictionary dictionary) {
for (Iterator keys = dictionary.keyList().iterator() ; keys.hasNext() ; ) {
COSName key = (COSName)keys.next();
console.println(key.getName() + "\t" + dictionary.getItem(key).toString());
}
}
protected static void dump(String name, Object obj) {
if (obj != null) {
console.println(name + ": " + obj.toString());
}
}
protected static void dump(String name, String str) {
if (str != null && !str.equals("")) {
console.println(name + ": " + str);
}
}
protected static boolean joinOutput(String suffix) {
String fileName = argInBase + suffix + ".txt";
try {
console = rememberConsole;
rememberConsole = null;
rememberFileOutputStream.close();
rememberFileOutputStream = null;
return true;
}
catch (IOException ioe) {
System.err.println("Error: could not close an output stream to " + fileName);
ioe.printStackTrace(System.err);
return false;
}
}
protected static boolean parseArgs(String[] args) {
for (int arg = 0 ; arg < args.length ; ++arg) {
if (false) {
// Copy/paste hack
}
else if (args[arg].equals(ANNOTATIONS)) {
argAnnotations = true;
}
else if (args[arg].equals(APPLY)) {
argApply = true;
argApplyValue = args[++arg];
}
else if (args[arg].equals(BOXES)) {
argBoxes = true;
}
else if (args[arg].equals(IN)) {
argIn = true;
argInValue = args[++arg];
}
else if (args[arg].equals(LOG)) {
argLog = true;
argLogValue = args[++arg];
}
else if (args[arg].equals(METADATA)) {
argMetadata = true;
}
else if (args[arg].equals(NUMBEREDPAGESTREAM)) {
argNumberedPageStream = true;
}
else if (args[arg].equals(OUT)) {
argOut = true;
argOutValue = args[++arg];
}
else if (args[arg].equals(PAGESTREAM)) {
argPageStream = true;
}
else if (args[arg].equals(QUIET)) {
argQuiet = true;
}
else if (args[arg].equals(REWRITE)) {
argRewrite = true;
}
else if (args[arg].equals(TRAILER)) {
argTrailer = true;
}
else {
System.err.println("Unknown option: " + args[arg]);
return false;
}
}
return true;
}
protected static boolean parseHelp(String[] args) {
if ( args.length == 0
|| ( args.length == 1
&& ( args[0].equals(HELP_SHORT)
|| args[0].equals(HELP)
|| args[0].equals(USAGE)))) {
System.err.println(USAGE_MESSAGE);
return false;
}
return true;
}
protected static boolean setUpInputOutput() {
if (argInValue.endsWith(".pdf")) {
argInBase = argInValue.substring(0, argInValue.length() - ".pdf".length());
}
else {
argInBase = argInValue;
}
// Set up PDF input
try {
pdfInputStream = new FileInputStream(argInValue);
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: input file not found");
fnfe.printStackTrace(System.err);
return false;
}
// Set up PDF output
if (argOut) {
try {
if (argOutValue.startsWith("-")) { // this functionality
argOutValue = argInBase + argOutValue + ".pdf"; // is currently
} // undocumented
pdfOutputStream = new FileOutputStream(argOutValue);
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: could not set up output stream");
fnfe.printStackTrace(System.err);
return false;
}
}
else {
pdfOutputStream = new NullOutputStream();
}
// Set up console output
// ...first, the actual console output
if (argQuiet) {
console = new PrintStream(new NullOutputStream());
}
else {
console = System.out;
}
// ...then, the indirect output
if (argLog) {
try {
FileOutputStream logOutputStream = new FileOutputStream(argLogValue);
TeeOutputStream teeOutputStream = new TeeOutputStream(console, logOutputStream);
console = new PrintStream(teeOutputStream);
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: could not set up log output stream");
fnfe.printStackTrace(System.err);
return false;
}
}
// Done
return true;
}
protected static boolean splitOutput(String suffix) {
String fileName = argInBase + suffix + ".txt";
try {
rememberFileOutputStream = new FileOutputStream(fileName);
TeeOutputStream teeOutputStream = new TeeOutputStream(console, rememberFileOutputStream);
rememberConsole = console;
console = new PrintStream(teeOutputStream);
return true;
}
catch (FileNotFoundException fnfe) {
System.err.println("Error: could not create an output stream for " + fileName);
fnfe.printStackTrace(System.err);
return false;
}
}
protected static void tearDownInputOutput() {
IOUtils.closeQuietly(pdfInputStream);
IOUtils.closeQuietly(pdfOutputStream);
IOUtils.closeQuietly(console);
}
protected static boolean validateArgs() {
// Cannot have APPLY and REWRITE at the same time
if (argApply && argRewrite) {
System.err.println("Error: cannot specify " + APPLY + " and " + REWRITE + " at the same time.");
return false;
}
// Remember that a transform is requested
if (argApply || argRewrite) {
doTransform = true;
doTransformString = argApply ? APPLY : REWRITE;
}
// IN must be specified
if (!argIn) {
if (doTransform) {
System.err.println("Error: cannot specify " + doTransformString + " without " + IN);
}
else {
System.err.println("Error: must specify " + IN);
}
return false;
}
// OUT must be specified if and only if a transform is requested
if (!argOut && doTransform) {
System.err.println("Error: cannot specify " + doTransformString + " without " + OUT);
return false;
}
if (argOut && !doTransform) {
System.err.println("Error: cannot specify " + OUT + " without " + APPLY + " or " + REWRITE);
return false;
}
if (doTransform) {
if (argApply) {
try {
Class transformClass = Class.forName(argApplyValue);
Object transform = transformClass.newInstance();
if (transform instanceof OutputDocumentTransform) {
applyTransform = (OutputDocumentTransform)transform;
}
else if (transform instanceof DocumentTransform) {
applyTransform = new SimpleOutputDocumentTransform((DocumentTransform)transform);
}
else if (transform instanceof PageTransform) {
applyTransform = new SimpleOutputDocumentTransform(new TransformEachPage((PageTransform)transform));
}
else {
throw new ClassCastException(transform.getClass().getName());
}
}
catch (ClassNotFoundException cnfe) {
System.err.println("Error: could not load " + argApplyValue);
cnfe.printStackTrace(System.err);
return false;
}
catch (InstantiationException ie) {
System.err.println("Error: could not instantiate " + argApplyValue);
ie.printStackTrace(System.err);
return false;
}
catch (IllegalAccessException iae) {
System.err.println("Error: could not access " + argApplyValue);
iae.printStackTrace(System.err);
return false;
}
catch (ClassCastException cce) {
System.err.println("Error: " + argApplyValue + " is not a transform type");
cce.printStackTrace(System.err);
return false;
}
}
else /* argRewrite */ {
applyTransform = new SimpleOutputDocumentTransform(new TransformEachPage(new ReiteratePageStream()));
}
}
// Done
return true;
}
protected static Options prepareOptions() {
Options options = new Options();
OptionGroup leadingGroup = new OptionGroup();
OptionBuilder.withDescription(HELP_DESCR);
OptionBuilder.withLongOpt(HELP_STR);
leadingGroup.addOption(OptionBuilder.create(HELP_CHAR));
OptionBuilder.hasArg();
OptionBuilder.withArgName("inputfile");
OptionBuilder.withDescription("specifies the input file");
OptionBuilder.withLongOpt("input");
leadingGroup.addOption(OptionBuilder.create('i'));
leadingGroup.setRequired(true);
options.addOptionGroup(leadingGroup);
OptionGroup transformGroup = new OptionGroup();
OptionBuilder.isRequired();
OptionBuilder.hasArg();
OptionBuilder.withArgName("transformclass");
OptionBuilder.withDescription("apply a transform");
OptionBuilder.withLongOpt("apply");
transformGroup.addOption(OptionBuilder.create('a'));
OptionBuilder.withDescription("rewrite the input file");
OptionBuilder.withLongOpt("rewrite");
transformGroup.addOption(OptionBuilder.create('r'));
options.addOptionGroup(transformGroup);
OptionBuilder.withDescription("duplicate all output to the console");
OptionBuilder.withLongOpt("console");
options.addOption(OptionBuilder.create('c'));
OptionBuilder.withDescription("dump the document metadata");
OptionBuilder.withLongOpt("metadata");
options.addOption(OptionBuilder.create('m'));
OptionBuilder.withDescription("dump the token stream of each page with numbers");
OptionBuilder.withLongOpt("numbered-page-streams");
options.addOption(OptionBuilder.create('N'));
OptionBuilder.hasArg();
OptionBuilder.withArgName("outputfile");
OptionBuilder.withDescription("specifies the output file");
OptionBuilder.withLongOpt("output");
options.addOption(OptionBuilder.create('o'));
OptionBuilder.withDescription("dump the annotations of each page");
OptionBuilder.withLongOpt("page-annotations");
options.addOption(OptionBuilder.create('A'));
OptionBuilder.withDescription("dump the boxes of each page");
OptionBuilder.withLongOpt("page-boxes");
options.addOption(OptionBuilder.create('B'));
OptionBuilder.withDescription("dump the dictionary of each page");
OptionBuilder.withLongOpt("page-dictionaries");
options.addOption(OptionBuilder.create('D'));
OptionBuilder.withDescription("dump the token stream of each page");
OptionBuilder.withLongOpt("page-streams");
options.addOption(OptionBuilder.create('S'));
OptionBuilder.withDescription("dump the document trailer");
OptionBuilder.withLongOpt("trailer");
options.addOption(OptionBuilder.create('r'));
OptionBuilder.withDescription("produce verbose output");
OptionBuilder.withLongOpt("verbose");
options.addOption(OptionBuilder.create('v'));
return options;
}
public static void main(String[] args) {
try {
// Parse the command line
Options options = prepareOptions();
CommandLineParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
// Display the usage message
if (commandLine.hasOption(HELP_CHAR)) {
new HelpFormatter().printHelp("java " + PdfTools.class.getName(), options, true);
return;
}
PdfTools pdfTools = new PdfTools();
pdfTools.processCommandLine(commandLine);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
protected CommandLine commandLine;
protected synchronized void processCommandLine(CommandLine commandLine) {
this.commandLine = commandLine;
validateCommandLine();
}
protected void validateCommandLine() {
}
}
|
Added Commons CLI. Partial rework of PdfTools.
git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@6416 4f837ed2-42f5-46e7-a7a5-fa17313484d4
|
tools/src/org/lockss/devtools/PdfTools.java
|
Added Commons CLI. Partial rework of PdfTools.
|
<ide><path>ools/src/org/lockss/devtools/PdfTools.java
<ide> /*
<del> * $Id: PdfTools.java,v 1.17 2007-07-24 00:11:13 thib_gc Exp $
<add> * $Id: PdfTools.java,v 1.18 2007-07-24 00:16:42 thib_gc Exp $
<ide> */
<ide>
<ide> /*
<ide>
<ide> options.addOptionGroup(transformGroup);
<ide>
<add> OptionBuilder.withDescription("dump the annotations of each page");
<add> OptionBuilder.withLongOpt("page-annotations");
<add> options.addOption(OptionBuilder.create('A'));
<add>
<add> OptionBuilder.withDescription("dump the boxes of each page");
<add> OptionBuilder.withLongOpt("page-boxes");
<add> options.addOption(OptionBuilder.create('B'));
<add>
<ide> OptionBuilder.withDescription("duplicate all output to the console");
<ide> OptionBuilder.withLongOpt("console");
<ide> options.addOption(OptionBuilder.create('c'));
<add>
<add> OptionBuilder.withDescription("dump the dictionary of each page");
<add> OptionBuilder.withLongOpt("page-dictionaries");
<add> options.addOption(OptionBuilder.create('D'));
<ide>
<ide> OptionBuilder.withDescription("dump the document metadata");
<ide> OptionBuilder.withLongOpt("metadata");
<ide> OptionBuilder.withLongOpt("output");
<ide> options.addOption(OptionBuilder.create('o'));
<ide>
<del> OptionBuilder.withDescription("dump the annotations of each page");
<del> OptionBuilder.withLongOpt("page-annotations");
<del> options.addOption(OptionBuilder.create('A'));
<del>
<del> OptionBuilder.withDescription("dump the boxes of each page");
<del> OptionBuilder.withLongOpt("page-boxes");
<del> options.addOption(OptionBuilder.create('B'));
<del>
<del> OptionBuilder.withDescription("dump the dictionary of each page");
<del> OptionBuilder.withLongOpt("page-dictionaries");
<del> options.addOption(OptionBuilder.create('D'));
<del>
<ide> OptionBuilder.withDescription("dump the token stream of each page");
<ide> OptionBuilder.withLongOpt("page-streams");
<ide> options.addOption(OptionBuilder.create('S'));
<ide>
<ide> OptionBuilder.withDescription("dump the document trailer");
<ide> OptionBuilder.withLongOpt("trailer");
<del> options.addOption(OptionBuilder.create('r'));
<add> options.addOption(OptionBuilder.create('t'));
<ide>
<ide> OptionBuilder.withDescription("produce verbose output");
<ide> OptionBuilder.withLongOpt("verbose");
|
|
Java
|
mit
|
85cf98903ed11961c497ceaf86605f0885e0dfc4
| 0 |
angusws/tcx2nikeplus,jasongdove/tcx2nikeplus,jasongdove/tcx2nikeplus,jasongdove/tcx2nikeplus,angusws/tcx2nikeplus
|
package com.awsmithson.tcx2nikeplus.http;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
// "Borrowed" from http://theskeleton.wordpress.com/2010/07/24/avoiding-the-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-with-httpclient/
public class HttpClientNaiveSsl {
@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
|
src/com/awsmithson/tcx2nikeplus/http/HttpClientNaiveSsl.java
|
package com.awsmithson.tcx2nikeplus.http;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
// "Borrowed" from http://theskeleton.wordpress.com/2010/07/24/avoiding-the-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-with-httpclient/
public class HttpClientNaiveSsl {
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
|
Suppressed deprecation warning on HttpClientNaiveSsl.wrapClient(...).
|
src/com/awsmithson/tcx2nikeplus/http/HttpClientNaiveSsl.java
|
Suppressed deprecation warning on HttpClientNaiveSsl.wrapClient(...).
|
<ide><path>rc/com/awsmithson/tcx2nikeplus/http/HttpClientNaiveSsl.java
<ide> // "Borrowed" from http://theskeleton.wordpress.com/2010/07/24/avoiding-the-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-with-httpclient/
<ide> public class HttpClientNaiveSsl {
<ide>
<del> public static HttpClient wrapClient(HttpClient base) {
<add> @SuppressWarnings("deprecation")
<add> public static HttpClient wrapClient(HttpClient base) {
<ide> try {
<ide> SSLContext ctx = SSLContext.getInstance("TLS");
<ide> X509TrustManager tm = new X509TrustManager() {
|
|
Java
|
apache-2.0
|
406080d06bfa702ef7f943ecd786ba63cf64aad3
| 0 |
freme-project/basic-services,freme-project/basic-services,freme-project/basic-services
|
/**
* Copyright (C) 2015 Agro-Know, Deutsches Forschungszentrum für Künstliche Intelligenz, iMinds,
* Institut für Angewandte Informatik e. V. an der Universität Leipzig,
* Istituto Superiore Mario Boella, Tilde, Vistatec, WRIPL (http://freme-project.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.freme.bservices.controllers.pipelines.core;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.HttpRequestWithBody;
import eu.freme.bservices.internationalization.api.InternationalizationAPI;
import eu.freme.bservices.internationalization.okapi.nif.converter.ConversionException;
import eu.freme.common.conversion.SerializationFormatMapper;
import eu.freme.common.conversion.rdf.RDFConstants;
import eu.freme.common.conversion.rdf.RDFSerializationFormats;
import eu.freme.common.exception.ExternalServiceFailedException;
import eu.freme.common.persistence.model.SerializedRequest;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Gerald Haesendonck
*/
@Component
public class PipelineService {
private final static Logger logger = Logger.getLogger(PipelineService.class);
@Autowired
private RDFSerializationFormats serializationFormats;
@Autowired
private InternationalizationAPI internationalizationApi;
@Autowired
SerializationFormatMapper serializationFormatMapper;
public PipelineService(){
// set timeouts
Unirest.setTimeouts(60*1000, 600*1000);
}
/**
* Performs a chain of requests to other e-services (pipeline).
* @param serializedRequests Requests to different services, serialized in JSON.
* @return The result of the pipeline.
*/
@SuppressWarnings("unused")
public WrappedPipelineResponse chain(final List<SerializedRequest> serializedRequests, String useI18n) throws IOException, UnirestException, ServiceException {
Map<String, Long> executionTime = new LinkedHashMap<>();
// determine mime types of first and last pipeline request
Conversion conversion = null;
boolean roundtrip = false; // true: convert input to NIF, execute pipeline, convert back to input format at the end.
String mime1 = null;
String mime2 = null;
if (serializedRequests.size() > 1) {
mime1 = serializedRequests.get(0).getInputMime(serializationFormatMapper);
mime2 = serializedRequests.get(serializedRequests.size() - 1).getOutputMime(serializationFormatMapper);
if(!(useI18n!=null && useI18n.trim().toLowerCase().equals("false")) && mime1!=null && mime2!=null && mime1.equals(mime2) && internationalizationApi.getRoundtrippingFormats().contains(mime1)){
roundtrip = true;
conversion = new Conversion(internationalizationApi);
try {
long startOfRequest = System.currentTimeMillis();
String nif = conversion.convertToNif(serializedRequests.get(0).getBody(), mime1);
executionTime.put("e-Internationalization ("+mime1+" -> NIF)", (System.currentTimeMillis() - startOfRequest));
serializedRequests.get(0).setBody(nif);
} catch (ConversionException e) {
logger.warn("Could not convert the "+mime1+" contents to NIF. Tying to proceed without converting... Error: ", e);
roundtrip = false;
}
}
}
PipelineResponse lastResponse = new PipelineResponse(serializedRequests.get(0).getBody(), null);
long start = System.currentTimeMillis();
for (int reqNr = 0; reqNr < serializedRequests.size(); reqNr++) {
long startOfRequest = System.currentTimeMillis();
SerializedRequest serializedRequest = serializedRequests.get(reqNr);
try {
if (roundtrip) {
serializedRequest.setInputMime(RDFConstants.TURTLE);
serializedRequest.setOutputMime(RDFConstants.TURTLE);
}
lastResponse = execute(serializedRequest, lastResponse.getBody(), lastResponse.getContentType());
} catch (ServiceException e) {
JSONObject jo = new JSONObject(e.getResponse().getBody());
throw new PipelineFailedException(jo, "The pipeline has failed in step " + reqNr + ", request to URL '" + serializedRequest.getEndpoint()+"'", e.getStatus());
} catch (UnirestException e) {
throw new UnirestException("Request #" + reqNr + " at " + serializedRequest.getEndpoint() + " failed: " + e.getMessage());
} catch (IOException e) {
throw new IOException("Request #" + reqNr + " at " + serializedRequest.getEndpoint() + " failed: " + e.getMessage());
} finally {
long endOfRequest = System.currentTimeMillis();
executionTime.put(serializedRequest.getEndpoint(), (endOfRequest - startOfRequest));
}
}
if (roundtrip) {
long startOfRequest = System.currentTimeMillis();
String output = conversion.convertBack(lastResponse.getBody());
lastResponse = new PipelineResponse(output, mime1);
executionTime.put("e-Internationalization (NIF -> "+mime1+")", (System.currentTimeMillis() - startOfRequest));
}
long end = System.currentTimeMillis();
return new WrappedPipelineResponse(lastResponse, executionTime, (end - start));
}
private PipelineResponse execute(final SerializedRequest request, final String body, final String lastResponseContentType) throws UnirestException, IOException, ServiceException {
switch (request.getMethod()) {
case GET:
throw new UnsupportedOperationException("GET is not supported at this moment.");
default:
HttpRequestWithBody req = Unirest.post(request.getEndpoint());
String inputMime = request.getInputMime(serializationFormatMapper);
if(lastResponseContentType !=null){
if(inputMime == null){
inputMime = lastResponseContentType;
}else{
if(!inputMime.split(";")[0].trim().toLowerCase().equals(lastResponseContentType.split(";")[0].trim().toLowerCase()))
logger.warn("The content type header of the last response is '"+lastResponseContentType+"', but '"+inputMime+"' will be used for the request to '"+request.getEndpoint()+"', because it is defined in the pipeline. This can cause errors at this pipeline step.");
}
}
// clear and set it
if(inputMime!=null){
request.setInputMime(inputMime);
}
if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
req.headers(request.getHeaders());
}
if (request.getParameters() != null && !request.getParameters().isEmpty()) {
req.queryString(request.getParameters()); // encode as POST parameters
}
HttpResponse<String> response;
if (body != null) {
response = req.body(body).asString();
} else {
response = req.asString();
}
if (!HttpStatus.Series.valueOf(response.getStatus()).equals(HttpStatus.Series.SUCCESSFUL)) {
String errorBody = response.getBody();
HttpStatus status = HttpStatus.valueOf(response.getStatus());
if (errorBody == null || errorBody.isEmpty()) {
//throw new ServiceException(new PipelineResponse( "The service failed. No further explanation given by service.", SerializationFormatMapper.PLAINTEXT), status);
throw new ServiceException(new PipelineResponse( "The service \"" + request.getEndpoint() + "\" reported HTTP status " + status.toString() + ". No further explanation given by service.", RDFConstants.RDFSerialization.PLAINTEXT.contentType()), status);
} else {
throw new ServiceException(new PipelineResponse(errorBody, response.getHeaders().getFirst("content-type")), status);
}
}
return new PipelineResponse(response.getBody(), response.getHeaders().getFirst("content-type"));
}
}
}
|
controllers/pipelines/src/main/java/eu/freme/bservices/controllers/pipelines/core/PipelineService.java
|
/**
* Copyright (C) 2015 Agro-Know, Deutsches Forschungszentrum für Künstliche Intelligenz, iMinds,
* Institut für Angewandte Informatik e. V. an der Universität Leipzig,
* Istituto Superiore Mario Boella, Tilde, Vistatec, WRIPL (http://freme-project.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.freme.bservices.controllers.pipelines.core;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.HttpRequestWithBody;
import eu.freme.bservices.internationalization.api.InternationalizationAPI;
import eu.freme.bservices.internationalization.okapi.nif.converter.ConversionException;
import eu.freme.common.conversion.SerializationFormatMapper;
import eu.freme.common.conversion.rdf.RDFConstants;
import eu.freme.common.conversion.rdf.RDFSerializationFormats;
import eu.freme.common.exception.ExternalServiceFailedException;
import eu.freme.common.persistence.model.SerializedRequest;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Gerald Haesendonck
*/
@Component
public class PipelineService {
private final static Logger logger = Logger.getLogger(PipelineService.class);
@Autowired
private RDFSerializationFormats serializationFormats;
@Autowired
private InternationalizationAPI internationalizationApi;
@Autowired
SerializationFormatMapper serializationFormatMapper;
public PipelineService(){
// set timeouts
Unirest.setTimeouts(60*1000, 600*1000);
}
/**
* Performs a chain of requests to other e-services (pipeline).
* @param serializedRequests Requests to different services, serialized in JSON.
* @return The result of the pipeline.
*/
@SuppressWarnings("unused")
public WrappedPipelineResponse chain(final List<SerializedRequest> serializedRequests, String useI18n) throws IOException, UnirestException, ServiceException {
Map<String, Long> executionTime = new LinkedHashMap<>();
// determine mime types of first and last pipeline request
Conversion conversion = null;
boolean roundtrip = false; // true: convert input to NIF, execute pipeline, convert back to input format at the end.
String mime1 = null;
String mime2 = null;
if (serializedRequests.size() > 1) {
mime1 = serializedRequests.get(0).getInputMime(serializationFormatMapper);
mime2 = serializedRequests.get(serializedRequests.size() - 1).getOutputMime(serializationFormatMapper);
if(!(useI18n!=null && useI18n.trim().toLowerCase().equals("false")) && mime1!=null && mime2!=null && mime1.equals(mime2) && internationalizationApi.getRoundtrippingFormats().contains(mime1)){
roundtrip = true;
conversion = new Conversion(internationalizationApi);
try {
long startOfRequest = System.currentTimeMillis();
String nif = conversion.convertToNif(serializedRequests.get(0).getBody(), mime1);
executionTime.put("e-Internationalization ("+mime1+" -> NIF)", (System.currentTimeMillis() - startOfRequest));
serializedRequests.get(0).setBody(nif);
} catch (ConversionException e) {
logger.warn("Could not convert the "+mime1+" contents to NIF. Tying to proceed without converting... Error: ", e);
roundtrip = false;
}
}
}
PipelineResponse lastResponse = new PipelineResponse(serializedRequests.get(0).getBody(), null);
long start = System.currentTimeMillis();
for (int reqNr = 0; reqNr < serializedRequests.size(); reqNr++) {
long startOfRequest = System.currentTimeMillis();
SerializedRequest serializedRequest = serializedRequests.get(reqNr);
try {
if (roundtrip) {
serializedRequest.setInputMime(RDFConstants.TURTLE);
serializedRequest.setOutputMime(RDFConstants.TURTLE);
}
lastResponse = execute(serializedRequest, lastResponse.getBody(), lastResponse.getContentType());
} catch (ServiceException e) {
JSONObject jo = new JSONObject(e.getResponse().getBody());
throw new PipelineFailedException(jo, "The pipeline has failed in step " + reqNr + ", request to URL '" + serializedRequest.getEndpoint()+"'", e.getStatus());
} catch (UnirestException e) {
throw new UnirestException("Request " + reqNr + ": " + e.getMessage());
} catch (IOException e) {
throw new IOException("Request " + reqNr + ": " + e.getMessage());
} finally {
long endOfRequest = System.currentTimeMillis();
executionTime.put(serializedRequest.getEndpoint(), (endOfRequest - startOfRequest));
}
}
if (roundtrip) {
long startOfRequest = System.currentTimeMillis();
String output = conversion.convertBack(lastResponse.getBody());
lastResponse = new PipelineResponse(output, mime1);
executionTime.put("e-Internationalization (NIF -> "+mime1+")", (System.currentTimeMillis() - startOfRequest));
}
long end = System.currentTimeMillis();
return new WrappedPipelineResponse(lastResponse, executionTime, (end - start));
}
private PipelineResponse execute(final SerializedRequest request, final String body, final String lastResponseContentType) throws UnirestException, IOException, ServiceException {
switch (request.getMethod()) {
case GET:
throw new UnsupportedOperationException("GET is not supported at this moment.");
default:
HttpRequestWithBody req = Unirest.post(request.getEndpoint());
String inputMime = request.getInputMime(serializationFormatMapper);
if(lastResponseContentType !=null){
if(inputMime == null){
inputMime = lastResponseContentType;
}else{
if(!inputMime.split(";")[0].trim().toLowerCase().equals(lastResponseContentType.split(";")[0].trim().toLowerCase()))
logger.warn("The content type header of the last response is '"+lastResponseContentType+"', but '"+inputMime+"' will be used for the request to '"+request.getEndpoint()+"', because it is defined in the pipeline. This can cause errors at this pipeline step.");
}
}
// clear and set it
if(inputMime!=null){
request.setInputMime(inputMime);
}
if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
req.headers(request.getHeaders());
}
if (request.getParameters() != null && !request.getParameters().isEmpty()) {
req.queryString(request.getParameters()); // encode as POST parameters
}
HttpResponse<String> response;
if (body != null) {
response = req.body(body).asString();
} else {
response = req.asString();
}
if (!HttpStatus.Series.valueOf(response.getStatus()).equals(HttpStatus.Series.SUCCESSFUL)) {
String errorBody = response.getBody();
HttpStatus status = HttpStatus.valueOf(response.getStatus());
if (errorBody == null || errorBody.isEmpty()) {
//throw new ServiceException(new PipelineResponse( "The service failed. No further explanation given by service.", SerializationFormatMapper.PLAINTEXT), status);
throw new ServiceException(new PipelineResponse( "The service \"" + request.getEndpoint() + "\" reported HTTP status " + status.toString() + ". No further explanation given by service.", RDFConstants.RDFSerialization.PLAINTEXT.contentType()), status);
} else {
throw new ServiceException(new PipelineResponse(errorBody, response.getHeaders().getFirst("content-type")), status);
}
}
return new PipelineResponse(response.getBody(), response.getHeaders().getFirst("content-type"));
}
}
}
|
improve error messages
|
controllers/pipelines/src/main/java/eu/freme/bservices/controllers/pipelines/core/PipelineService.java
|
improve error messages
|
<ide><path>ontrollers/pipelines/src/main/java/eu/freme/bservices/controllers/pipelines/core/PipelineService.java
<ide> JSONObject jo = new JSONObject(e.getResponse().getBody());
<ide> throw new PipelineFailedException(jo, "The pipeline has failed in step " + reqNr + ", request to URL '" + serializedRequest.getEndpoint()+"'", e.getStatus());
<ide> } catch (UnirestException e) {
<del> throw new UnirestException("Request " + reqNr + ": " + e.getMessage());
<add> throw new UnirestException("Request #" + reqNr + " at " + serializedRequest.getEndpoint() + " failed: " + e.getMessage());
<ide> } catch (IOException e) {
<del> throw new IOException("Request " + reqNr + ": " + e.getMessage());
<add> throw new IOException("Request #" + reqNr + " at " + serializedRequest.getEndpoint() + " failed: " + e.getMessage());
<ide> } finally {
<ide> long endOfRequest = System.currentTimeMillis();
<ide> executionTime.put(serializedRequest.getEndpoint(), (endOfRequest - startOfRequest));
|
|
JavaScript
|
mit
|
89864b5eefa6d81b89a4a1f73003b10a7fe51d5f
| 0 |
onsetsu/bloob,onsetsu/bloob,onsetsu/bloob
|
Jiquid.Material = function(folder) {
this.stiffness = 1;
this.restDensity = 1;
this.bulkViscosity = 1 ;
this.elasticity = 0;
this.shearViscosity = 0;
this.meltRate = 0;
this.smoothing = 1;
this.yieldRate = 1;
folder.open();
folder.add(this, "restDensity", 0.1, 5.0);
folder.add(this, "stiffness", 0, 1);
folder.add(this, "bulkViscosity", 0, 1);
folder.add(this, "elasticity", 0, 1);
folder.add(this, "shearViscosity", 0, 1);
folder.add(this, "meltRate", 0, 1);
folder.add(this, "smoothing", 0, 1);
};
Jiquid.Material.prototype.setStiffness = function(stiffness) {
this.stiffness = stiffness;
return this;
};
Jiquid.Material.prototype.setRestDensity = function(restDensity) {
this.restDensity = restDensity;
return this;
};
Jiquid.Material.prototype.setBulkViscosity = function(bulkViscosity) {
this.bulkViscosity = bulkViscosity ;
return this;
};
Jiquid.Material.prototype.setElasticity = function(elasticity) {
this.elasticity = elasticity;
return this;
};
Jiquid.Material.prototype.setShearViscosity = function(shearViscosity) {
this.shearViscosity = shearViscosity;
return this;
};
Jiquid.Material.prototype.setSmoothing = function(smoothing) {
this.smoothing = smoothing;
return this;
};
Jiquid.Material.prototype.setMeltRate = function(meltRate) {
this.meltRate = meltRate;
return this;
};
Jiquid.Material.prototype.setYieldRate = function(yieldRate) {
this.yieldRate = yieldRate;
return this;
};
|
lib/jiquid/material.js
|
Jiquid.Material = function() {
};
Jiquid.Material.prototype.setStiffness = function(stiffness) {
this.stiffness = stiffness;
return this;
};
Jiquid.Material.prototype.setRestDensity = function(restDensity) {
this.restDensity = restDensity;
return this;
};
Jiquid.Material.prototype.setBulkViscosity = function(bulkViscosity) {
this.bulkViscosity = bulkViscosity ;
return this;
};
Jiquid.Material.prototype.setElasticity = function(elasticity) {
this.elasticity = elasticity;
return this;
};
Jiquid.Material.prototype.setViscosity = function(viscosity) {
this.viscosity = viscosity;
return this;
};
Jiquid.Material.prototype.setSmoothing = function(smoothing) {
this.smoothing = smoothing;
return this;
};
Jiquid.Material.prototype.setYieldRate = function(yieldRate) {
this.yieldRate = yieldRate;
return this;
};
|
adjusted Material constructor to take dat.Gui folder as parameter
|
lib/jiquid/material.js
|
adjusted Material constructor to take dat.Gui folder as parameter
|
<ide><path>ib/jiquid/material.js
<del>Jiquid.Material = function() {
<del>
<add>Jiquid.Material = function(folder) {
<add> this.stiffness = 1;
<add> this.restDensity = 1;
<add> this.bulkViscosity = 1 ;
<add> this.elasticity = 0;
<add> this.shearViscosity = 0;
<add> this.meltRate = 0;
<add> this.smoothing = 1;
<add> this.yieldRate = 1;
<add>
<add> folder.open();
<add> folder.add(this, "restDensity", 0.1, 5.0);
<add> folder.add(this, "stiffness", 0, 1);
<add> folder.add(this, "bulkViscosity", 0, 1);
<add> folder.add(this, "elasticity", 0, 1);
<add> folder.add(this, "shearViscosity", 0, 1);
<add> folder.add(this, "meltRate", 0, 1);
<add> folder.add(this, "smoothing", 0, 1);
<ide> };
<ide>
<ide> Jiquid.Material.prototype.setStiffness = function(stiffness) {
<ide> return this;
<ide> };
<ide>
<del>Jiquid.Material.prototype.setViscosity = function(viscosity) {
<del> this.viscosity = viscosity;
<add>Jiquid.Material.prototype.setShearViscosity = function(shearViscosity) {
<add> this.shearViscosity = shearViscosity;
<ide>
<ide> return this;
<ide> };
<ide> return this;
<ide> };
<ide>
<add>Jiquid.Material.prototype.setMeltRate = function(meltRate) {
<add> this.meltRate = meltRate;
<add>
<add> return this;
<add>};
<add>
<ide> Jiquid.Material.prototype.setYieldRate = function(yieldRate) {
<ide> this.yieldRate = yieldRate;
<ide>
|
|
Java
|
bsd-2-clause
|
d7be9d97df342868f6146f59929ee8831789709e
| 0 |
padrig64/ValidationFramework
|
/*
* Copyright (c) 2012, Patrick Moawad
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.validationframework.base.rule.bool;
import com.github.validationframework.api.rule.Rule;
import com.github.validationframework.base.transform.OrBooleanAggregator;
import com.github.validationframework.base.transform.Transformer;
import java.util.Collection;
/**
* Rule validating a collection of boolean values using the boolean OR operator.
*
* @see AndBooleanRule
*/
public class OrBooleanRule implements Rule<Collection<Boolean>, Boolean> {
/**
* Default boolean result for empty or null collections.
*/
public static final boolean DEFAULT_EMPTY_COLLECTION_VALID = OrBooleanAggregator.DEFAULT_EMPTY_COLLECTION_VALUE;
/**
* Default boolean value for null elements in the collections.
*/
public static final boolean DEFAULT_NULL_ELEMENT_VALID = OrBooleanAggregator.DEFAULT_NULL_ELEMENT_VALUE;
/**
* Boolean aggregator using the OR operator.
*
* @see OrBooleanAggregator
*/
private final Transformer<Collection<Boolean>, Boolean> aggregator;
/**
* Default constructor using default results for empty collections and null elements.
*/
public OrBooleanRule() {
this(DEFAULT_EMPTY_COLLECTION_VALID, DEFAULT_NULL_ELEMENT_VALID);
}
/**
* Constructor specifying the results for empty and null collections, and null elements.
*
* @param emptyCollectionValid Result for empty and null collections.
* @param nullElementValid Boolean value for null elements.
*/
public OrBooleanRule(final boolean emptyCollectionValid, final boolean nullElementValid) {
aggregator = new OrBooleanAggregator(emptyCollectionValid, nullElementValid);
}
/**
* @see Rule#validate(Object)
*/
@Override
public Boolean validate(final Collection<Boolean> elements) {
return aggregator.transform(elements);
}
}
|
validationframework-core/src/main/java/com/github/validationframework/base/rule/bool/OrBooleanRule.java
|
/*
* Copyright (c) 2012, Patrick Moawad
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.validationframework.base.rule.bool;
import com.github.validationframework.api.rule.Rule;
import com.github.validationframework.base.transform.AndBooleanAggregator;
import com.github.validationframework.base.transform.OrBooleanAggregator;
import com.github.validationframework.base.transform.Transformer;
import java.util.Collection;
/**
* Rule validating a collection of boolean values using the boolean AND operator.
*
* @see AndBooleanRule
*/
public class OrBooleanRule implements Rule<Collection<Boolean>, Boolean> {
/**
* Default boolean result for empty or null collections.
*/
public static final boolean DEFAULT_EMPTY_COLLECTION_VALID = OrBooleanAggregator.DEFAULT_EMPTY_COLLECTION_VALUE;
/**
* Default boolean value for null elements in the collections.
*/
public static final boolean DEFAULT_NULL_ELEMENT_VALID = OrBooleanAggregator.DEFAULT_NULL_ELEMENT_VALUE;
/**
* Boolean aggregator using the OR operator.
*
* @see OrBooleanAggregator
*/
private final Transformer<Collection<Boolean>, Boolean> aggregator;
/**
* Default constructor using default results for empty collections and null elements.
*/
public OrBooleanRule() {
this(DEFAULT_EMPTY_COLLECTION_VALID, DEFAULT_NULL_ELEMENT_VALID);
}
/**
* Constructor specifying the results for empty and null collections, and null elements.
*
* @param emptyCollectionValid Result for empty and null collections.
* @param nullElementValid Boolean value for null elements.
*/
public OrBooleanRule(final boolean emptyCollectionValid, final boolean nullElementValid) {
aggregator = new AndBooleanAggregator(emptyCollectionValid, nullElementValid);
}
/**
* @see Rule#validate(Object)
*/
@Override
public Boolean validate(final Collection<Boolean> elements) {
return aggregator.transform(elements);
}
}
|
Fixed bug in OrBooleanRule
|
validationframework-core/src/main/java/com/github/validationframework/base/rule/bool/OrBooleanRule.java
|
Fixed bug in OrBooleanRule
|
<ide><path>alidationframework-core/src/main/java/com/github/validationframework/base/rule/bool/OrBooleanRule.java
<ide> package com.github.validationframework.base.rule.bool;
<ide>
<ide> import com.github.validationframework.api.rule.Rule;
<del>import com.github.validationframework.base.transform.AndBooleanAggregator;
<ide> import com.github.validationframework.base.transform.OrBooleanAggregator;
<ide> import com.github.validationframework.base.transform.Transformer;
<ide> import java.util.Collection;
<ide>
<ide> /**
<del> * Rule validating a collection of boolean values using the boolean AND operator.
<add> * Rule validating a collection of boolean values using the boolean OR operator.
<ide> *
<ide> * @see AndBooleanRule
<ide> */
<ide> * @param nullElementValid Boolean value for null elements.
<ide> */
<ide> public OrBooleanRule(final boolean emptyCollectionValid, final boolean nullElementValid) {
<del> aggregator = new AndBooleanAggregator(emptyCollectionValid, nullElementValid);
<add> aggregator = new OrBooleanAggregator(emptyCollectionValid, nullElementValid);
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
9e12bfcb65b656f692823e0ad1d2ee0255cc8fa6
| 0 |
bimargulies/org.ops4j.pax.exam2,bimargulies/org.ops4j.pax.exam2,ops4j/org.ops4j.pax.exam2,The-Alchemist/org.ops4j.pax.exam2,koma-akdb/org.ops4j.pax.exam2,koma-akdb/org.ops4j.pax.exam2,The-Alchemist/org.ops4j.pax.exam2,ops4j/org.ops4j.pax.exam2
|
/*
* Copyright 2008 Toni Menzel.
* Copyright 2008 Alin Dreghiciu.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.pax.exam.options.extra;
import static org.ops4j.lang.NullArgumentException.validateNotEmpty;
/**
* {@link RepositoryOption} implementation.
*
* @author Toni Menzel (tonit)
* @author Alin Dreghiciu ([email protected])
* @since 0.3.0, December 19, 2008
*/
public class RepositoryOptionImpl implements RepositoryOption {
/**
* Repository url (cannot be null or empty).
*/
private final String repositoryUrl;
/**
* Marks repository as allowing snapshots.
*/
private boolean allowSnapshots;
/**
* MArks repository as allowing releases.
*/
private boolean allowReleases;
/**
* Defines repository identifier to be referenced in Maven settings.
*/
private String id;
/**
* Constructor.
*
* @param repositoryUrl
* repository url (cannot be null or empty)
*
* @throws IllegalArgumentException
* - If repository url is null or empty
*/
public RepositoryOptionImpl(final String repositoryUrl) {
validateNotEmpty(repositoryUrl, "Repository URL");
this.repositoryUrl = repositoryUrl;
allowSnapshots = false;
allowReleases = true;
}
public RepositoryOptionImpl allowSnapshots() {
allowSnapshots = true;
return this;
}
public RepositoryOptionImpl disableReleases() {
allowReleases = false;
return this;
}
public RepositoryOption id(String _id) {
this.id = _id;
return this;
}
/**
* Returns the full repository url.
*
* @return the full repository as given plus eventual snapshot/release tags (cannot be null or
* empty)
*
* @throws IllegalStateException
* - if both snapshots and releases are not allowed
*/
public String getRepository() {
if (!allowReleases && !allowSnapshots) {
throw new IllegalStateException(
"Does not make sense to disallow both releases and snapshots.");
}
// start with a plus to append default repositories from settings.xml and Maven Cental
// to the list of repositories defined by options
final StringBuilder url = new StringBuilder("+");
url.append(this.repositoryUrl);
if (allowSnapshots) {
url.append("@snapshots");
}
if (!allowReleases) {
url.append("@noreleases");
}
if (id != null) {
url.append("@id=");
url.append(id);
}
return url.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("RepositoryOptionImpl");
sb.append("{url=").append(getRepository());
sb.append('}');
return sb.toString();
}
public String getValue() {
return getRepository();
}
}
|
core/pax-exam/src/main/java/org/ops4j/pax/exam/options/extra/RepositoryOptionImpl.java
|
/*
* Copyright 2008 Toni Menzel.
* Copyright 2008 Alin Dreghiciu.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.pax.exam.options.extra;
import static org.ops4j.lang.NullArgumentException.validateNotEmpty;
/**
* {@link RepositoryOption} implementation.
*
* @author Toni Menzel (tonit)
* @author Alin Dreghiciu ([email protected])
* @since 0.3.0, December 19, 2008
*/
public class RepositoryOptionImpl implements RepositoryOption {
/**
* Repository url (cannot be null or empty).
*/
private final String repositoryUrl;
/**
* Marks repository as allowing snapshots.
*/
private boolean allowSnapshots;
/**
* MArks repository as allowing releases.
*/
private boolean allowReleases;
/**
* Defines repository identifier to be referenced in Maven settings.
*/
private String id;
/**
* Constructor.
*
* @param repositoryUrl
* repository url (cannot be null or empty)
*
* @throws IllegalArgumentException
* - If repository url is null or empty
*/
public RepositoryOptionImpl(final String repositoryUrl) {
validateNotEmpty(repositoryUrl, "Repository URL");
this.repositoryUrl = repositoryUrl;
allowSnapshots = false;
allowReleases = true;
}
public RepositoryOptionImpl allowSnapshots() {
allowSnapshots = true;
return this;
}
public RepositoryOptionImpl disableReleases() {
allowReleases = false;
return this;
}
public RepositoryOption id(String _id) {
this.id = _id;
return this;
}
/**
* Returns the full repository url.
*
* @return the full repository as given plus eventual snapshot/release tags (cannot be null or
* empty)
*
* @throws IllegalStateException
* - if both snapshots and releases are not allowed
*/
public String getRepository() {
if (!allowReleases && !allowSnapshots) {
throw new IllegalStateException(
"Does not make sense to disallow both releases and snapshots.");
}
final StringBuilder url = new StringBuilder();
url.append(this.repositoryUrl);
if (allowSnapshots) {
url.append("@snapshots");
}
if (!allowReleases) {
url.append("@noreleases");
}
if (id != null) {
url.append("@id=");
url.append(id);
}
return url.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("RepositoryOptionImpl");
sb.append("{url=").append(getRepository());
sb.append('}');
return sb.toString();
}
public String getValue() {
return getRepository();
}
}
|
[PAXEXAM-522] repository() should not exclude default repositories
|
core/pax-exam/src/main/java/org/ops4j/pax/exam/options/extra/RepositoryOptionImpl.java
|
[PAXEXAM-522] repository() should not exclude default repositories
|
<ide><path>ore/pax-exam/src/main/java/org/ops4j/pax/exam/options/extra/RepositoryOptionImpl.java
<ide> throw new IllegalStateException(
<ide> "Does not make sense to disallow both releases and snapshots.");
<ide> }
<del> final StringBuilder url = new StringBuilder();
<add> // start with a plus to append default repositories from settings.xml and Maven Cental
<add> // to the list of repositories defined by options
<add> final StringBuilder url = new StringBuilder("+");
<ide> url.append(this.repositoryUrl);
<ide> if (allowSnapshots) {
<ide> url.append("@snapshots");
|
|
Java
|
lgpl-2.1
|
error: pathspec 'src/ch/unizh/ini/caviar/eventprocessing/filter/Info.java' did not match any file(s) known to git
|
d68d867e693bca01b1a472fb126160166faf2600
| 1 |
viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer
|
/*
* Info.java
*
* Created on September 28, 2007, 7:29 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*
*
*Copyright September 28, 2007 Tobi Delbruck, Inst. of Neuroinformatics, UNI-ETH Zurich
*/
package ch.unizh.ini.caviar.eventprocessing.filter;
import ch.unizh.ini.caviar.aemonitor.AEConstants;
import ch.unizh.ini.caviar.chip.*;
import ch.unizh.ini.caviar.event.EventPacket;
import ch.unizh.ini.caviar.eventio.AEDataFile;
import ch.unizh.ini.caviar.eventio.AEFileInputStream;
import ch.unizh.ini.caviar.eventio.AEInputStreamInterface;
import ch.unizh.ini.caviar.eventprocessing.*;
import ch.unizh.ini.caviar.graphics.AEPlayerInterface;
import ch.unizh.ini.caviar.graphics.AEViewer;
import ch.unizh.ini.caviar.graphics.FrameAnnotater;
import com.sun.opengl.util.*;
import java.awt.Graphics2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.io.File;
import java.text.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.media.opengl.*;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.glu.*;
/**
* Annotates the rendered data stream canvas
with additional information like a
clock with absolute time, a bar showing instantaneous activity rate,
a graph showing historical activity over the file, etc. These are enabled by flags of the filter.
* @author tobi
*/
public class Info extends EventFilter2D implements FrameAnnotater, PropertyChangeListener {
DateFormat timeFormat=DateFormat.getTimeInstance();
DateFormat dateFormat=DateFormat.getDateInstance();
Date dateInstance=new Date();
Calendar calendar=Calendar.getInstance();
private boolean analogClock=getPrefs().getBoolean("Into.analogClock",true);
{setPropertyTooltip("analogClock","show normal circular clock");}
private boolean digitalClock=getPrefs().getBoolean("Into.digitalClock",true);
{setPropertyTooltip("digitalClock","show digital clock");}
private boolean date=getPrefs().getBoolean("Into.date",true);
{setPropertyTooltip("date","show date");}
private boolean absoluteTime=getPrefs().getBoolean("Info.absoluteTime",true);
{setPropertyTooltip("absoluteTime","enable to show absolute time, disable to show timestmp time (usually relative to start of recording");}
private long dataFileTimestampStartTimeMs=0;
private long wrappingCorrectionMs=0;
private long absoluteStartTime=0;
private long relativeTimeInFileMs=0;
/** Creates a new instance of Info for the chip
@param chip the chip object
*/
public Info(AEChip chip) {
super(chip);
calendar.setLenient(true); // speed up calendar
}
public EventPacket<?> filterPacket(EventPacket<?> in) {
checkPropSupport();
if(in!=null && in.getSize()>0){
relativeTimeInFileMs=(in.getLastTimestamp()-dataFileTimestampStartTimeMs)/1000;
}
return in;
}
boolean addedSupport=false;
void checkPropSupport(){
if(addedSupport) return;
AEPlayerInterface player=chip.getAeViewer().getAePlayer();
if(player!=null){
AEFileInputStream in=(AEFileInputStream)(player.getAEInputStream());
if(in!=null){
in.getSupport().addPropertyChangeListener(this);
dataFileTimestampStartTimeMs=in.getFirstTimestamp();
log.info("added ourselves for PropertyChangeEvents from "+in);
addedSupport=true;
}
}
}
public Object getFilterState() {
return null;
}
public void resetFilter() {
}
public void initFilter() {
}
public void annotate(float[][][] frame) {
}
public void annotate(Graphics2D g) {
}
GLU glu=null;
GLUquadric wheelQuad;
public void annotate(GLAutoDrawable drawable) {
if(!isAnnotationEnabled()) return;
GL gl=drawable.getGL();
// gl.glColor3f(1,1,1);
// gl.glRasterPos3f(0,0,0);
// if(rewound){
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_12, "rewound");
// rewound=false;
// }else{
// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_12, String.format("%.3f",timestampTimeSeconds()));
// }
long t=relativeTimeInFileMs+wrappingCorrectionMs;
if(absoluteTime) t+=absoluteStartTime;
drawClock(gl,t);
}
private volatile boolean rewound=false;
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("rewind")){
log.info("rewind PropertyChangeEvent received by "+this+" from "+evt.getSource());
rewound=true;
wrappingCorrectionMs=0;
absoluteStartTime=getAbsoluteStartingTimeMsFromFile();
}else if(evt.getPropertyName().equals("wrappedTime")){
wrappingCorrectionMs+=(long)(1L<<32L)/1000; // fixme
}else if(evt.getPropertyName().equals("init")){
absoluteStartTime=getAbsoluteStartingTimeMsFromFile();
}
}
/** @return start of logging time in ms, i.e., in "java" time, since 1970 */
private long getAbsoluteStartingTimeMsFromFile(){
File f=chip.getAeViewer().getCurrentFile();
if(f==null){
return 0;
}
try{
String fn=f.getName();
String dateStr=fn.substring(fn.indexOf('-')+1); // guess that datestamp is right after first - which follows Chip classname
Date date=AEViewer.loggingFilenameDateFormat.parse(dateStr);
return date.getTime();
}catch(Exception e){
log.warning(e.toString());
return 0;
}
}
private void drawClock(GL gl, long t){
final int radius=20, hourLen=10, minLen=19, secLen=7;
calendar.setTimeInMillis(t);
gl.glColor3f(1,1,1);
if(analogClock){
// draw clock circle
if(glu==null) glu=new GLU();
if(wheelQuad==null) wheelQuad = glu.gluNewQuadric();
gl.glPushMatrix();
{
gl.glTranslatef(radius+2, radius+6,0); // clock center
glu.gluQuadricDrawStyle(wheelQuad,GLU.GLU_FILL);
glu.gluDisk(wheelQuad,radius,radius+0.5f,24,1);
// draw hour, minute, second hands
// each hand has x,y components related to periodicity of clock and time
gl.glColor3f(1,1,1);
// second hand
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0,0);
double a=2*Math.PI*calendar.get(Calendar.SECOND)/60;
float x=secLen*(float)Math.sin(a);
float y=secLen*(float)Math.cos(a);
gl.glVertex2f(x,y);
gl.glEnd();
// minute hand
gl.glLineWidth(4f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0,0);
int minute=calendar.get(Calendar.MINUTE);
a=2*Math.PI*minute/60;
x=minLen*(float)Math.sin(a);
y=minLen*(float)Math.cos(a); // y= + when min=0, pointing at noon/midnight on clock
gl.glVertex2f(x,y);
gl.glEnd();
// hour hand
gl.glLineWidth(6f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0,0);
a=2*Math.PI*(calendar.get(Calendar.HOUR)+minute/60.0)/12; // a=0 for midnight, a=2*3/12*pi=pi/2 for 3am/pm, etc
x=hourLen*(float)Math.sin(a);
y=hourLen*(float)Math.cos(a);
gl.glVertex2f(x,y);
gl.glEnd();
}
gl.glPopMatrix();
}
if(digitalClock){
gl.glPushMatrix();
gl.glRasterPos3f(0,0,0);
GLUT glut=chip.getCanvas().getGlut();
dateInstance.setTime((long)t);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18,timeFormat.format(t));
if(date){
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18,dateFormat.format(t));
}
gl.glPopMatrix();
}
}
public boolean isAnalogClock() {
return analogClock;
}
public void setAnalogClock(boolean analogClock) {
this.analogClock = analogClock;
getPrefs().putBoolean("Info.analogClock",analogClock);
}
public boolean isDigitalClock() {
return digitalClock;
}
public void setDigitalClock(boolean digitalClock) {
this.digitalClock = digitalClock;
getPrefs().putBoolean("Info.digitalClock",digitalClock);
}
public boolean isDate() {
return date;
}
public void setDate(boolean date) {
this.date = date;
getPrefs().putBoolean("Info.date",date);
}
public boolean isAbsoluteTime() {
return absoluteTime;
}
public void setAbsoluteTime(boolean absoluteTime) {
this.absoluteTime = absoluteTime;
getPrefs().putBoolean("Info.absoluteTime",absoluteTime);
}
}
|
src/ch/unizh/ini/caviar/eventprocessing/filter/Info.java
|
initial version (functional) of a new type of filter that just annotates the ChipCanvas to show a clock with absolute file time.
you still need to rewind the file to get the absolute time which is parsed from the filename.
git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@281 b7f4320f-462c-0410-a916-d9f35bb82d52
|
src/ch/unizh/ini/caviar/eventprocessing/filter/Info.java
|
initial version (functional) of a new type of filter that just annotates the ChipCanvas to show a clock with absolute file time. you still need to rewind the file to get the absolute time which is parsed from the filename.
|
<ide><path>rc/ch/unizh/ini/caviar/eventprocessing/filter/Info.java
<add>/*
<add> * Info.java
<add> *
<add> * Created on September 28, 2007, 7:29 PM
<add> *
<add> * To change this template, choose Tools | Template Manager
<add> * and open the template in the editor.
<add> *
<add> *
<add> *Copyright September 28, 2007 Tobi Delbruck, Inst. of Neuroinformatics, UNI-ETH Zurich
<add> */
<add>
<add>package ch.unizh.ini.caviar.eventprocessing.filter;
<add>
<add>import ch.unizh.ini.caviar.aemonitor.AEConstants;
<add>import ch.unizh.ini.caviar.chip.*;
<add>import ch.unizh.ini.caviar.event.EventPacket;
<add>import ch.unizh.ini.caviar.eventio.AEDataFile;
<add>import ch.unizh.ini.caviar.eventio.AEFileInputStream;
<add>import ch.unizh.ini.caviar.eventio.AEInputStreamInterface;
<add>import ch.unizh.ini.caviar.eventprocessing.*;
<add>import ch.unizh.ini.caviar.graphics.AEPlayerInterface;
<add>import ch.unizh.ini.caviar.graphics.AEViewer;
<add>import ch.unizh.ini.caviar.graphics.FrameAnnotater;
<add>import com.sun.opengl.util.*;
<add>import java.awt.Graphics2D;
<add>import java.beans.PropertyChangeEvent;
<add>import java.beans.PropertyChangeListener;
<add>import java.io.*;
<add>import java.io.File;
<add>import java.text.*;
<add>import java.text.SimpleDateFormat;
<add>import java.util.*;
<add>import javax.media.opengl.*;
<add>import javax.media.opengl.GLAutoDrawable;
<add>import javax.media.opengl.glu.*;
<add>
<add>/**
<add> * Annotates the rendered data stream canvas
<add> with additional information like a
<add> clock with absolute time, a bar showing instantaneous activity rate,
<add> a graph showing historical activity over the file, etc. These are enabled by flags of the filter.
<add> * @author tobi
<add> */
<add>public class Info extends EventFilter2D implements FrameAnnotater, PropertyChangeListener {
<add>
<add> DateFormat timeFormat=DateFormat.getTimeInstance();
<add> DateFormat dateFormat=DateFormat.getDateInstance();
<add> Date dateInstance=new Date();
<add> Calendar calendar=Calendar.getInstance();
<add>
<add> private boolean analogClock=getPrefs().getBoolean("Into.analogClock",true);
<add> {setPropertyTooltip("analogClock","show normal circular clock");}
<add> private boolean digitalClock=getPrefs().getBoolean("Into.digitalClock",true);
<add> {setPropertyTooltip("digitalClock","show digital clock");}
<add> private boolean date=getPrefs().getBoolean("Into.date",true);
<add> {setPropertyTooltip("date","show date");}
<add> private boolean absoluteTime=getPrefs().getBoolean("Info.absoluteTime",true);
<add> {setPropertyTooltip("absoluteTime","enable to show absolute time, disable to show timestmp time (usually relative to start of recording");}
<add>
<add> private long dataFileTimestampStartTimeMs=0;
<add> private long wrappingCorrectionMs=0;
<add> private long absoluteStartTime=0;
<add> private long relativeTimeInFileMs=0;
<add>
<add> /** Creates a new instance of Info for the chip
<add> @param chip the chip object
<add> */
<add> public Info(AEChip chip) {
<add> super(chip);
<add> calendar.setLenient(true); // speed up calendar
<add> }
<add>
<add> public EventPacket<?> filterPacket(EventPacket<?> in) {
<add> checkPropSupport();
<add> if(in!=null && in.getSize()>0){
<add> relativeTimeInFileMs=(in.getLastTimestamp()-dataFileTimestampStartTimeMs)/1000;
<add> }
<add> return in;
<add> }
<add> boolean addedSupport=false;
<add>
<add> void checkPropSupport(){
<add> if(addedSupport) return;
<add> AEPlayerInterface player=chip.getAeViewer().getAePlayer();
<add> if(player!=null){
<add> AEFileInputStream in=(AEFileInputStream)(player.getAEInputStream());
<add> if(in!=null){
<add> in.getSupport().addPropertyChangeListener(this);
<add> dataFileTimestampStartTimeMs=in.getFirstTimestamp();
<add> log.info("added ourselves for PropertyChangeEvents from "+in);
<add> addedSupport=true;
<add> }
<add> }
<add> }
<add>
<add> public Object getFilterState() {
<add> return null;
<add> }
<add>
<add> public void resetFilter() {
<add> }
<add>
<add> public void initFilter() {
<add> }
<add>
<add> public void annotate(float[][][] frame) {
<add> }
<add>
<add> public void annotate(Graphics2D g) {
<add> }
<add>
<add> GLU glu=null;
<add> GLUquadric wheelQuad;
<add>
<add> public void annotate(GLAutoDrawable drawable) {
<add> if(!isAnnotationEnabled()) return;
<add> GL gl=drawable.getGL();
<add>// gl.glColor3f(1,1,1);
<add>// gl.glRasterPos3f(0,0,0);
<add>// if(rewound){
<add>// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_12, "rewound");
<add>// rewound=false;
<add>// }else{
<add>// chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_12, String.format("%.3f",timestampTimeSeconds()));
<add>// }
<add> long t=relativeTimeInFileMs+wrappingCorrectionMs;
<add> if(absoluteTime) t+=absoluteStartTime;
<add> drawClock(gl,t);
<add> }
<add>
<add> private volatile boolean rewound=false;
<add>
<add> public void propertyChange(PropertyChangeEvent evt) {
<add> if(evt.getPropertyName().equals("rewind")){
<add> log.info("rewind PropertyChangeEvent received by "+this+" from "+evt.getSource());
<add> rewound=true;
<add> wrappingCorrectionMs=0;
<add> absoluteStartTime=getAbsoluteStartingTimeMsFromFile();
<add> }else if(evt.getPropertyName().equals("wrappedTime")){
<add> wrappingCorrectionMs+=(long)(1L<<32L)/1000; // fixme
<add> }else if(evt.getPropertyName().equals("init")){
<add> absoluteStartTime=getAbsoluteStartingTimeMsFromFile();
<add> }
<add> }
<add>
<add> /** @return start of logging time in ms, i.e., in "java" time, since 1970 */
<add> private long getAbsoluteStartingTimeMsFromFile(){
<add> File f=chip.getAeViewer().getCurrentFile();
<add> if(f==null){
<add> return 0;
<add> }
<add> try{
<add> String fn=f.getName();
<add> String dateStr=fn.substring(fn.indexOf('-')+1); // guess that datestamp is right after first - which follows Chip classname
<add> Date date=AEViewer.loggingFilenameDateFormat.parse(dateStr);
<add> return date.getTime();
<add> }catch(Exception e){
<add> log.warning(e.toString());
<add> return 0;
<add> }
<add> }
<add>
<add> private void drawClock(GL gl, long t){
<add> final int radius=20, hourLen=10, minLen=19, secLen=7;
<add> calendar.setTimeInMillis(t);
<add>
<add> gl.glColor3f(1,1,1);
<add> if(analogClock){
<add> // draw clock circle
<add> if(glu==null) glu=new GLU();
<add> if(wheelQuad==null) wheelQuad = glu.gluNewQuadric();
<add> gl.glPushMatrix();
<add> {
<add> gl.glTranslatef(radius+2, radius+6,0); // clock center
<add> glu.gluQuadricDrawStyle(wheelQuad,GLU.GLU_FILL);
<add> glu.gluDisk(wheelQuad,radius,radius+0.5f,24,1);
<add>
<add> // draw hour, minute, second hands
<add> // each hand has x,y components related to periodicity of clock and time
<add>
<add> gl.glColor3f(1,1,1);
<add>
<add> // second hand
<add> gl.glLineWidth(2f);
<add> gl.glBegin(GL.GL_LINES);
<add> gl.glVertex2f(0,0);
<add> double a=2*Math.PI*calendar.get(Calendar.SECOND)/60;
<add> float x=secLen*(float)Math.sin(a);
<add> float y=secLen*(float)Math.cos(a);
<add> gl.glVertex2f(x,y);
<add> gl.glEnd();
<add>
<add> // minute hand
<add> gl.glLineWidth(4f);
<add> gl.glBegin(GL.GL_LINES);
<add> gl.glVertex2f(0,0);
<add> int minute=calendar.get(Calendar.MINUTE);
<add> a=2*Math.PI*minute/60;
<add> x=minLen*(float)Math.sin(a);
<add> y=minLen*(float)Math.cos(a); // y= + when min=0, pointing at noon/midnight on clock
<add> gl.glVertex2f(x,y);
<add> gl.glEnd();
<add>
<add> // hour hand
<add> gl.glLineWidth(6f);
<add> gl.glBegin(GL.GL_LINES);
<add> gl.glVertex2f(0,0);
<add> a=2*Math.PI*(calendar.get(Calendar.HOUR)+minute/60.0)/12; // a=0 for midnight, a=2*3/12*pi=pi/2 for 3am/pm, etc
<add> x=hourLen*(float)Math.sin(a);
<add> y=hourLen*(float)Math.cos(a);
<add> gl.glVertex2f(x,y);
<add> gl.glEnd();
<add> }
<add> gl.glPopMatrix();
<add> }
<add>
<add> if(digitalClock){
<add> gl.glPushMatrix();
<add> gl.glRasterPos3f(0,0,0);
<add> GLUT glut=chip.getCanvas().getGlut();
<add> dateInstance.setTime((long)t);
<add> glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18,timeFormat.format(t));
<add> if(date){
<add> glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18,dateFormat.format(t));
<add> }
<add> gl.glPopMatrix();
<add> }
<add> }
<add>
<add> public boolean isAnalogClock() {
<add> return analogClock;
<add> }
<add>
<add> public void setAnalogClock(boolean analogClock) {
<add> this.analogClock = analogClock;
<add> getPrefs().putBoolean("Info.analogClock",analogClock);
<add> }
<add>
<add> public boolean isDigitalClock() {
<add> return digitalClock;
<add> }
<add>
<add> public void setDigitalClock(boolean digitalClock) {
<add> this.digitalClock = digitalClock;
<add> getPrefs().putBoolean("Info.digitalClock",digitalClock);
<add> }
<add>
<add> public boolean isDate() {
<add> return date;
<add> }
<add>
<add> public void setDate(boolean date) {
<add> this.date = date;
<add> getPrefs().putBoolean("Info.date",date);
<add> }
<add>
<add> public boolean isAbsoluteTime() {
<add> return absoluteTime;
<add> }
<add>
<add> public void setAbsoluteTime(boolean absoluteTime) {
<add> this.absoluteTime = absoluteTime;
<add> getPrefs().putBoolean("Info.absoluteTime",absoluteTime);
<add> }
<add>
<add>}
|
|
Java
|
bsd-2-clause
|
87d6e3aff8b24395945254ad604d55e3c4588d81
| 0 |
archiecobbs/com4j,archiecobbs/com4j,archiecobbs/com4j,archiecobbs/com4j,kohsuke/com4j,kohsuke/com4j,kohsuke/com4j,kohsuke/com4j
|
import com4j.COM4J;
import com4j.Holder;
/**
* Test program.
*
* @author Kohsuke Kawaguchi ([email protected])
*/
public class Main {
public static void main(String[] args) {
IWshShell wsh = COM4J.createInstance(IWshShell.class,"WScript.Shell");
String s = wsh.ExpandEnvironmentStrings("%WinDir%");
// Holder<String> h = new Holder<String>();
// wsh.ExpandEnvironmentStrings("%WinDir%",h);
// String s = h.value;
System.out.println(s);
wsh.dispose();
}
}
|
test/src/test/java/Main.java
|
import com4j.COM4J;
import com4j.Holder;
/**
* Test program.
*
* @author Kohsuke Kawaguchi ([email protected])
*/
public class Main {
public static void main(String[] args) {
IWshShell wsh = COM4J.createInstance(IWshShell.class,"WScript.Shell");
String s = wsh.ExpandEnvironmentStrings("%WinDir%");
// Holder<String> h = new Holder<String>();
// wsh.ExpandEnvironmentStrings("%WinDir%",h);
// String s = h.value;
System.out.println(s);
COM4J.dispose(wsh);
}
}
|
updated to the modern com4j
|
test/src/test/java/Main.java
|
updated to the modern com4j
|
<ide><path>est/src/test/java/Main.java
<ide> // wsh.ExpandEnvironmentStrings("%WinDir%",h);
<ide> // String s = h.value;
<ide> System.out.println(s);
<del> COM4J.dispose(wsh);
<add> wsh.dispose();
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
82ca3a09ca04a71fd12f35508dfb59c96e88cce6
| 0 |
DennisRippinger/spade,DennisRippinger/spade,DennisRippinger/spade,DennisRippinger/spade
|
/**
* Copyright 2014 Dennis Rippinger
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.interactivesystems.spade.similarity;
import info.interactivesystems.spade.dao.NilsimsaSimilarityDao;
import info.interactivesystems.spade.dao.service.ReviewContentService;
import info.interactivesystems.spade.entities.NilsimsaSimilarity;
import info.interactivesystems.spade.entities.Review;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* The Class NilsimsaSimilarityCalculator.
*
* @author Dennis Rippinger
*/
@Slf4j
@Component
public class NilsimsaSimilarityCalculator {
@Resource
private NilsimsaSimilarityDao nisimsaDao;
@Resource
private ReviewContentService service;
@Resource
private NilsimsaHash hash;
/**
* Calculate similarity between unique reviews.
*/
public void calculateSimilarityBetweenUniqueReviews(String category) {
List<Review> uniqueReviews = service.findReviewsByCategory(category);
Integer start = 0;
Integer counter = 0;
log.info("Size of '{}': '{}'", category, uniqueReviews.size());
for (Review outerReview : uniqueReviews) {
for (Integer current = start; current < uniqueReviews.size(); current++) {
Review innerReview = uniqueReviews.get(current);
if (innerReview.getId().equals(outerReview.getId())) {
continue;
}
Integer sameBits = hash.compare(outerReview.getNilsimsa(), innerReview.getNilsimsa());
Double percentage = sameBits / 128.0;
if (percentage >= 0.70) {
NilsimsaSimilarity similarity = new NilsimsaSimilarity();
similarity.setProductA(outerReview.getId());
similarity.setProductB(innerReview.getId());
similarity.setSimilarity(percentage);
similarity.setCategory(category);
nisimsaDao.save(similarity);
counter++;
}
}
start++;
// Reduce output noise
Integer rand = ThreadLocalRandom.current().nextInt(1, 2000);
if (rand == 500) {
log.info("Current Item ID of '{}' on '{}': {}'", category, getHostnameSecure(), start);
}
}
log.info("FINISHED on '{}'. Found '{}' similar items", getHostnameSecure(), counter);
}
private String getHostnameSecure() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
log.warn("Could not getHostName");
}
return "Empty";
}
}
|
spade/spade-core/src/main/java/info/interactivesystems/spade/similarity/NilsimsaSimilarityCalculator.java
|
/**
* Copyright 2014 Dennis Rippinger
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.interactivesystems.spade.similarity;
import info.interactivesystems.spade.dao.NilsimsaSimilarityDao;
import info.interactivesystems.spade.dao.service.ReviewContentService;
import info.interactivesystems.spade.entities.NilsimsaSimilarity;
import info.interactivesystems.spade.entities.Review;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* The Class NilsimsaSimilarityCalculator.
*
* @author Dennis Rippinger
*/
@Slf4j
@Component
public class NilsimsaSimilarityCalculator {
@Resource
private NilsimsaSimilarityDao nisimsaDao;
@Resource
private ReviewContentService service;
@Resource
private NilsimsaHash hash;
/**
* Calculate similarity between unique reviews.
*/
public void calculateSimilarityBetweenUniqueReviews(String category) {
List<Review> uniqueReviews = service.findReviewsByCategory(category);
Integer start = 0;
Integer counter = 0;
for (Review outerReview : uniqueReviews) {
for (Integer current = start; current < uniqueReviews.size(); current++) {
Review innerReview = uniqueReviews.get(current);
Integer sameBits = hash.compare(outerReview.getNilsimsa(), innerReview.getNilsimsa());
Double percentage = sameBits / 128.0;
if (percentage >= 65.0) {
NilsimsaSimilarity similarity = new NilsimsaSimilarity();
similarity.setProductA(outerReview.getId());
similarity.setProductB(innerReview.getId());
similarity.setSimilarity(percentage);
similarity.setCategory(category);
nisimsaDao.save(similarity);
counter++;
}
}
start++;
// Reduce output noise
Integer rand = ThreadLocalRandom.current().nextInt(1, 2000);
if (rand == 500) {
log.info("Current Item ID '{}'", start);
}
}
log.info("Found '{}' similar items", counter);
}
}
|
Fixed Nilsimsa Calculator
haha 650 %
|
spade/spade-core/src/main/java/info/interactivesystems/spade/similarity/NilsimsaSimilarityCalculator.java
|
Fixed Nilsimsa Calculator
|
<ide><path>pade/spade-core/src/main/java/info/interactivesystems/spade/similarity/NilsimsaSimilarityCalculator.java
<ide> import info.interactivesystems.spade.entities.NilsimsaSimilarity;
<ide> import info.interactivesystems.spade.entities.Review;
<ide>
<add>import java.net.InetAddress;
<add>import java.net.UnknownHostException;
<ide> import java.util.List;
<ide> import java.util.concurrent.ThreadLocalRandom;
<ide>
<ide> Integer start = 0;
<ide> Integer counter = 0;
<ide>
<add> log.info("Size of '{}': '{}'", category, uniqueReviews.size());
<add>
<ide> for (Review outerReview : uniqueReviews) {
<ide>
<ide> for (Integer current = start; current < uniqueReviews.size(); current++) {
<ide> Review innerReview = uniqueReviews.get(current);
<add> if (innerReview.getId().equals(outerReview.getId())) {
<add> continue;
<add> }
<add>
<ide> Integer sameBits = hash.compare(outerReview.getNilsimsa(), innerReview.getNilsimsa());
<ide> Double percentage = sameBits / 128.0;
<ide>
<del> if (percentage >= 65.0) {
<add> if (percentage >= 0.70) {
<ide> NilsimsaSimilarity similarity = new NilsimsaSimilarity();
<ide> similarity.setProductA(outerReview.getId());
<ide> similarity.setProductB(innerReview.getId());
<ide> // Reduce output noise
<ide> Integer rand = ThreadLocalRandom.current().nextInt(1, 2000);
<ide> if (rand == 500) {
<del> log.info("Current Item ID '{}'", start);
<add> log.info("Current Item ID of '{}' on '{}': {}'", category, getHostnameSecure(), start);
<ide> }
<ide> }
<ide>
<del> log.info("Found '{}' similar items", counter);
<add> log.info("FINISHED on '{}'. Found '{}' similar items", getHostnameSecure(), counter);
<ide>
<ide> }
<ide>
<add> private String getHostnameSecure() {
<add> try {
<add> return InetAddress.getLocalHost().getHostName();
<add> } catch (UnknownHostException e) {
<add> log.warn("Could not getHostName");
<add> }
<add>
<add> return "Empty";
<add> }
<add>
<ide> }
|
|
Java
|
apache-2.0
|
error: pathspec 'catalog/src/test/java/org/killbill/billing/catalog/caching/TestPriceOverridePattern.java' did not match any file(s) known to git
|
67b508c52addbd8f957047d564fea2d0507a507c
| 1 |
sbrossie/killbill,killbill/killbill,sbrossie/killbill,sbrossie/killbill,sbrossie/killbill,killbill/killbill,killbill/killbill,killbill/killbill,killbill/killbill,sbrossie/killbill
|
import static org.testng.Assert.*;
public class TestPriceOverridePattern {
}
|
catalog/src/test/java/org/killbill/billing/catalog/caching/TestPriceOverridePattern.java
|
catalog: Add basic test to verify legacy and non legacy separator in PriceOverridePattern. See #1364
|
catalog/src/test/java/org/killbill/billing/catalog/caching/TestPriceOverridePattern.java
|
catalog: Add basic test to verify legacy and non legacy separator in PriceOverridePattern. See #1364
|
<ide><path>atalog/src/test/java/org/killbill/billing/catalog/caching/TestPriceOverridePattern.java
<add>import static org.testng.Assert.*;
<add>
<add>public class TestPriceOverridePattern {
<add>
<add>}
|
|
Java
|
apache-2.0
|
3fd49cf9fadc5a6821874c185675205bf9e2eeb7
| 0 |
bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm,bazelbuild/bazel-buildfarm
|
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.instance.shard;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static java.lang.String.format;
import static java.util.logging.Level.SEVERE;
import build.bazel.remote.execution.v2.ActionResult;
import build.bazel.remote.execution.v2.Digest;
import build.bazel.remote.execution.v2.ExecuteOperationMetadata;
import build.bazel.remote.execution.v2.ExecutionStage;
import build.buildfarm.common.DigestUtil;
import build.buildfarm.common.DigestUtil.ActionKey;
import build.buildfarm.common.ShardBackplane;
import build.buildfarm.common.Watcher;
import build.buildfarm.common.function.InterruptingRunnable;
import build.buildfarm.instance.shard.RedisShardSubscriber.TimedWatchFuture;
import build.buildfarm.v1test.CompletedOperationMetadata;
import build.buildfarm.v1test.DispatchedOperation;
import build.buildfarm.v1test.ExecuteEntry;
import build.buildfarm.v1test.ExecutingOperationMetadata;
import build.buildfarm.v1test.OperationChange;
import build.buildfarm.v1test.QueueEntry;
import build.buildfarm.v1test.QueuedOperationMetadata;
import build.buildfarm.v1test.RedisShardBackplaneConfig;
import build.buildfarm.v1test.ShardWorker;
import build.buildfarm.v1test.WorkerChange;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.longrunning.Operation;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.JsonFormat;
import com.google.rpc.PreconditionFailure;
import io.grpc.Status;
import io.grpc.Status.Code;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.time.Instant;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.naming.ConfigurationException;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisClusterPipeline;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Response;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException;
public class RedisShardBackplane implements ShardBackplane {
private static final Logger logger = Logger.getLogger(RedisShardBackplane.class.getName());
private static final JsonFormat.Parser operationParser = JsonFormat.parser()
.usingTypeRegistry(
JsonFormat.TypeRegistry.newBuilder()
.add(CompletedOperationMetadata.getDescriptor())
.add(ExecutingOperationMetadata.getDescriptor())
.add(ExecuteOperationMetadata.getDescriptor())
.add(QueuedOperationMetadata.getDescriptor())
.add(PreconditionFailure.getDescriptor())
.build())
.ignoringUnknownFields();
private static final JsonFormat.Printer operationPrinter = JsonFormat.printer().usingTypeRegistry(
JsonFormat.TypeRegistry.newBuilder()
.add(CompletedOperationMetadata.getDescriptor())
.add(ExecutingOperationMetadata.getDescriptor())
.add(ExecuteOperationMetadata.getDescriptor())
.add(QueuedOperationMetadata.getDescriptor())
.add(PreconditionFailure.getDescriptor())
.build());
private final RedisShardBackplaneConfig config;
private final String source; // used in operation change publication
private final Function<Operation, Operation> onPublish;
private final Function<Operation, Operation> onComplete;
private final Predicate<Operation> isPrequeued;
private final Predicate<Operation> isDispatched;
private final Supplier<JedisCluster> jedisClusterFactory;
private @Nullable InterruptingRunnable onUnsubscribe = null;
private Thread subscriptionThread = null;
private Thread failsafeOperationThread = null;
private RedisShardSubscriber subscriber = null;
private RedisShardSubscription operationSubscription = null;
private ExecutorService subscriberService = null;
private boolean poolStarted = false;
private @Nullable JedisCluster jedisCluster = null;
private Set<String> workerSet = Collections.synchronizedSet(new HashSet<>());
private long workerSetExpiresAt = 0;
private static class JedisMisconfigurationException extends JedisDataException {
public JedisMisconfigurationException(final String message) {
super(message);
}
public JedisMisconfigurationException(final Throwable cause) {
super(cause);
}
public JedisMisconfigurationException(final String message, final Throwable cause) {
super(message, cause);
}
}
private static JedisPoolConfig createJedisPoolConfig(RedisShardBackplaneConfig config) {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(config.getJedisPoolMaxTotal());
return jedisPoolConfig;
}
private static URI parseRedisURI(String redisURI) throws ConfigurationException {
try {
return new URI(redisURI);
} catch (URISyntaxException e) {
throw new ConfigurationException(e.getMessage());
}
}
private static Supplier<JedisCluster> createJedisClusterFactory(URI redisURI, JedisPoolConfig poolConfig) {
return () -> new JedisCluster(
new HostAndPort(redisURI.getHost(), redisURI.getPort()),
poolConfig);
}
public RedisShardBackplane(
RedisShardBackplaneConfig config,
String source,
Function<Operation, Operation> onPublish,
Function<Operation, Operation> onComplete,
Predicate<Operation> isPrequeued,
Predicate<Operation> isDispatched) throws ConfigurationException {
this(
config,
source,
onPublish,
onComplete,
isPrequeued,
isDispatched,
createJedisClusterFactory(parseRedisURI(config.getRedisUri()), createJedisPoolConfig(config)));
}
public RedisShardBackplane(
RedisShardBackplaneConfig config,
String source,
Function<Operation, Operation> onPublish,
Function<Operation, Operation> onComplete,
Predicate<Operation> isPrequeued,
Predicate<Operation> isDispatched,
Supplier<JedisCluster> jedisClusterFactory) {
this.config = config;
this.source = source;
this.onPublish = onPublish;
this.onComplete = onComplete;
this.isPrequeued = isPrequeued;
this.isDispatched = isDispatched;
this.jedisClusterFactory = jedisClusterFactory;
}
@Override
public InterruptingRunnable setOnUnsubscribe(InterruptingRunnable onUnsubscribe) {
InterruptingRunnable oldOnUnsubscribe = this.onUnsubscribe;
this.onUnsubscribe = onUnsubscribe;
return oldOnUnsubscribe;
}
private Instant getExpiresAt(JedisCluster jedis, String key, Instant now) {
String value = jedis.get(key);
if (value != null) {
try {
return Instant.ofEpochMilli(Long.parseLong(value));
} catch (NumberFormatException e) {
logger.severe(format("invalid expiration %s for %s", value, key));
}
}
Instant expiresAt = now.plusMillis(config.getProcessingTimeoutMillis());
jedis.setex(
key,
/* expire=*/ (config.getProcessingTimeoutMillis() * 2) / 1000,
String.format("%d", expiresAt.toEpochMilli()));
return expiresAt;
}
abstract static class ListVisitor {
private static final int LIST_PAGE_SIZE = 10000;
protected abstract void visit(String entry);
// this can potentially operate over the same set of entries in multiple steps
public static void visit(JedisCluster jedis, String name, ListVisitor visitor) {
int index = 0;
int nextIndex = LIST_PAGE_SIZE;
List<String> entries;
do {
entries = jedis.lrange(name, index, nextIndex - 1);
for (String entry : entries) {
visitor.visit(entry);
}
index = nextIndex;
nextIndex += entries.size();
} while (entries.size() == LIST_PAGE_SIZE);
}
}
abstract static class QueueEntryListVisitor extends ListVisitor {
protected abstract void visit(QueueEntry queueEntry, String queueEntryJson);
@Override
protected void visit(String entry) {
QueueEntry.Builder queueEntry = QueueEntry.newBuilder();
try {
JsonFormat.parser().merge(entry, queueEntry);
visit(queueEntry.build(), entry);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "invalid QueueEntry json: " + entry, e);
}
}
}
abstract static class ExecuteEntryListVisitor extends ListVisitor {
protected abstract void visit(ExecuteEntry executeEntry, String executeEntryJson);
@Override
protected void visit(String entry) {
ExecuteEntry.Builder executeEntry = ExecuteEntry.newBuilder();
try {
JsonFormat.parser().merge(entry, executeEntry);
visit(executeEntry.build(), entry);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "invalid ExecuteEntry json: " + entry, e);
}
}
}
private void scanProcessing(JedisCluster jedis, Consumer<String> onOperationName, Instant now) {
ListVisitor.visit(
jedis,
config.getProcessingListName(),
new ExecuteEntryListVisitor() {
@Override
protected void visit(ExecuteEntry executeEntry, String executeEntryJson) {
String operationName = executeEntry.getOperationName();
String operationProcessingKey = processingKey(operationName);
Instant expiresAt = getExpiresAt(jedis, operationProcessingKey, now);
if (now.isBefore(expiresAt)) {
onOperationName.accept(operationName);
} else {
if (jedis.lrem(config.getProcessingListName(), -1, executeEntryJson) != 0) {
jedis.del(operationProcessingKey);
}
}
}
});
}
private void scanDispatching(JedisCluster jedis, Consumer<String> onOperationName, Instant now) {
ListVisitor.visit(
jedis,
config.getDispatchingListName(),
new QueueEntryListVisitor() {
@Override
protected void visit(QueueEntry queueEntry, String queueEntryJson) {
String operationName = queueEntry.getExecuteEntry().getOperationName();
String operationDispatchingKey = dispatchingKey(operationName);
Instant expiresAt = getExpiresAt(jedis, operationDispatchingKey, now);
if (now.isBefore(expiresAt)) {
onOperationName.accept(operationName);
} else {
if (jedis.lrem(config.getDispatchingListName(), -1, queueEntryJson) != 0) {
jedis.del(operationDispatchingKey);
}
}
}
});
}
private void scanPrequeue(JedisCluster jedis, Consumer<String> onOperationName) {
ListVisitor.visit(
jedis,
config.getPreQueuedOperationsListName(),
new ExecuteEntryListVisitor() {
@Override
protected void visit(ExecuteEntry executeEntry, String executeEntryJson) {
onOperationName.accept(executeEntry.getOperationName());
}
});
}
private void scanQueue(JedisCluster jedis, Consumer<String> onOperationName) {
ListVisitor.visit(
jedis,
config.getQueuedOperationsListName(),
new QueueEntryListVisitor() {
@Override
protected void visit(QueueEntry queueEntry, String queueEntryJson) {
onOperationName.accept(queueEntry.getExecuteEntry().getOperationName());
}
});
}
private void scanDispatched(JedisCluster jedis, Consumer<String> onOperationName) {
for (String operationName : jedis.hkeys(config.getDispatchedOperationsHashName())) {
onOperationName.accept(operationName);
}
}
private void updateWatchers(JedisCluster jedis) {
Instant now = Instant.now();
Instant expiresAt = nextExpiresAt(now);
Set<String> expiringChannels = Sets.newHashSet(
subscriber.expiredWatchedOperationChannels(now));
Consumer<String> resetChannel = (operationName) -> {
String channel = operationChannel(operationName);
if (expiringChannels.remove(channel)) {
subscriber.resetWatchers(channel, expiresAt);
}
};
if (!expiringChannels.isEmpty()) {
logger.info(
format(
"Scan %d watches, %s, expiresAt: %s",
expiringChannels.size(),
now,
expiresAt));
logger.info("Scan prequeue");
// scan prequeue, pet watches
scanPrequeue(jedis, resetChannel);
}
// scan processing, create ttl key if missing, remove dead entries, pet live watches
scanProcessing(jedis, resetChannel, now);
if (!expiringChannels.isEmpty()) {
logger.info("Scan queue");
// scan queue, pet watches
scanQueue(jedis, resetChannel);
}
// scan dispatching, create ttl key if missing, remove dead entries, pet live watches
scanDispatching(jedis, resetChannel, now);
if (!expiringChannels.isEmpty()) {
logger.info("Scan dispatched");
// scan dispatched pet watches
scanDispatched(jedis, resetChannel);
}
//
// filter watches on expiration
// delete the operation?
// update expired watches with null operation
for (String channel : expiringChannels) {
Operation operation = parseOperationJson(getOperation(jedis, parseOperationChannel(channel)));
if (operation == null || !operation.getDone()) {
publishExpiration(jedis, channel, now, /* force=*/ false);
} else {
subscriber.onOperation(
channel,
onPublish.apply(operation),
expiresAt);
}
}
}
static String printOperationChange(OperationChange operationChange) throws InvalidProtocolBufferException {
return operationPrinter.print(operationChange);
}
void publish(JedisCluster jedis, String channel, Instant effectiveAt, OperationChange.Builder operationChange) {
try {
String operationChangeJson = printOperationChange(
operationChange
.setEffectiveAt(toTimestamp(effectiveAt))
.setSource(source)
.build());
jedis.publish(channel, operationChangeJson);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing operation change", e);
// very unlikely, printer would have to fail
}
}
void publishReset(JedisCluster jedis, Operation operation) {
Instant effectiveAt = Instant.now();
Instant expiresAt = nextExpiresAt(effectiveAt);
publish(
jedis,
operationChannel(operation.getName()),
Instant.now(),
OperationChange.newBuilder()
.setReset(OperationChange.Reset.newBuilder()
.setExpiresAt(toTimestamp(expiresAt))
.setOperation(operation)
.build()));
}
static Timestamp toTimestamp(Instant instant) {
return Timestamp.newBuilder()
.setSeconds(instant.getEpochSecond())
.setNanos(instant.getNano())
.build();
}
void publishExpiration(JedisCluster jedis, String channel, Instant effectiveAt, boolean force) {
publish(
jedis,
channel,
effectiveAt,
OperationChange.newBuilder()
.setExpire(OperationChange.Expire.newBuilder()
.setForce(force)
.build()));
}
public void updateWatchedIfDone(JedisCluster jedis) {
List<String> operationChannels = subscriber.watchedOperationChannels();
if (operationChannels.isEmpty()) {
return;
}
Instant now = Instant.now();
List<Map.Entry<String, Response<String>>> operations = new ArrayList(operationChannels.size());
JedisClusterPipeline p = jedis.pipelined();
for (String operationName : Iterables.transform(operationChannels, RedisShardBackplane::parseOperationChannel)) {
operations.add(new AbstractMap.SimpleEntry<>(
operationName,
p.get(operationKey(operationName))));
}
p.sync();
for (Map.Entry<String, Response<String>> entry : operations) {
String json = entry.getValue().get();
Operation operation = json == null
? null : RedisShardBackplane.parseOperationJson(json);
String operationName = entry.getKey();
if (operation == null || operation.getDone()) {
if (operation != null) {
operation = onPublish.apply(operation);
}
subscriber.onOperation(
operationChannel(operationName),
operation,
nextExpiresAt(now));
logger.info(
format(
"operation %s done due to %s",
operationName,
operation == null ? "null" : "completed"));
}
}
}
private Instant nextExpiresAt(Instant from) {
return from.plusSeconds(10);
}
private void startSubscriptionThread() {
ListMultimap<String, TimedWatchFuture> watchers =
Multimaps.<String, TimedWatchFuture>synchronizedListMultimap(
MultimapBuilder.linkedHashKeys().arrayListValues().build());
subscriberService = Executors.newFixedThreadPool(32);
subscriber = new RedisShardSubscriber(watchers, workerSet, config.getWorkerChannel(), subscriberService);
operationSubscription = new RedisShardSubscription(
subscriber,
/* onUnsubscribe=*/ () -> {
subscriptionThread = null;
if (onUnsubscribe != null) {
onUnsubscribe.runInterruptibly();
}
},
/* onReset=*/ this::updateWatchedIfDone,
/* subscriptions=*/ subscriber::subscribedChannels,
this::getSubscribeJedis);
// use Executors...
subscriptionThread = new Thread(operationSubscription);
subscriptionThread.start();
}
private void startFailsafeOperationThread() {
failsafeOperationThread = new Thread(() -> {
while (true) {
try {
TimeUnit.SECONDS.sleep(10);
updateWatchers(getJedis());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
logger.log(SEVERE, "error while updating watchers in failsafe", e);
}
}
});
failsafeOperationThread.start();
}
@Override
public void start() {
poolStarted = true;
if (config.getSubscribeToBackplane()) {
startSubscriptionThread();
}
if (config.getRunFailsafeOperation()) {
startFailsafeOperationThread();
}
jedisCluster = jedisClusterFactory.get();
}
@Override
public synchronized void stop() throws InterruptedException {
if (failsafeOperationThread != null) {
failsafeOperationThread.stop();
failsafeOperationThread.join();
logger.fine("failsafeOperationThread has been stopped");
}
if (operationSubscription != null) {
operationSubscription.stop();
if (subscriptionThread != null) {
subscriptionThread.join();
}
logger.fine("subscriptionThread has been stopped");
}
if (subscriberService != null) {
subscriberService.shutdown();
subscriberService.awaitTermination(10, TimeUnit.SECONDS);
logger.fine("subscriberService has been stopped");
}
if (jedisCluster != null) {
poolStarted = false;
jedisCluster.close();
jedisCluster = null;
logger.fine("pool has been closed");
}
}
@Override
public boolean isStopped() {
return !poolStarted;
}
@Override
public ListenableFuture<Void> watchOperation(
String operationName,
Watcher watcher) throws IOException {
TimedWatcher timedWatcher = new TimedWatcher(nextExpiresAt(Instant.now())) {
@Override
public void observe(Operation operation) {
watcher.observe(operation);
}
};
return subscriber.watch(
operationChannel(operationName),
timedWatcher);
}
@Override
public boolean addWorker(ShardWorker shardWorker) throws IOException {
String json = JsonFormat.printer().print(shardWorker);
String workerChangeJson = JsonFormat.printer().print(
WorkerChange.newBuilder()
.setEffectiveAt(toTimestamp(Instant.now()))
.setName(shardWorker.getEndpoint())
.setAdd(WorkerChange.Add.getDefaultInstance())
.build());
return withBackplaneException(
(jedis) -> {
// could rework with an hget to publish prior, but this seems adequate, and
// we are the only guaranteed source
if (jedis.hset(config.getWorkersHashName(), shardWorker.getEndpoint(), json) == 1) {
jedis.publish(config.getWorkerChannel(), workerChangeJson);
return true;
}
return false;
});
}
private static final String MISCONF_RESPONSE = "MISCONF";
@FunctionalInterface
private static interface JedisContext<T> {
T run(JedisCluster jedis) throws JedisException;
}
@VisibleForTesting
public void withVoidBackplaneException(Consumer<JedisCluster> withJedis) throws IOException {
withBackplaneException(new JedisContext<Void>() {
@Override
public Void run(JedisCluster jedis) throws JedisException {
withJedis.accept(jedis);
return null;
}
});
}
@VisibleForTesting
public <T> T withBackplaneException(JedisContext<T> withJedis) throws IOException {
try {
try {
return withJedis.run(getJedis());
} catch (JedisDataException e) {
if (e.getMessage().startsWith(MISCONF_RESPONSE)) {
throw new JedisMisconfigurationException(e.getMessage());
}
throw e;
}
} catch (JedisMisconfigurationException e) {
// the backplane is configured not to accept writes currently
// as a result of an error. The error is meant to indicate
// that substantial resources were unavailable.
// we must throw an IOException which indicates as much
// this looks simply to me like a good opportunity to use UNAVAILABLE
// we are technically not at RESOURCE_EXHAUSTED, this is a
// persistent state which can exist long past the error
throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException());
} catch (JedisNoReachableClusterNodeException e) {
throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException());
} catch (JedisConnectionException e) {
if ((e.getMessage() != null && e.getMessage().equals("Unexpected end of stream."))
|| e.getCause() instanceof ConnectException) {
throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException());
}
Throwable cause = e;
Status status = Status.UNKNOWN;
while (status.getCode() == Code.UNKNOWN && cause != null) {
String message = cause.getMessage() == null ? "" : cause.getMessage();
if ((cause instanceof SocketException && cause.getMessage().equals("Connection reset"))
|| cause instanceof ConnectException
|| message.equals("Unexpected end of stream.")) {
status = Status.UNAVAILABLE;
} else if (cause instanceof SocketTimeoutException) {
status = Status.DEADLINE_EXCEEDED;
} else if (cause instanceof IOException) {
throw (IOException) cause;
} else {
cause = cause.getCause();
}
}
throw new IOException(status.withCause(cause == null ? e : cause).asRuntimeException());
}
}
@Override
public boolean removeWorker(String workerName) throws IOException {
WorkerChange workerChange = WorkerChange.newBuilder()
.setName(workerName)
.setRemove(WorkerChange.Remove.newBuilder()
.setSource(source)
.build())
.build();
String workerChangeJson = JsonFormat.printer().print(workerChange);
return subscriber.removeWorker(workerName) &&
withBackplaneException((jedis) -> {
if (jedis.hdel(config.getWorkersHashName(), workerName) == 1) {
jedis.publish(config.getWorkerChannel(), workerChangeJson);
return true;
}
return false;
});
}
@Override
public synchronized Set<String> getWorkers() throws IOException {
long now = System.currentTimeMillis();
if (now < workerSetExpiresAt) {
return workerSet;
}
synchronized (workerSet) {
Set<String> newWorkerSet = withBackplaneException((jedis) -> fetchAndExpireWorkers(jedis, now));
workerSet.clear();
workerSet.addAll(newWorkerSet);
}
// fetch every 3 seconds
workerSetExpiresAt = now + 3000;
return workerSet;
}
private Set<String> fetchAndExpireWorkers(JedisCluster jedis, long now) {
Set<String> workers = Sets.newConcurrentHashSet();
ImmutableList.Builder<String> invalidWorkers = ImmutableList.builder();
for (Map.Entry<String, String> entry : jedis.hgetAll(config.getWorkersHashName()).entrySet()) {
String json = entry.getValue();
String name = entry.getKey();
try {
if (json == null) {
invalidWorkers.add(name);
} else {
ShardWorker.Builder builder = ShardWorker.newBuilder();
JsonFormat.parser().merge(json, builder);
ShardWorker worker = builder.build();
if (worker.getExpireAt() <= now) {
invalidWorkers.add(name);
} else {
workers.add(worker.getEndpoint());
}
}
} catch (InvalidProtocolBufferException e) {
invalidWorkers.add(name);
}
}
JedisClusterPipeline p = jedis.pipelined();
for (String invalidWorker : invalidWorkers.build()) {
p.hdel(config.getWorkersHashName(), invalidWorker);
}
p.sync();
return workers;
}
private static ActionResult parseActionResult(String json) {
try {
ActionResult.Builder builder = ActionResult.newBuilder();
JsonFormat.parser().merge(json, builder);
return builder.build();
} catch (InvalidProtocolBufferException e) {
return null;
}
}
@Override
public ActionResult getActionResult(ActionKey actionKey) throws IOException {
String json = withBackplaneException((jedis) -> jedis.get(acKey(actionKey)));
if (json == null) {
return null;
}
ActionResult actionResult = parseActionResult(json);
if (actionResult == null) {
withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey));
}
return actionResult;
}
@Override
public void putActionResult(ActionKey actionKey, ActionResult actionResult)
throws IOException {
String json = JsonFormat.printer().print(actionResult);
withVoidBackplaneException((jedis) -> jedis.setex(acKey(actionKey), config.getActionCacheExpire(), json));
}
private void removeActionResult(JedisCluster jedis, ActionKey actionKey) {
jedis.del(acKey(actionKey));
}
@Override
public void removeActionResult(ActionKey actionKey) throws IOException {
withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey));
}
@Override
public void removeActionResults(Iterable<ActionKey> actionKeys) throws IOException {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (ActionKey actionKey : actionKeys) {
p.del(acKey(actionKey));
}
p.sync();
});
}
@Override
public ActionCacheScanResult scanActionCache(String scanToken, int count) throws IOException {
final String jedisScanToken = scanToken == null ? SCAN_POINTER_START : scanToken;
ImmutableList.Builder<Map.Entry<ActionKey, String>> results = new ImmutableList.Builder<>();
ScanParams scanParams = new ScanParams()
.match(config.getActionCachePrefix() + ":*")
.count(count);
String token = withBackplaneException((jedis) -> {
ScanResult<String> scanResult = jedis.scan(jedisScanToken, scanParams);
List<String> keyResults = scanResult.getResult();
List<Response<String>> actionResults = new ArrayList<>(keyResults.size());
JedisClusterPipeline p = jedis.pipelined();
for (int i = 0; i < keyResults.size(); i++) {
actionResults.add(p.get(keyResults.get(i)));
}
p.sync();
for (int i = 0; i < keyResults.size(); i++) {
String json = actionResults.get(i).get();
if (json == null) {
continue;
}
String key = keyResults.get(i);
results.add(new AbstractMap.SimpleEntry<>(
DigestUtil.asActionKey(DigestUtil.parseDigest(key.split(":")[1])),
json));
}
String cursor = scanResult.getCursor();
return cursor.equals(SCAN_POINTER_START) ? null : cursor;
});
return new ActionCacheScanResult(
token,
Iterables.transform(
results.build(),
(entry) -> new AbstractMap.SimpleEntry<>(
entry.getKey(),
parseActionResult(entry.getValue()))));
}
@Override
public void adjustBlobLocations(Digest blobDigest, Set<String> addWorkers, Set<String> removeWorkers) throws IOException {
String key = casKey(blobDigest);
withVoidBackplaneException((jedis) -> {
for (String workerName : addWorkers) {
jedis.sadd(key, workerName);
}
for (String workerName : removeWorkers) {
jedis.srem(key, workerName);
}
jedis.expire(key, config.getCasExpire());
});
}
@Override
public void addBlobLocation(Digest blobDigest, String workerName) throws IOException {
String key = casKey(blobDigest);
withVoidBackplaneException((jedis) -> {
jedis.sadd(key, workerName);
jedis.expire(key, config.getCasExpire());
});
}
@Override
public void addBlobsLocation(Iterable<Digest> blobDigests, String workerName)
throws IOException {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (Digest blobDigest : blobDigests) {
String key = casKey(blobDigest);
p.sadd(key, workerName);
p.expire(key, config.getCasExpire());
}
p.sync();
});
}
@Override
public void removeBlobLocation(Digest blobDigest, String workerName) throws IOException {
String key = casKey(blobDigest);
withVoidBackplaneException((jedis) -> jedis.srem(key, workerName));
}
@Override
public void removeBlobsLocation(Iterable<Digest> blobDigests, String workerName)
throws IOException {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (Digest blobDigest : blobDigests) {
p.srem(casKey(blobDigest), workerName);
}
p.sync();
});
}
@Override
public String getBlobLocation(Digest blobDigest) throws IOException {
return withBackplaneException((jedis) -> jedis.srandmember(casKey(blobDigest)));
}
@Override
public Set<String> getBlobLocationSet(Digest blobDigest) throws IOException {
return withBackplaneException((jedis) -> jedis.smembers(casKey(blobDigest)));
}
@Override
public Map<Digest, Set<String>> getBlobDigestsWorkers(Iterable<Digest> blobDigests)
throws IOException {
// FIXME pipeline
ImmutableMap.Builder<Digest, Set<String>> blobDigestsWorkers = new ImmutableMap.Builder<>();
withVoidBackplaneException((jedis) -> {
for (Digest blobDigest : blobDigests) {
Set<String> workers = jedis.smembers(casKey(blobDigest));
if (workers.isEmpty()) {
continue;
}
blobDigestsWorkers.put(blobDigest, workers);
}
});
return blobDigestsWorkers.build();
}
public static WorkerChange parseWorkerChange(String workerChangeJson) throws InvalidProtocolBufferException {
WorkerChange.Builder workerChange = WorkerChange.newBuilder();
JsonFormat.parser().merge(workerChangeJson, workerChange);
return workerChange.build();
}
public static OperationChange parseOperationChange(String operationChangeJson) throws InvalidProtocolBufferException {
OperationChange.Builder operationChange = OperationChange.newBuilder();
operationParser.merge(operationChangeJson, operationChange);
return operationChange.build();
}
public static Operation parseOperationJson(String operationJson) {
if (operationJson == null) {
return null;
}
try {
Operation.Builder operationBuilder = Operation.newBuilder();
operationParser.merge(operationJson, operationBuilder);
return operationBuilder.build();
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error parsing operation from " + operationJson, e);
return null;
}
}
private String getOperation(JedisCluster jedis, String operationName) {
String json = jedis.get(operationKey(operationName));
if (json == null) {
return null;
}
return json;
}
@Override
public Operation getOperation(String operationName) throws IOException {
String json = withBackplaneException((jedis) -> getOperation(jedis, operationName));
return parseOperationJson(json);
}
@Override
public boolean putOperation(Operation operation, ExecutionStage.Value stage) throws IOException {
// FIXME queue and prequeue should no longer be passed to here
boolean prequeue = stage == ExecutionStage.Value.UNKNOWN && !operation.getDone();
boolean queue = stage == ExecutionStage.Value.QUEUED;
boolean complete = !queue && operation.getDone();
boolean publish = !queue && stage != ExecutionStage.Value.UNKNOWN;
if (complete) {
// for filtering anything that shouldn't be stored
operation = onComplete.apply(operation);
}
String json;
try {
json = operationPrinter.print(operation);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing operation " + operation.getName(), e);
return false;
}
Operation publishOperation;
if (publish) {
publishOperation = onPublish.apply(operation);
} else {
publishOperation = null;
}
String name = operation.getName();
withVoidBackplaneException((jedis) -> {
if (complete) {
completeOperation(jedis, name);
}
jedis.setex(operationKey(name), config.getOperationExpire(), json);
if (publishOperation != null) {
publishReset(jedis, publishOperation);
}
});
return true;
}
private void queue(JedisCluster jedis, String operationName, String queueEntryJson) {
if (jedis.hdel(config.getDispatchedOperationsHashName(), operationName) == 1) {
logger.warning(format("removed dispatched operation %s", operationName));
}
jedis.lpush(config.getQueuedOperationsListName(), queueEntryJson);
}
@Override
public void queue(QueueEntry queueEntry, Operation operation) throws IOException {
String operationName = operation.getName();
String operationJson = operationPrinter.print(operation);
String queueEntryJson = JsonFormat.printer().print(queueEntry);
Operation publishOperation = onPublish.apply(operation);
withVoidBackplaneException((jedis) -> {
jedis.setex(operationKey(operationName), config.getOperationExpire(), operationJson);
queue(jedis, operation.getName(), queueEntryJson);
publishReset(jedis, publishOperation);
});
}
public Map<String, Operation> getOperationsMap() throws IOException {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
withVoidBackplaneException((jedis) -> {
for (Map.Entry<String, String> entry : jedis.hgetAll(config.getDispatchedOperationsHashName()).entrySet()) {
builder.put(entry.getKey(), entry.getValue());
}
});
return Maps.transformValues(builder.build(), RedisShardBackplane::parseOperationJson);
}
@Override
public Iterable<String> getOperations() throws IOException {
throw new UnsupportedOperationException();
/*
return withVoidBackplaneException((jedis) -> {
Iterable<String> dispatchedOperations = jedis.hkeys(config.getDispatchedOperationsHashName());
Iterable<String> queuedOperations = jedis.lrange(config.getQueuedOperationsListName(), 0, -1);
return Iterables.concat(queuedOperations, dispatchedOperations, getCompletedOperations(jedis));
});
*/
}
@Override
public ImmutableList<DispatchedOperation> getDispatchedOperations() throws IOException {
ImmutableList.Builder<DispatchedOperation> builder = new ImmutableList.Builder<>();
Map<String, String> dispatchedOperations = withBackplaneException((jedis) -> jedis.hgetAll(config.getDispatchedOperationsHashName()));
ImmutableList.Builder<String> invalidOperationNames = new ImmutableList.Builder<>();
boolean hasInvalid = false;
// executor work queue?
for (Map.Entry<String, String> entry : dispatchedOperations.entrySet()) {
try {
DispatchedOperation.Builder dispatchedOperationBuilder = DispatchedOperation.newBuilder();
JsonFormat.parser().merge(entry.getValue(), dispatchedOperationBuilder);
builder.add(dispatchedOperationBuilder.build());
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "RedisShardBackplane::getDispatchedOperations: removing invalid operation " + entry.getKey(), e);
/* guess we don't want to spin on this */
invalidOperationNames.add(entry.getKey());
hasInvalid = true;
}
}
if (hasInvalid) {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (String invalidOperationName : invalidOperationNames.build()) {
p.hdel(config.getDispatchedOperationsHashName(), invalidOperationName);
}
p.sync();
});
}
return builder.build();
}
private ExecuteEntry deprequeueOperation(JedisCluster jedis) {
String executeEntryJson;
do {
executeEntryJson = jedis.brpoplpush(
config.getPreQueuedOperationsListName(),
config.getProcessingListName(),
1);
if (Thread.currentThread().isInterrupted()) {
return null;
}
} while (executeEntryJson == null);
ExecuteEntry.Builder executeEntryBuilder = ExecuteEntry.newBuilder();
try {
JsonFormat.parser().merge(executeEntryJson, executeEntryBuilder);
ExecuteEntry executeEntry = executeEntryBuilder.build();
String operationName = executeEntry.getOperationName();
Operation operation = keepaliveOperation(operationName);
// publish so that watchers reset their timeout
publishReset(jedis, operation);
// destroy the processing entry and ttl
if (jedis.lrem(config.getProcessingListName(), -1, executeEntryJson) == 0) {
logger.severe(
format(
"could not remove %s from %s",
operationName,
config.getProcessingListName()));
return null;
}
jedis.del(processingKey(operationName)); // may or may not exist
return executeEntry;
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error parsing execute entry", e);
return null;
}
}
@Override
public ExecuteEntry deprequeueOperation() throws IOException, InterruptedException {
ExecuteEntry executeEntry = withBackplaneException(this::deprequeueOperation);
if (Thread.interrupted()) {
throw new InterruptedException();
}
return executeEntry;
}
private QueueEntry dispatchOperation(JedisCluster jedis) {
String queueEntryJson;
do {
queueEntryJson = jedis.brpoplpush(
config.getQueuedOperationsListName(),
config.getDispatchingListName(),
1);
// right here is an operation loss risk
if (Thread.currentThread().isInterrupted()) {
return null;
}
} while (queueEntryJson == null);
QueueEntry.Builder queueEntryBuilder = QueueEntry.newBuilder();
try {
JsonFormat.parser().merge(queueEntryJson, queueEntryBuilder);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error parsing queue entry", e);
return null;
}
QueueEntry queueEntry = queueEntryBuilder.build();
String operationName = queueEntry.getExecuteEntry().getOperationName();
Operation operation = keepaliveOperation(operationName);
publishReset(jedis, operation);
long requeueAt = System.currentTimeMillis() + 30 * 1000;
DispatchedOperation o = DispatchedOperation.newBuilder()
.setQueueEntry(queueEntry)
.setRequeueAt(requeueAt)
.build();
boolean success = false;
try {
String dispatchedOperationJson = JsonFormat.printer().print(o);
/* if the operation is already in the dispatch list, fail the dispatch */
success = jedis.hsetnx(
config.getDispatchedOperationsHashName(),
operationName,
dispatchedOperationJson) == 1;
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing dispatched operation", e);
// very unlikely, printer would have to fail
}
if (success) {
if (jedis.lrem(config.getDispatchingListName(), -1, queueEntryJson) == 0) {
logger.warning(
format(
"operation %s was missing in %s, may be orphaned",
operationName,
config.getDispatchingListName()));
}
jedis.del(dispatchingKey(operationName)); // may or may not exist
return queueEntry;
}
return null;
}
@Override
public QueueEntry dispatchOperation() throws IOException, InterruptedException {
QueueEntry queueEntry = withBackplaneException(this::dispatchOperation);
if (Thread.interrupted()) {
throw new InterruptedException();
}
return queueEntry;
}
@Override
public boolean pollOperation(QueueEntry queueEntry, ExecutionStage.Value stage, long requeueAt) throws IOException {
String operationName = queueEntry.getExecuteEntry().getOperationName();
DispatchedOperation o = DispatchedOperation.newBuilder()
.setQueueEntry(queueEntry)
.setRequeueAt(requeueAt)
.build();
String json;
try {
json = JsonFormat.printer().print(o);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing dispatched operation " + operationName, e);
return false;
}
return withBackplaneException((jedis) -> {
if (jedis.hexists(config.getDispatchedOperationsHashName(), operationName)) {
if (jedis.hset(config.getDispatchedOperationsHashName(), operationName, json) == 0) {
return true;
}
/* someone else beat us to the punch, delete our incorrectly added key */
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
}
return false;
});
}
@Override
public void prequeue(ExecuteEntry executeEntry, Operation operation) throws IOException {
String operationName = operation.getName();
String operationJson = operationPrinter.print(operation);
String executeEntryJson = JsonFormat.printer().print(executeEntry);
Operation publishOperation = onPublish.apply(operation);
withVoidBackplaneException((jedis) -> {
jedis.setex(operationKey(operationName), config.getOperationExpire(), operationJson);
jedis.lpush(config.getPreQueuedOperationsListName(), executeEntryJson);
publishReset(jedis, publishOperation);
});
}
private Operation keepaliveOperation(String operationName) {
return Operation.newBuilder()
.setName(operationName)
.build();
}
@Override
public void queueing(String operationName) throws IOException {
Operation operation = keepaliveOperation(operationName);
// publish so that watchers reset their timeout
withVoidBackplaneException((jedis) -> {
publishReset(jedis, operation);
});
}
@Override
public void requeueDispatchedOperation(QueueEntry queueEntry) throws IOException {
String queueEntryJson = JsonFormat.printer().print(queueEntry);
String operationName = queueEntry.getExecuteEntry().getOperationName();
Operation publishOperation = keepaliveOperation(operationName);
withVoidBackplaneException((jedis) -> {
queue(jedis, operationName, queueEntryJson);
publishReset(jedis, publishOperation);
});
}
private void completeOperation(JedisCluster jedis, String operationName) {
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
}
@Override
public void completeOperation(String operationName) throws IOException {
withVoidBackplaneException((jedis) -> completeOperation(jedis, operationName));
}
@Override
public void deleteOperation(String operationName) throws IOException {
Operation o = Operation.newBuilder()
.setName(operationName)
.setDone(true)
.setError(com.google.rpc.Status.newBuilder()
.setCode(Code.UNAVAILABLE.value())
.build())
.build();
String json;
try {
json = JsonFormat.printer().print(o);
} catch (InvalidProtocolBufferException e) {
json = null;
logger.log(SEVERE, "error printing deleted operation " + operationName, e);
}
withVoidBackplaneException((jedis) -> {
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
// FIXME find a way to get rid of this thing from the queue by name
// jedis.lrem(config.getQueuedOperationsListName(), 0, operationName);
jedis.del(operationKey(operationName));
publishReset(jedis, o);
});
}
private JedisCluster getSubscribeJedis() throws IOException {
if (!poolStarted) {
throw new IOException(
Status.UNAVAILABLE.withDescription("backend is not started").asRuntimeException());
}
return jedisClusterFactory.get();
}
private JedisCluster getJedis() throws IOException {
if (!poolStarted) {
throw new IOException(
Status.UNAVAILABLE.withDescription("backend is not started").asRuntimeException());
}
return jedisCluster;
}
private String casKey(Digest blobDigest) {
return config.getCasPrefix() + ":" + DigestUtil.toString(blobDigest);
}
private String acKey(ActionKey actionKey) {
return config.getActionCachePrefix() + ":" + DigestUtil.toString(actionKey.getDigest());
}
private String operationKey(String operationName) {
return config.getOperationPrefix() + ":" + operationName;
}
private String operationChannel(String operationName) {
return config.getOperationChannelPrefix() + ":" + operationName;
}
private String processingKey(String operationName) {
return config.getProcessingPrefix() + ":" + operationName;
}
private String dispatchingKey(String operationName) {
return config.getDispatchingPrefix() + ":" + operationName;
}
public static String parseOperationChannel(String channel) {
return channel.split(":")[1];
}
@Override
public boolean canQueue() throws IOException {
int maxQueueDepth = config.getMaxQueueDepth();
return maxQueueDepth < 0
|| withBackplaneException((jedis) -> jedis.llen(config.getQueuedOperationsListName()) < maxQueueDepth);
}
@Override
public boolean canPrequeue() throws IOException {
int maxPreQueueDepth = config.getMaxPreQueueDepth();
return maxPreQueueDepth < 0
|| withBackplaneException((jedis) -> jedis.llen(config.getPreQueuedOperationsListName()) < maxPreQueueDepth);
}
}
|
src/main/java/build/buildfarm/instance/shard/RedisShardBackplane.java
|
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.instance.shard;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static java.lang.String.format;
import static java.util.logging.Level.SEVERE;
import build.bazel.remote.execution.v2.ActionResult;
import build.bazel.remote.execution.v2.Digest;
import build.bazel.remote.execution.v2.ExecuteOperationMetadata;
import build.bazel.remote.execution.v2.ExecutionStage;
import build.buildfarm.common.DigestUtil;
import build.buildfarm.common.DigestUtil.ActionKey;
import build.buildfarm.common.ShardBackplane;
import build.buildfarm.common.Watcher;
import build.buildfarm.common.function.InterruptingRunnable;
import build.buildfarm.instance.shard.RedisShardSubscriber.TimedWatchFuture;
import build.buildfarm.v1test.CompletedOperationMetadata;
import build.buildfarm.v1test.DispatchedOperation;
import build.buildfarm.v1test.ExecuteEntry;
import build.buildfarm.v1test.ExecutingOperationMetadata;
import build.buildfarm.v1test.OperationChange;
import build.buildfarm.v1test.QueueEntry;
import build.buildfarm.v1test.QueuedOperationMetadata;
import build.buildfarm.v1test.RedisShardBackplaneConfig;
import build.buildfarm.v1test.ShardWorker;
import build.buildfarm.v1test.WorkerChange;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.longrunning.Operation;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.JsonFormat;
import com.google.rpc.PreconditionFailure;
import io.grpc.Status;
import io.grpc.Status.Code;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.time.Instant;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.naming.ConfigurationException;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisClusterPipeline;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Response;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException;
public class RedisShardBackplane implements ShardBackplane {
private static final Logger logger = Logger.getLogger(RedisShardBackplane.class.getName());
private static final JsonFormat.Parser operationParser = JsonFormat.parser()
.usingTypeRegistry(
JsonFormat.TypeRegistry.newBuilder()
.add(CompletedOperationMetadata.getDescriptor())
.add(ExecutingOperationMetadata.getDescriptor())
.add(ExecuteOperationMetadata.getDescriptor())
.add(QueuedOperationMetadata.getDescriptor())
.add(PreconditionFailure.getDescriptor())
.build())
.ignoringUnknownFields();
private static final JsonFormat.Printer operationPrinter = JsonFormat.printer().usingTypeRegistry(
JsonFormat.TypeRegistry.newBuilder()
.add(CompletedOperationMetadata.getDescriptor())
.add(ExecutingOperationMetadata.getDescriptor())
.add(ExecuteOperationMetadata.getDescriptor())
.add(QueuedOperationMetadata.getDescriptor())
.add(PreconditionFailure.getDescriptor())
.build());
private final RedisShardBackplaneConfig config;
private final String source; // used in operation change publication
private final Function<Operation, Operation> onPublish;
private final Function<Operation, Operation> onComplete;
private final Predicate<Operation> isPrequeued;
private final Predicate<Operation> isDispatched;
private final Supplier<JedisCluster> jedisClusterFactory;
private @Nullable InterruptingRunnable onUnsubscribe = null;
private Thread subscriptionThread = null;
private Thread failsafeOperationThread = null;
private RedisShardSubscriber subscriber = null;
private RedisShardSubscription operationSubscription = null;
private ExecutorService subscriberService = null;
private boolean poolStarted = false;
private @Nullable JedisCluster jedisCluster = null;
private Set<String> workerSet = Collections.synchronizedSet(new HashSet<>());
private long workerSetExpiresAt = 0;
private static class JedisMisconfigurationException extends JedisDataException {
public JedisMisconfigurationException(final String message) {
super(message);
}
public JedisMisconfigurationException(final Throwable cause) {
super(cause);
}
public JedisMisconfigurationException(final String message, final Throwable cause) {
super(message, cause);
}
}
private static JedisPoolConfig createJedisPoolConfig(RedisShardBackplaneConfig config) {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(config.getJedisPoolMaxTotal());
return jedisPoolConfig;
}
private static URI parseRedisURI(String redisURI) throws ConfigurationException {
try {
return new URI(redisURI);
} catch (URISyntaxException e) {
throw new ConfigurationException(e.getMessage());
}
}
private static Supplier<JedisCluster> createJedisClusterFactory(URI redisURI, JedisPoolConfig poolConfig) {
return () -> new JedisCluster(
new HostAndPort(redisURI.getHost(), redisURI.getPort()),
poolConfig);
}
public RedisShardBackplane(
RedisShardBackplaneConfig config,
String source,
Function<Operation, Operation> onPublish,
Function<Operation, Operation> onComplete,
Predicate<Operation> isPrequeued,
Predicate<Operation> isDispatched) throws ConfigurationException {
this(
config,
source,
onPublish,
onComplete,
isPrequeued,
isDispatched,
createJedisClusterFactory(parseRedisURI(config.getRedisUri()), createJedisPoolConfig(config)));
}
public RedisShardBackplane(
RedisShardBackplaneConfig config,
String source,
Function<Operation, Operation> onPublish,
Function<Operation, Operation> onComplete,
Predicate<Operation> isPrequeued,
Predicate<Operation> isDispatched,
Supplier<JedisCluster> jedisClusterFactory) {
this.config = config;
this.source = source;
this.onPublish = onPublish;
this.onComplete = onComplete;
this.isPrequeued = isPrequeued;
this.isDispatched = isDispatched;
this.jedisClusterFactory = jedisClusterFactory;
}
@Override
public InterruptingRunnable setOnUnsubscribe(InterruptingRunnable onUnsubscribe) {
InterruptingRunnable oldOnUnsubscribe = this.onUnsubscribe;
this.onUnsubscribe = onUnsubscribe;
return oldOnUnsubscribe;
}
private Instant getExpiresAt(JedisCluster jedis, String key, Instant now) {
String value = jedis.get(key);
if (value != null) {
try {
return Instant.ofEpochMilli(Long.parseLong(value));
} catch (NumberFormatException e) {
logger.severe(format("invalid expiration %s for %s", value, key));
}
}
Instant expiresAt = now.plusMillis(config.getProcessingTimeoutMillis());
jedis.setex(
key,
/* expire=*/ (config.getProcessingTimeoutMillis() * 2) / 1000,
String.format("%d", expiresAt.toEpochMilli()));
return expiresAt;
}
abstract static class ListVisitor {
private static final int LIST_PAGE_SIZE = 10000;
protected abstract void visit(String entry);
// this can potentially operate over the same set of entries in multiple steps
public static void visit(JedisCluster jedis, String name, ListVisitor visitor) {
int index = 0;
int nextIndex = LIST_PAGE_SIZE;
List<String> entries;
do {
entries = jedis.lrange(name, index, nextIndex - 1);
for (String entry : entries) {
visitor.visit(entry);
}
index = nextIndex;
nextIndex += entries.size();
} while (entries.size() == LIST_PAGE_SIZE);
}
}
abstract static class QueueEntryListVisitor extends ListVisitor {
protected abstract void visit(QueueEntry queueEntry, String queueEntryJson);
@Override
protected void visit(String entry) {
QueueEntry.Builder queueEntry = QueueEntry.newBuilder();
try {
JsonFormat.parser().merge(entry, queueEntry);
visit(queueEntry.build(), entry);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "invalid QueueEntry json: " + entry, e);
}
}
}
abstract static class ExecuteEntryListVisitor extends ListVisitor {
protected abstract void visit(ExecuteEntry executeEntry, String executeEntryJson);
@Override
protected void visit(String entry) {
ExecuteEntry.Builder executeEntry = ExecuteEntry.newBuilder();
try {
JsonFormat.parser().merge(entry, executeEntry);
visit(executeEntry.build(), entry);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "invalid ExecuteEntry json: " + entry, e);
}
}
}
private void scanProcessing(JedisCluster jedis, Consumer<String> onOperationName, Instant now) {
ListVisitor.visit(
jedis,
config.getProcessingListName(),
new ExecuteEntryListVisitor() {
@Override
protected void visit(ExecuteEntry executeEntry, String executeEntryJson) {
String operationName = executeEntry.getOperationName();
String operationProcessingKey = processingKey(operationName);
Instant expiresAt = getExpiresAt(jedis, operationProcessingKey, now);
if (now.isBefore(expiresAt)) {
onOperationName.accept(operationName);
} else {
if (jedis.lrem(config.getProcessingListName(), -1, executeEntryJson) != 0) {
jedis.del(operationProcessingKey);
}
}
}
});
}
private void scanDispatching(JedisCluster jedis, Consumer<String> onOperationName, Instant now) {
ListVisitor.visit(
jedis,
config.getDispatchingListName(),
new QueueEntryListVisitor() {
@Override
protected void visit(QueueEntry queueEntry, String queueEntryJson) {
String operationName = queueEntry.getExecuteEntry().getOperationName();
String operationDispatchingKey = dispatchingKey(operationName);
Instant expiresAt = getExpiresAt(jedis, operationDispatchingKey, now);
if (now.isBefore(expiresAt)) {
onOperationName.accept(operationName);
} else {
if (jedis.lrem(config.getDispatchingListName(), -1, queueEntryJson) != 0) {
jedis.del(operationDispatchingKey);
}
}
}
});
}
private void scanPrequeue(JedisCluster jedis, Consumer<String> onOperationName) {
ListVisitor.visit(
jedis,
config.getPreQueuedOperationsListName(),
new ExecuteEntryListVisitor() {
@Override
protected void visit(ExecuteEntry executeEntry, String executeEntryJson) {
onOperationName.accept(executeEntry.getOperationName());
}
});
}
private void scanQueue(JedisCluster jedis, Consumer<String> onOperationName) {
ListVisitor.visit(
jedis,
config.getQueuedOperationsListName(),
new QueueEntryListVisitor() {
@Override
protected void visit(QueueEntry queueEntry, String queueEntryJson) {
onOperationName.accept(queueEntry.getExecuteEntry().getOperationName());
}
});
}
private void scanDispatched(JedisCluster jedis, Consumer<String> onOperationName) {
for (String operationName : jedis.hkeys(config.getDispatchedOperationsHashName())) {
onOperationName.accept(operationName);
}
}
private void updateWatchers(JedisCluster jedis) {
Instant now = Instant.now();
Instant expiresAt = nextExpiresAt(now);
Set<String> expiringChannels = Sets.newHashSet(
subscriber.expiredWatchedOperationChannels(now));
Consumer<String> resetChannel = (operationName) -> {
String channel = operationChannel(operationName);
if (expiringChannels.remove(channel)) {
subscriber.resetWatchers(channel, expiresAt);
}
};
if (!expiringChannels.isEmpty()) {
logger.info(
format(
"Scan %d watches, %s, expiresAt: %s",
expiringChannels.size(),
now,
expiresAt));
logger.info("Scan prequeue");
// scan prequeue, pet watches
scanPrequeue(jedis, resetChannel);
}
// scan processing, create ttl key if missing, remove dead entries, pet live watches
scanProcessing(jedis, resetChannel, now);
if (!expiringChannels.isEmpty()) {
logger.info("Scan queue");
// scan queue, pet watches
scanQueue(jedis, resetChannel);
}
// scan dispatching, create ttl key if missing, remove dead entries, pet live watches
scanDispatching(jedis, resetChannel, now);
if (!expiringChannels.isEmpty()) {
logger.info("Scan dispatched");
// scan dispatched pet watches
scanDispatched(jedis, resetChannel);
}
//
// filter watches on expiration
// delete the operation?
// update expired watches with null operation
for (String channel : expiringChannels) {
Operation operation = parseOperationJson(getOperation(jedis, parseOperationChannel(channel)));
if (operation == null || !operation.getDone()) {
publishExpiration(jedis, channel, now, /* force=*/ false);
} else {
subscriber.onOperation(
channel,
onPublish.apply(operation),
expiresAt);
}
}
}
static String printOperationChange(OperationChange operationChange) throws InvalidProtocolBufferException {
return operationPrinter.print(operationChange);
}
void publish(JedisCluster jedis, String channel, Instant effectiveAt, OperationChange.Builder operationChange) {
try {
String operationChangeJson = printOperationChange(
operationChange
.setEffectiveAt(toTimestamp(effectiveAt))
.setSource(source)
.build());
jedis.publish(channel, operationChangeJson);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing operation change", e);
// very unlikely, printer would have to fail
}
}
void publishReset(JedisCluster jedis, Operation operation) {
Instant effectiveAt = Instant.now();
Instant expiresAt = nextExpiresAt(effectiveAt);
publish(
jedis,
operationChannel(operation.getName()),
Instant.now(),
OperationChange.newBuilder()
.setReset(OperationChange.Reset.newBuilder()
.setExpiresAt(toTimestamp(expiresAt))
.setOperation(operation)
.build()));
}
static Timestamp toTimestamp(Instant instant) {
return Timestamp.newBuilder()
.setSeconds(instant.getEpochSecond())
.setNanos(instant.getNano())
.build();
}
void publishExpiration(JedisCluster jedis, String channel, Instant effectiveAt, boolean force) {
publish(
jedis,
channel,
effectiveAt,
OperationChange.newBuilder()
.setExpire(OperationChange.Expire.newBuilder()
.setForce(force)
.build()));
}
public void updateWatchedIfDone(JedisCluster jedis) {
List<String> operationChannels = subscriber.watchedOperationChannels();
if (operationChannels.isEmpty()) {
return;
}
Instant now = Instant.now();
List<Map.Entry<String, Response<String>>> operations = new ArrayList(operationChannels.size());
JedisClusterPipeline p = jedis.pipelined();
for (String operationName : Iterables.transform(operationChannels, RedisShardBackplane::parseOperationChannel)) {
operations.add(new AbstractMap.SimpleEntry<>(
operationName,
p.get(operationKey(operationName))));
}
p.sync();
for (Map.Entry<String, Response<String>> entry : operations) {
String json = entry.getValue().get();
Operation operation = json == null
? null : RedisShardBackplane.parseOperationJson(json);
String operationName = entry.getKey();
if (operation == null || operation.getDone()) {
if (operation != null) {
operation = onPublish.apply(operation);
}
subscriber.onOperation(
operationChannel(operationName),
operation,
nextExpiresAt(now));
logger.info(
format(
"operation %s done due to %s",
operationName,
operation == null ? "null" : "completed"));
}
}
}
private Instant nextExpiresAt(Instant from) {
return from.plusSeconds(10);
}
private void startSubscriptionThread() {
ListMultimap<String, TimedWatchFuture> watchers =
Multimaps.<String, TimedWatchFuture>synchronizedListMultimap(
MultimapBuilder.linkedHashKeys().arrayListValues().build());
subscriberService = Executors.newFixedThreadPool(32);
subscriber = new RedisShardSubscriber(watchers, workerSet, config.getWorkerChannel(), subscriberService);
operationSubscription = new RedisShardSubscription(
subscriber,
/* onUnsubscribe=*/ () -> {
subscriptionThread = null;
if (onUnsubscribe != null) {
onUnsubscribe.runInterruptibly();
}
},
/* onReset=*/ this::updateWatchedIfDone,
/* subscriptions=*/ subscriber::subscribedChannels,
this::getSubscribeJedis);
// use Executors...
subscriptionThread = new Thread(operationSubscription);
subscriptionThread.start();
}
private void startFailsafeOperationThread() {
failsafeOperationThread = new Thread(() -> {
while (true) {
try {
TimeUnit.SECONDS.sleep(10);
updateWatchers(jedisCluster);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
logger.log(SEVERE, "error while updating watchers in failsafe", e);
}
}
});
failsafeOperationThread.start();
}
@Override
public void start() {
poolStarted = true;
if (config.getSubscribeToBackplane()) {
startSubscriptionThread();
}
if (config.getRunFailsafeOperation()) {
startFailsafeOperationThread();
}
jedisCluster = jedisClusterFactory.get();
}
@Override
public synchronized void stop() throws InterruptedException {
if (failsafeOperationThread != null) {
failsafeOperationThread.stop();
failsafeOperationThread.join();
logger.fine("failsafeOperationThread has been stopped");
}
if (operationSubscription != null) {
operationSubscription.stop();
if (subscriptionThread != null) {
subscriptionThread.join();
}
logger.fine("subscriptionThread has been stopped");
}
if (subscriberService != null) {
subscriberService.shutdown();
subscriberService.awaitTermination(10, TimeUnit.SECONDS);
logger.fine("subscriberService has been stopped");
}
if (jedisCluster != null) {
poolStarted = false;
jedisCluster.close();
jedisCluster = null;
logger.fine("pool has been closed");
}
}
@Override
public boolean isStopped() {
return !poolStarted;
}
@Override
public ListenableFuture<Void> watchOperation(
String operationName,
Watcher watcher) throws IOException {
TimedWatcher timedWatcher = new TimedWatcher(nextExpiresAt(Instant.now())) {
@Override
public void observe(Operation operation) {
watcher.observe(operation);
}
};
return subscriber.watch(
operationChannel(operationName),
timedWatcher);
}
@Override
public boolean addWorker(ShardWorker shardWorker) throws IOException {
String json = JsonFormat.printer().print(shardWorker);
String workerChangeJson = JsonFormat.printer().print(
WorkerChange.newBuilder()
.setEffectiveAt(toTimestamp(Instant.now()))
.setName(shardWorker.getEndpoint())
.setAdd(WorkerChange.Add.getDefaultInstance())
.build());
return withBackplaneException(
(jedis) -> {
// could rework with an hget to publish prior, but this seems adequate, and
// we are the only guaranteed source
if (jedis.hset(config.getWorkersHashName(), shardWorker.getEndpoint(), json) == 1) {
jedis.publish(config.getWorkerChannel(), workerChangeJson);
return true;
}
return false;
});
}
private static final String MISCONF_RESPONSE = "MISCONF";
@FunctionalInterface
private static interface JedisContext<T> {
T run(JedisCluster jedis) throws JedisException;
}
@VisibleForTesting
public void withVoidBackplaneException(Consumer<JedisCluster> withJedis) throws IOException {
withBackplaneException(new JedisContext<Void>() {
@Override
public Void run(JedisCluster jedis) throws JedisException {
withJedis.accept(jedis);
return null;
}
});
}
@VisibleForTesting
public <T> T withBackplaneException(JedisContext<T> withJedis) throws IOException {
try {
try {
return withJedis.run(jedisCluster);
} catch (JedisDataException e) {
if (e.getMessage().startsWith(MISCONF_RESPONSE)) {
throw new JedisMisconfigurationException(e.getMessage());
}
throw e;
}
} catch (JedisMisconfigurationException e) {
// the backplane is configured not to accept writes currently
// as a result of an error. The error is meant to indicate
// that substantial resources were unavailable.
// we must throw an IOException which indicates as much
// this looks simply to me like a good opportunity to use UNAVAILABLE
// we are technically not at RESOURCE_EXHAUSTED, this is a
// persistent state which can exist long past the error
throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException());
} catch (JedisNoReachableClusterNodeException e) {
throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException());
} catch (JedisConnectionException e) {
if ((e.getMessage() != null && e.getMessage().equals("Unexpected end of stream."))
|| e.getCause() instanceof ConnectException) {
throw new IOException(Status.UNAVAILABLE.withCause(e).asRuntimeException());
}
Throwable cause = e;
Status status = Status.UNKNOWN;
while (status.getCode() == Code.UNKNOWN && cause != null) {
String message = cause.getMessage() == null ? "" : cause.getMessage();
if ((cause instanceof SocketException && cause.getMessage().equals("Connection reset"))
|| cause instanceof ConnectException
|| message.equals("Unexpected end of stream.")) {
status = Status.UNAVAILABLE;
} else if (cause instanceof SocketTimeoutException) {
status = Status.DEADLINE_EXCEEDED;
} else if (cause instanceof IOException) {
throw (IOException) cause;
} else {
cause = cause.getCause();
}
}
throw new IOException(status.withCause(cause == null ? e : cause).asRuntimeException());
}
}
@Override
public boolean removeWorker(String workerName) throws IOException {
WorkerChange workerChange = WorkerChange.newBuilder()
.setName(workerName)
.setRemove(WorkerChange.Remove.newBuilder()
.setSource(source)
.build())
.build();
String workerChangeJson = JsonFormat.printer().print(workerChange);
return subscriber.removeWorker(workerName) &&
withBackplaneException((jedis) -> {
if (jedis.hdel(config.getWorkersHashName(), workerName) == 1) {
jedis.publish(config.getWorkerChannel(), workerChangeJson);
return true;
}
return false;
});
}
@Override
public synchronized Set<String> getWorkers() throws IOException {
long now = System.currentTimeMillis();
if (now < workerSetExpiresAt) {
return workerSet;
}
synchronized (workerSet) {
Set<String> newWorkerSet = withBackplaneException((jedis) -> fetchAndExpireWorkers(jedis, now));
workerSet.clear();
workerSet.addAll(newWorkerSet);
}
// fetch every 3 seconds
workerSetExpiresAt = now + 3000;
return workerSet;
}
private Set<String> fetchAndExpireWorkers(JedisCluster jedis, long now) {
Set<String> workers = Sets.newConcurrentHashSet();
ImmutableList.Builder<String> invalidWorkers = ImmutableList.builder();
for (Map.Entry<String, String> entry : jedis.hgetAll(config.getWorkersHashName()).entrySet()) {
String json = entry.getValue();
String name = entry.getKey();
try {
if (json == null) {
invalidWorkers.add(name);
} else {
ShardWorker.Builder builder = ShardWorker.newBuilder();
JsonFormat.parser().merge(json, builder);
ShardWorker worker = builder.build();
if (worker.getExpireAt() <= now) {
invalidWorkers.add(name);
} else {
workers.add(worker.getEndpoint());
}
}
} catch (InvalidProtocolBufferException e) {
invalidWorkers.add(name);
}
}
JedisClusterPipeline p = jedis.pipelined();
for (String invalidWorker : invalidWorkers.build()) {
p.hdel(config.getWorkersHashName(), invalidWorker);
}
p.sync();
return workers;
}
private static ActionResult parseActionResult(String json) {
try {
ActionResult.Builder builder = ActionResult.newBuilder();
JsonFormat.parser().merge(json, builder);
return builder.build();
} catch (InvalidProtocolBufferException e) {
return null;
}
}
@Override
public ActionResult getActionResult(ActionKey actionKey) throws IOException {
String json = withBackplaneException((jedis) -> jedis.get(acKey(actionKey)));
if (json == null) {
return null;
}
ActionResult actionResult = parseActionResult(json);
if (actionResult == null) {
withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey));
}
return actionResult;
}
@Override
public void putActionResult(ActionKey actionKey, ActionResult actionResult)
throws IOException {
String json = JsonFormat.printer().print(actionResult);
withVoidBackplaneException((jedis) -> jedis.setex(acKey(actionKey), config.getActionCacheExpire(), json));
}
private void removeActionResult(JedisCluster jedis, ActionKey actionKey) {
jedis.del(acKey(actionKey));
}
@Override
public void removeActionResult(ActionKey actionKey) throws IOException {
withVoidBackplaneException((jedis) -> removeActionResult(jedis, actionKey));
}
@Override
public void removeActionResults(Iterable<ActionKey> actionKeys) throws IOException {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (ActionKey actionKey : actionKeys) {
p.del(acKey(actionKey));
}
p.sync();
});
}
@Override
public ActionCacheScanResult scanActionCache(String scanToken, int count) throws IOException {
final String jedisScanToken = scanToken == null ? SCAN_POINTER_START : scanToken;
ImmutableList.Builder<Map.Entry<ActionKey, String>> results = new ImmutableList.Builder<>();
ScanParams scanParams = new ScanParams()
.match(config.getActionCachePrefix() + ":*")
.count(count);
String token = withBackplaneException((jedis) -> {
ScanResult<String> scanResult = jedis.scan(jedisScanToken, scanParams);
List<String> keyResults = scanResult.getResult();
List<Response<String>> actionResults = new ArrayList<>(keyResults.size());
JedisClusterPipeline p = jedis.pipelined();
for (int i = 0; i < keyResults.size(); i++) {
actionResults.add(p.get(keyResults.get(i)));
}
p.sync();
for (int i = 0; i < keyResults.size(); i++) {
String json = actionResults.get(i).get();
if (json == null) {
continue;
}
String key = keyResults.get(i);
results.add(new AbstractMap.SimpleEntry<>(
DigestUtil.asActionKey(DigestUtil.parseDigest(key.split(":")[1])),
json));
}
String cursor = scanResult.getCursor();
return cursor.equals(SCAN_POINTER_START) ? null : cursor;
});
return new ActionCacheScanResult(
token,
Iterables.transform(
results.build(),
(entry) -> new AbstractMap.SimpleEntry<>(
entry.getKey(),
parseActionResult(entry.getValue()))));
}
@Override
public void adjustBlobLocations(Digest blobDigest, Set<String> addWorkers, Set<String> removeWorkers) throws IOException {
String key = casKey(blobDigest);
withVoidBackplaneException((jedis) -> {
for (String workerName : addWorkers) {
jedis.sadd(key, workerName);
}
for (String workerName : removeWorkers) {
jedis.srem(key, workerName);
}
jedis.expire(key, config.getCasExpire());
});
}
@Override
public void addBlobLocation(Digest blobDigest, String workerName) throws IOException {
String key = casKey(blobDigest);
withVoidBackplaneException((jedis) -> {
jedis.sadd(key, workerName);
jedis.expire(key, config.getCasExpire());
});
}
@Override
public void addBlobsLocation(Iterable<Digest> blobDigests, String workerName)
throws IOException {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (Digest blobDigest : blobDigests) {
String key = casKey(blobDigest);
p.sadd(key, workerName);
p.expire(key, config.getCasExpire());
}
p.sync();
});
}
@Override
public void removeBlobLocation(Digest blobDigest, String workerName) throws IOException {
String key = casKey(blobDigest);
withVoidBackplaneException((jedis) -> jedis.srem(key, workerName));
}
@Override
public void removeBlobsLocation(Iterable<Digest> blobDigests, String workerName)
throws IOException {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (Digest blobDigest : blobDigests) {
p.srem(casKey(blobDigest), workerName);
}
p.sync();
});
}
@Override
public String getBlobLocation(Digest blobDigest) throws IOException {
return withBackplaneException((jedis) -> jedis.srandmember(casKey(blobDigest)));
}
@Override
public Set<String> getBlobLocationSet(Digest blobDigest) throws IOException {
return withBackplaneException((jedis) -> jedis.smembers(casKey(blobDigest)));
}
@Override
public Map<Digest, Set<String>> getBlobDigestsWorkers(Iterable<Digest> blobDigests)
throws IOException {
// FIXME pipeline
ImmutableMap.Builder<Digest, Set<String>> blobDigestsWorkers = new ImmutableMap.Builder<>();
withVoidBackplaneException((jedis) -> {
for (Digest blobDigest : blobDigests) {
Set<String> workers = jedis.smembers(casKey(blobDigest));
if (workers.isEmpty()) {
continue;
}
blobDigestsWorkers.put(blobDigest, workers);
}
});
return blobDigestsWorkers.build();
}
public static WorkerChange parseWorkerChange(String workerChangeJson) throws InvalidProtocolBufferException {
WorkerChange.Builder workerChange = WorkerChange.newBuilder();
JsonFormat.parser().merge(workerChangeJson, workerChange);
return workerChange.build();
}
public static OperationChange parseOperationChange(String operationChangeJson) throws InvalidProtocolBufferException {
OperationChange.Builder operationChange = OperationChange.newBuilder();
operationParser.merge(operationChangeJson, operationChange);
return operationChange.build();
}
public static Operation parseOperationJson(String operationJson) {
if (operationJson == null) {
return null;
}
try {
Operation.Builder operationBuilder = Operation.newBuilder();
operationParser.merge(operationJson, operationBuilder);
return operationBuilder.build();
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error parsing operation from " + operationJson, e);
return null;
}
}
private String getOperation(JedisCluster jedis, String operationName) {
String json = jedis.get(operationKey(operationName));
if (json == null) {
return null;
}
return json;
}
@Override
public Operation getOperation(String operationName) throws IOException {
String json = withBackplaneException((jedis) -> getOperation(jedis, operationName));
return parseOperationJson(json);
}
@Override
public boolean putOperation(Operation operation, ExecutionStage.Value stage) throws IOException {
// FIXME queue and prequeue should no longer be passed to here
boolean prequeue = stage == ExecutionStage.Value.UNKNOWN && !operation.getDone();
boolean queue = stage == ExecutionStage.Value.QUEUED;
boolean complete = !queue && operation.getDone();
boolean publish = !queue && stage != ExecutionStage.Value.UNKNOWN;
if (complete) {
// for filtering anything that shouldn't be stored
operation = onComplete.apply(operation);
}
String json;
try {
json = operationPrinter.print(operation);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing operation " + operation.getName(), e);
return false;
}
Operation publishOperation;
if (publish) {
publishOperation = onPublish.apply(operation);
} else {
publishOperation = null;
}
String name = operation.getName();
withVoidBackplaneException((jedis) -> {
if (complete) {
completeOperation(jedis, name);
}
jedis.setex(operationKey(name), config.getOperationExpire(), json);
if (publishOperation != null) {
publishReset(jedis, publishOperation);
}
});
return true;
}
private void queue(JedisCluster jedis, String operationName, String queueEntryJson) {
if (jedis.hdel(config.getDispatchedOperationsHashName(), operationName) == 1) {
logger.warning(format("removed dispatched operation %s", operationName));
}
jedis.lpush(config.getQueuedOperationsListName(), queueEntryJson);
}
@Override
public void queue(QueueEntry queueEntry, Operation operation) throws IOException {
String operationName = operation.getName();
String operationJson = operationPrinter.print(operation);
String queueEntryJson = JsonFormat.printer().print(queueEntry);
Operation publishOperation = onPublish.apply(operation);
withVoidBackplaneException((jedis) -> {
jedis.setex(operationKey(operationName), config.getOperationExpire(), operationJson);
queue(jedis, operation.getName(), queueEntryJson);
publishReset(jedis, publishOperation);
});
}
public Map<String, Operation> getOperationsMap() throws IOException {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
withVoidBackplaneException((jedis) -> {
for (Map.Entry<String, String> entry : jedis.hgetAll(config.getDispatchedOperationsHashName()).entrySet()) {
builder.put(entry.getKey(), entry.getValue());
}
});
return Maps.transformValues(builder.build(), RedisShardBackplane::parseOperationJson);
}
@Override
public Iterable<String> getOperations() throws IOException {
throw new UnsupportedOperationException();
/*
return withVoidBackplaneException((jedis) -> {
Iterable<String> dispatchedOperations = jedis.hkeys(config.getDispatchedOperationsHashName());
Iterable<String> queuedOperations = jedis.lrange(config.getQueuedOperationsListName(), 0, -1);
return Iterables.concat(queuedOperations, dispatchedOperations, getCompletedOperations(jedis));
});
*/
}
@Override
public ImmutableList<DispatchedOperation> getDispatchedOperations() throws IOException {
ImmutableList.Builder<DispatchedOperation> builder = new ImmutableList.Builder<>();
Map<String, String> dispatchedOperations = withBackplaneException((jedis) -> jedis.hgetAll(config.getDispatchedOperationsHashName()));
ImmutableList.Builder<String> invalidOperationNames = new ImmutableList.Builder<>();
boolean hasInvalid = false;
// executor work queue?
for (Map.Entry<String, String> entry : dispatchedOperations.entrySet()) {
try {
DispatchedOperation.Builder dispatchedOperationBuilder = DispatchedOperation.newBuilder();
JsonFormat.parser().merge(entry.getValue(), dispatchedOperationBuilder);
builder.add(dispatchedOperationBuilder.build());
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "RedisShardBackplane::getDispatchedOperations: removing invalid operation " + entry.getKey(), e);
/* guess we don't want to spin on this */
invalidOperationNames.add(entry.getKey());
hasInvalid = true;
}
}
if (hasInvalid) {
withVoidBackplaneException((jedis) -> {
JedisClusterPipeline p = jedis.pipelined();
for (String invalidOperationName : invalidOperationNames.build()) {
p.hdel(config.getDispatchedOperationsHashName(), invalidOperationName);
}
p.sync();
});
}
return builder.build();
}
private ExecuteEntry deprequeueOperation(JedisCluster jedis) {
String executeEntryJson;
do {
executeEntryJson = jedis.brpoplpush(
config.getPreQueuedOperationsListName(),
config.getProcessingListName(),
1);
if (Thread.currentThread().isInterrupted()) {
return null;
}
} while (executeEntryJson == null);
ExecuteEntry.Builder executeEntryBuilder = ExecuteEntry.newBuilder();
try {
JsonFormat.parser().merge(executeEntryJson, executeEntryBuilder);
ExecuteEntry executeEntry = executeEntryBuilder.build();
String operationName = executeEntry.getOperationName();
Operation operation = keepaliveOperation(operationName);
// publish so that watchers reset their timeout
publishReset(jedis, operation);
// destroy the processing entry and ttl
if (jedis.lrem(config.getProcessingListName(), -1, executeEntryJson) == 0) {
logger.severe(
format(
"could not remove %s from %s",
operationName,
config.getProcessingListName()));
return null;
}
jedis.del(processingKey(operationName)); // may or may not exist
return executeEntry;
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error parsing execute entry", e);
return null;
}
}
@Override
public ExecuteEntry deprequeueOperation() throws IOException, InterruptedException {
ExecuteEntry executeEntry = withBackplaneException(this::deprequeueOperation);
if (Thread.interrupted()) {
throw new InterruptedException();
}
return executeEntry;
}
private QueueEntry dispatchOperation(JedisCluster jedis) {
String queueEntryJson;
do {
queueEntryJson = jedis.brpoplpush(
config.getQueuedOperationsListName(),
config.getDispatchingListName(),
1);
// right here is an operation loss risk
if (Thread.currentThread().isInterrupted()) {
return null;
}
} while (queueEntryJson == null);
QueueEntry.Builder queueEntryBuilder = QueueEntry.newBuilder();
try {
JsonFormat.parser().merge(queueEntryJson, queueEntryBuilder);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error parsing queue entry", e);
return null;
}
QueueEntry queueEntry = queueEntryBuilder.build();
String operationName = queueEntry.getExecuteEntry().getOperationName();
Operation operation = keepaliveOperation(operationName);
publishReset(jedis, operation);
long requeueAt = System.currentTimeMillis() + 30 * 1000;
DispatchedOperation o = DispatchedOperation.newBuilder()
.setQueueEntry(queueEntry)
.setRequeueAt(requeueAt)
.build();
boolean success = false;
try {
String dispatchedOperationJson = JsonFormat.printer().print(o);
/* if the operation is already in the dispatch list, fail the dispatch */
success = jedis.hsetnx(
config.getDispatchedOperationsHashName(),
operationName,
dispatchedOperationJson) == 1;
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing dispatched operation", e);
// very unlikely, printer would have to fail
}
if (success) {
if (jedis.lrem(config.getDispatchingListName(), -1, queueEntryJson) == 0) {
logger.warning(
format(
"operation %s was missing in %s, may be orphaned",
operationName,
config.getDispatchingListName()));
}
jedis.del(dispatchingKey(operationName)); // may or may not exist
return queueEntry;
}
return null;
}
@Override
public QueueEntry dispatchOperation() throws IOException, InterruptedException {
QueueEntry queueEntry = withBackplaneException(this::dispatchOperation);
if (Thread.interrupted()) {
throw new InterruptedException();
}
return queueEntry;
}
@Override
public boolean pollOperation(QueueEntry queueEntry, ExecutionStage.Value stage, long requeueAt) throws IOException {
String operationName = queueEntry.getExecuteEntry().getOperationName();
DispatchedOperation o = DispatchedOperation.newBuilder()
.setQueueEntry(queueEntry)
.setRequeueAt(requeueAt)
.build();
String json;
try {
json = JsonFormat.printer().print(o);
} catch (InvalidProtocolBufferException e) {
logger.log(SEVERE, "error printing dispatched operation " + operationName, e);
return false;
}
return withBackplaneException((jedis) -> {
if (jedis.hexists(config.getDispatchedOperationsHashName(), operationName)) {
if (jedis.hset(config.getDispatchedOperationsHashName(), operationName, json) == 0) {
return true;
}
/* someone else beat us to the punch, delete our incorrectly added key */
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
}
return false;
});
}
@Override
public void prequeue(ExecuteEntry executeEntry, Operation operation) throws IOException {
String operationName = operation.getName();
String operationJson = operationPrinter.print(operation);
String executeEntryJson = JsonFormat.printer().print(executeEntry);
Operation publishOperation = onPublish.apply(operation);
withVoidBackplaneException((jedis) -> {
jedis.setex(operationKey(operationName), config.getOperationExpire(), operationJson);
jedis.lpush(config.getPreQueuedOperationsListName(), executeEntryJson);
publishReset(jedis, publishOperation);
});
}
private Operation keepaliveOperation(String operationName) {
return Operation.newBuilder()
.setName(operationName)
.build();
}
@Override
public void queueing(String operationName) throws IOException {
Operation operation = keepaliveOperation(operationName);
// publish so that watchers reset their timeout
withVoidBackplaneException((jedis) -> {
publishReset(jedis, operation);
});
}
@Override
public void requeueDispatchedOperation(QueueEntry queueEntry) throws IOException {
String queueEntryJson = JsonFormat.printer().print(queueEntry);
String operationName = queueEntry.getExecuteEntry().getOperationName();
Operation publishOperation = keepaliveOperation(operationName);
withVoidBackplaneException((jedis) -> {
queue(jedis, operationName, queueEntryJson);
publishReset(jedis, publishOperation);
});
}
private void completeOperation(JedisCluster jedis, String operationName) {
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
}
@Override
public void completeOperation(String operationName) throws IOException {
withVoidBackplaneException((jedis) -> completeOperation(jedis, operationName));
}
@Override
public void deleteOperation(String operationName) throws IOException {
Operation o = Operation.newBuilder()
.setName(operationName)
.setDone(true)
.setError(com.google.rpc.Status.newBuilder()
.setCode(Code.UNAVAILABLE.value())
.build())
.build();
String json;
try {
json = JsonFormat.printer().print(o);
} catch (InvalidProtocolBufferException e) {
json = null;
logger.log(SEVERE, "error printing deleted operation " + operationName, e);
}
withVoidBackplaneException((jedis) -> {
jedis.hdel(config.getDispatchedOperationsHashName(), operationName);
// FIXME find a way to get rid of this thing from the queue by name
// jedis.lrem(config.getQueuedOperationsListName(), 0, operationName);
jedis.del(operationKey(operationName));
publishReset(jedis, o);
});
}
private JedisCluster getSubscribeJedis() throws IOException {
if (!poolStarted) {
throw new IOException(
Status.UNAVAILABLE.withDescription("backend is not started").asRuntimeException());
}
return jedisClusterFactory.get();
}
private JedisCluster getJedis() throws IOException {
if (!poolStarted) {
throw new IOException(
Status.UNAVAILABLE.withDescription("backend is not started").asRuntimeException());
}
return jedisCluster;
}
private String casKey(Digest blobDigest) {
return config.getCasPrefix() + ":" + DigestUtil.toString(blobDigest);
}
private String acKey(ActionKey actionKey) {
return config.getActionCachePrefix() + ":" + DigestUtil.toString(actionKey.getDigest());
}
private String operationKey(String operationName) {
return config.getOperationPrefix() + ":" + operationName;
}
private String operationChannel(String operationName) {
return config.getOperationChannelPrefix() + ":" + operationName;
}
private String processingKey(String operationName) {
return config.getProcessingPrefix() + ":" + operationName;
}
private String dispatchingKey(String operationName) {
return config.getDispatchingPrefix() + ":" + operationName;
}
public static String parseOperationChannel(String channel) {
return channel.split(":")[1];
}
@Override
public boolean canQueue() throws IOException {
int maxQueueDepth = config.getMaxQueueDepth();
return maxQueueDepth < 0
|| withBackplaneException((jedis) -> jedis.llen(config.getQueuedOperationsListName()) < maxQueueDepth);
}
@Override
public boolean canPrequeue() throws IOException {
int maxPreQueueDepth = config.getMaxPreQueueDepth();
return maxPreQueueDepth < 0
|| withBackplaneException((jedis) -> jedis.llen(config.getPreQueuedOperationsListName()) < maxPreQueueDepth);
}
}
|
Use getJedis for client acquisition to obey pool
Ensure that all client uses in RedisShardBackplane go through getJedis
to ensure that pool closure is properly logged and propagated.
|
src/main/java/build/buildfarm/instance/shard/RedisShardBackplane.java
|
Use getJedis for client acquisition to obey pool
|
<ide><path>rc/main/java/build/buildfarm/instance/shard/RedisShardBackplane.java
<ide> while (true) {
<ide> try {
<ide> TimeUnit.SECONDS.sleep(10);
<del> updateWatchers(jedisCluster);
<add> updateWatchers(getJedis());
<ide> } catch (InterruptedException e) {
<ide> Thread.currentThread().interrupt();
<ide> break;
<ide> public <T> T withBackplaneException(JedisContext<T> withJedis) throws IOException {
<ide> try {
<ide> try {
<del> return withJedis.run(jedisCluster);
<add> return withJedis.run(getJedis());
<ide> } catch (JedisDataException e) {
<ide> if (e.getMessage().startsWith(MISCONF_RESPONSE)) {
<ide> throw new JedisMisconfigurationException(e.getMessage());
|
|
JavaScript
|
mit
|
60644d29354d613cb71c21939609c1f2862019e3
| 0 |
ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt
|
const Exchange = require ('./base/Exchange');
const { TICK_SIZE } = require ('./base/functions/number');
const Precise = require ('./base/Precise');
const { BadSymbol, BadRequest, OnMaintenance, AccountSuspended, PermissionDenied, ExchangeError, RateLimitExceeded, ExchangeNotAvailable, OrderNotFound, InsufficientFunds, InvalidOrder, AuthenticationError, ArgumentsRequired } = require ('./base/errors');
module.exports = class hitbtc3 extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'hitbtc3',
'name': 'HitBTC',
'countries': [ 'HK' ],
// 300 requests per second => 1000ms / 300 = 3.333 (Trading: placing, replacing, deleting)
// 30 requests per second => ( 1000ms / rateLimit ) / 30 = cost = 10 (Market Data and other Public Requests)
// 20 requests per second => ( 1000ms / rateLimit ) / 20 = cost = 15 (All Other)
'rateLimit': 3.333, // TODO: optimize https://api.hitbtc.com/#rate-limiting
'version': '3',
'pro': true,
'has': {
'CORS': false,
'spot': true,
'margin': undefined, // has but not fully implemented
'swap': true,
'future': false,
'option': undefined,
'addMargin': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'createReduceOnlyOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchFundingHistory': false,
'fetchFundingRate': true,
'fetchFundingRateHistory': true,
'fetchFundingRates': false,
'fetchIndexOHLCV': undefined,
'fetchLeverageTiers': undefined,
'fetchMarketLeverageTiers': undefined,
'fetchMarkets': true,
'fetchMarkOHLCV': undefined,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrder': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrderBooks': true,
'fetchOrders': false,
'fetchOrderTrades': true,
'fetchPosition': false,
'fetchPositions': true,
'fetchPremiumIndexOHLCV': undefined,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchTradingFee': true,
'fetchTradingFees': true,
'fetchTransactions': true,
'fetchWithdrawals': true,
'reduceMargin': undefined,
'setLeverage': undefined,
'setMarginMode': false,
'setPositionMode': false,
'transfer': true,
'withdraw': true,
},
'precisionMode': TICK_SIZE,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'test': {
'public': 'https://api.demo.hitbtc.com',
'private': 'https://api.demo.hitbtc.com',
},
'api': {
'public': 'https://api.hitbtc.com/api/3',
'private': 'https://api.hitbtc.com/api/3',
},
'www': 'https://hitbtc.com',
'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
'doc': [
'https://api.hitbtc.com',
'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
],
'fees': [
'https://hitbtc.com/fees-and-limits',
'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
],
},
'api': {
'public': {
'get': {
'public/currency': 10,
'public/symbol': 10,
'public/ticker': 10,
'public/price/rate': 10,
'public/trades': 10,
'public/orderbook': 10,
'public/candles': 10,
'public/futures/info': 10,
'public/futures/history/funding': 10,
'public/futures/candles/index_price': 10,
'public/futures/candles/mark_price': 10,
'public/futures/candles/premium_index': 10,
'public/futures/candles/open_interest': 10,
},
},
'private': {
'get': {
'spot/balance': 15,
'spot/order': 15,
'spot/order/{client_order_id}': 15,
'spot/fee': 15,
'spot/fee/{symbol}': 15,
'spot/history/order': 15,
'spot/history/trade': 15,
'margin/account': 15,
'margin/account/isolated/{symbol}': 15,
'margin/order': 15,
'margin/order/{client_order_id}': 15,
'margin/history/order': 15,
'margin/history/trade': 15,
'futures/balance': 15,
'futures/account': 15,
'futures/account/isolated/{symbol}': 15,
'futures/order': 15,
'futures/order/{client_order_id}': 15,
'futures/fee': 15,
'futures/fee/{symbol}': 15,
'futures/history/order': 15,
'futures/history/trade': 15,
'wallet/balance': 15,
'wallet/crypto/address': 15,
'wallet/crypto/address/recent-deposit': 15,
'wallet/crypto/address/recent-withdraw': 15,
'wallet/crypto/address/check-mine': 15,
'wallet/transactions': 15,
'wallet/crypto/check-offchain-available': 15,
'wallet/crypto/fee/estimate': 15,
'sub-account': 15,
'sub-account/acl': 15,
'sub-account/balance/{subAccID}': 15,
'sub-account/crypto/address/{subAccID}/{currency}': 15,
},
'post': {
'spot/order': 1,
'margin/order': 1,
'futures/order': 1,
'wallet/convert': 15,
'wallet/crypto/withdraw': 15,
'wallet/transfer': 15,
'sub-account/freeze': 15,
'sub-account/activate': 15,
'sub-account/transfer': 15,
'sub-account/acl': 15,
},
'patch': {
'spot/order/{client_order_id}': 1,
'margin/order/{client_order_id}': 1,
'futures/order/{client_order_id}': 1,
},
'delete': {
'spot/order': 1,
'spot/order/{client_order_id}': 1,
'margin/position': 1,
'margin/position/isolated/{symbol}': 1,
'margin/order': 1,
'margin/order/{client_order_id}': 1,
'futures/position': 1,
'futures/position/isolated/{symbol}': 1,
'futures/order': 1,
'futures/order/{client_order_id}': 1,
'wallet/crypto/withdraw/{id}': 1,
},
'put': {
'margin/account/isolated/{symbol}': 1,
'futures/account/isolated/{symbol}': 1,
'wallet/crypto/withdraw/{id}': 1,
},
},
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0009'),
'maker': this.parseNumber ('0.0009'),
'tiers': {
'maker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0002') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0001') ],
[ this.parseNumber ('20000'), this.parseNumber ('0') ],
[ this.parseNumber ('50000'), this.parseNumber ('-0.0001') ],
[ this.parseNumber ('100000'), this.parseNumber ('-0.0001') ],
],
'taker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('20000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('50000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('100000'), this.parseNumber ('0.0002') ],
],
},
},
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30', // default
'1h': 'H1',
'4h': 'H4',
'1d': 'D1',
'1w': 'D7',
'1M': '1M',
},
'exceptions': {
'exact': {
'429': RateLimitExceeded,
'500': ExchangeError,
'503': ExchangeNotAvailable,
'504': ExchangeNotAvailable,
'600': PermissionDenied,
'800': ExchangeError,
'1002': AuthenticationError,
'1003': PermissionDenied,
'1004': AuthenticationError,
'1005': AuthenticationError,
'2001': BadSymbol,
'2002': BadRequest,
'2003': BadRequest,
'2010': BadRequest,
'2011': BadRequest,
'2012': BadRequest,
'2020': BadRequest,
'2022': BadRequest,
'10001': BadRequest,
'10021': AccountSuspended,
'10022': BadRequest,
'20001': InsufficientFunds,
'20002': OrderNotFound,
'20003': ExchangeError,
'20004': ExchangeError,
'20005': ExchangeError,
'20006': ExchangeError,
'20007': ExchangeError,
'20008': InvalidOrder,
'20009': InvalidOrder,
'20010': OnMaintenance,
'20011': ExchangeError,
'20012': ExchangeError,
'20014': ExchangeError,
'20016': ExchangeError,
'20031': ExchangeError,
'20032': ExchangeError,
'20033': ExchangeError,
'20034': ExchangeError,
'20040': ExchangeError,
'20041': ExchangeError,
'20042': ExchangeError,
'20043': ExchangeError,
'20044': PermissionDenied,
'20045': InvalidOrder,
'20080': ExchangeError,
'21001': ExchangeError,
'21003': AccountSuspended,
'21004': AccountSuspended,
},
'broad': {},
},
'options': {
'networks': {
'ETH': 'USDT20',
'ERC20': 'USDT20',
'TRX': 'USDTRX',
'TRC20': 'USDTRX',
'OMNI': 'USDT',
},
'accountsByType': {
'spot': 'spot',
'funding': 'wallet',
'wallet': 'wallet',
'future': 'derivatives',
'derivatives': 'derivatives',
},
},
});
}
nonce () {
return this.milliseconds ();
}
async fetchMarkets (params = {}) {
const response = await this.publicGetPublicSymbol (params);
//
// {
// "AAVEUSDT_PERP":{
// "type":"futures",
// "expiry":null,
// "underlying":"AAVE",
// "base_currency":null,
// "quote_currency":"USDT",
// "quantity_increment":"0.01",
// "tick_size":"0.001",
// "take_rate":"0.0005",
// "make_rate":"0.0002",
// "fee_currency":"USDT",
// "margin_trading":true,
// "max_initial_leverage":"50.00"
// },
// "MANAUSDT":{
// "type":"spot",
// "base_currency":"MANA",
// "quote_currency":"USDT",
// "quantity_increment":"1",
// "tick_size":"0.0000001",
// "take_rate":"0.0025",
// "make_rate":"0.001",
// "fee_currency":"USDT",
// "margin_trading":true,
// "max_initial_leverage":"5.00"
// },
// }
//
const result = [];
const ids = Object.keys (response);
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const market = this.safeValue (response, id);
const marketType = this.safeString (market, 'type');
const expiry = this.safeInteger (market, 'expiry');
const contract = (marketType === 'futures');
const spot = (marketType === 'spot');
const marginTrading = this.safeValue (market, 'margin_trading', false);
const margin = spot && marginTrading;
const future = (expiry !== undefined);
const swap = (contract && !future);
const option = false;
const baseId = this.safeString2 (market, 'base_currency', 'underlying');
const quoteId = this.safeString (market, 'quote_currency');
const feeCurrencyId = this.safeString (market, 'fee_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const feeCurrency = this.safeCurrencyCode (feeCurrencyId);
let settleId = undefined;
let settle = undefined;
let symbol = base + '/' + quote;
let type = 'spot';
let contractSize = undefined;
let linear = undefined;
let inverse = undefined;
if (contract) {
contractSize = this.parseNumber ('1');
settleId = feeCurrencyId;
settle = this.safeCurrencyCode (settleId);
linear = ((quote !== undefined) && (quote === settle));
inverse = !linear;
symbol = symbol + ':' + settle;
if (future) {
symbol = symbol + '-' + expiry;
type = 'future';
} else {
type = 'swap';
}
}
const lotString = this.safeString (market, 'quantity_increment');
const stepString = this.safeString (market, 'tick_size');
const lot = this.parseNumber (lotString);
const step = this.parseNumber (stepString);
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': spot,
'margin': margin,
'swap': swap,
'future': future,
'option': option,
'active': true,
'contract': contract,
'linear': linear,
'inverse': inverse,
'taker': this.safeNumber (market, 'take_rate'),
'maker': this.safeNumber (market, 'make_rate'),
'contractSize': contractSize,
'expiry': expiry,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'feeCurrency': feeCurrency,
'precision': {
'amount': lot,
'price': step,
},
'limits': {
'leverage': {
'min': this.parseNumber ('1'),
'max': this.safeNumber (market, 'max_initial_leverage', 1),
},
'amount': {
'min': lot,
'max': undefined,
},
'price': {
'min': step,
'max': undefined,
},
'cost': {
'min': this.parseNumber (Precise.stringMul (lotString, stepString)),
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.publicGetPublicCurrency (params);
//
// {
// "WEALTH": {
// "full_name": "ConnectWealth",
// "payin_enabled": false,
// "payout_enabled": false,
// "transfer_enabled": true,
// "precision_transfer": "0.001",
// "networks": [
// {
// "network": "ETH",
// "protocol": "ERC20",
// "default": true,
// "payin_enabled": false,
// "payout_enabled": false,
// "precision_payout": "0.001",
// "payout_fee": "0.016800000000",
// "payout_is_payment_id": false,
// "payin_payment_id": false,
// "payin_confirmations": "2"
// }
// ]
// }
// }
//
const result = {};
const currencies = Object.keys (response);
for (let i = 0; i < currencies.length; i++) {
const currencyId = currencies[i];
const code = this.safeCurrencyCode (currencyId);
const entry = response[currencyId];
const name = this.safeString (entry, 'full_name');
const precision = this.safeNumber (entry, 'precision_transfer');
const payinEnabled = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabled = this.safeValue (entry, 'payout_enabled', false);
const transferEnabled = this.safeValue (entry, 'transfer_enabled', false);
const active = payinEnabled && payoutEnabled && transferEnabled;
const rawNetworks = this.safeValue (entry, 'networks', []);
const networks = {};
let fee = undefined;
let depositEnabled = undefined;
let withdrawEnabled = undefined;
for (let j = 0; j < rawNetworks.length; j++) {
const rawNetwork = rawNetworks[j];
let networkId = this.safeString (rawNetwork, 'protocol');
if (networkId.length === 0) {
networkId = this.safeString (rawNetwork, 'network');
}
const network = this.safeNetwork (networkId);
fee = this.safeNumber (rawNetwork, 'payout_fee');
const precision = this.safeNumber (rawNetwork, 'precision_payout');
const payinEnabledNetwork = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabledNetwork = this.safeValue (entry, 'payout_enabled', false);
const activeNetwork = payinEnabledNetwork && payoutEnabledNetwork;
if (payinEnabledNetwork && !depositEnabled) {
depositEnabled = true;
} else if (!payinEnabledNetwork) {
depositEnabled = false;
}
if (payoutEnabledNetwork && !withdrawEnabled) {
withdrawEnabled = true;
} else if (!payoutEnabledNetwork) {
withdrawEnabled = false;
}
networks[network] = {
'info': rawNetwork,
'id': networkId,
'network': network,
'fee': fee,
'active': activeNetwork,
'deposit': payinEnabledNetwork,
'withdraw': payoutEnabledNetwork,
'precision': precision,
'limits': {
'withdraw': {
'min': undefined,
'max': undefined,
},
},
};
}
const networksKeys = Object.keys (networks);
const networksLength = networksKeys.length;
result[code] = {
'info': entry,
'code': code,
'id': currencyId,
'precision': precision,
'name': name,
'active': active,
'deposit': depositEnabled,
'withdraw': withdrawEnabled,
'networks': networks,
'fee': (networksLength <= 1) ? fee : undefined,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
},
};
}
return result;
}
safeNetwork (networkId) {
if (networkId === undefined) {
return undefined;
} else {
return networkId.toUpperCase ();
}
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const network = this.safeStringUpper (params, 'network');
if ((network !== undefined) && (code === 'USDT')) {
const networks = this.safeValue (this.options, 'networks');
const parsedNetwork = this.safeString (networks, network);
if (parsedNetwork !== undefined) {
request['currency'] = parsedNetwork;
}
params = this.omit (params, 'network');
}
const response = await this.privateGetWalletCryptoAddress (this.extend (request, params));
//
// [{"currency":"ETH","address":"0xd0d9aea60c41988c3e68417e2616065617b7afd3"}]
//
const firstAddress = this.safeValue (response, 0);
const address = this.safeString (firstAddress, 'address');
const currencyId = this.safeString (firstAddress, 'currency');
const tag = this.safeString (firstAddress, 'payment_id');
const parsedCode = this.safeCurrencyCode (currencyId);
return {
'info': response,
'address': address,
'tag': tag,
'code': parsedCode,
'network': undefined,
};
}
parseBalance (response) {
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const currencyId = this.safeString (entry, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (entry, 'available');
account['used'] = this.safeString (entry, 'reserved');
result[code] = account;
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
const type = this.safeStringLower (params, 'type', 'spot');
params = this.omit (params, [ 'type' ]);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
const account = this.safeString (accountsByType, type);
let response = undefined;
if (account === 'wallet') {
response = await this.privateGetWalletBalance (params);
} else if (account === 'spot') {
response = await this.privateGetSpotBalance (params);
} else if (account === 'derivatives') {
response = await this.privateGetFuturesBalance (params);
} else {
const keys = Object.keys (accountsByType);
throw new BadRequest (this.id + ' fetchBalance() type parameter must be one of ' + keys.join (', '));
}
//
// [
// {
// "currency": "PAXG",
// "available": "0",
// "reserved": "0",
// "reserved_margin": "0",
// },
// ...
// ]
//
return this.parseBalance (response);
}
async fetchTicker (symbol, params = {}) {
const response = await this.fetchTickers ([ symbol ], params);
return this.safeValue (response, symbol);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
const delimited = marketIds.join (',');
request['symbols'] = delimited;
}
const response = await this.publicGetPublicTicker (this.extend (request, params));
//
// {
// "BTCUSDT": {
// "ask": "63049.06",
// "bid": "63046.41",
// "last": "63048.36",
// "low": "62010.00",
// "high": "66657.99",
// "open": "64839.75",
// "volume": "15272.13278",
// "volume_quote": "976312127.6277998",
// "timestamp": "2021-10-22T04:25:47.573Z"
// }
// }
//
const result = {};
const keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
const marketId = keys[i];
const market = this.safeMarket (marketId);
const symbol = market['symbol'];
const entry = response[marketId];
result[symbol] = this.parseTicker (entry, market);
}
return this.filterByArray (result, 'symbol', symbols);
}
parseTicker (ticker, market = undefined) {
//
// {
// "ask": "62756.01",
// "bid": "62754.09",
// "last": "62755.87",
// "low": "62010.00",
// "high": "66657.99",
// "open": "65089.27",
// "volume": "16719.50366",
// "volume_quote": "1063422878.8156828",
// "timestamp": "2021-10-22T07:29:14.585Z"
// }
//
const timestamp = this.parse8601 (ticker['timestamp']);
const symbol = this.safeSymbol (undefined, market);
const baseVolume = this.safeString (ticker, 'volume');
const quoteVolume = this.safeString (ticker, 'volume_quote');
const open = this.safeString (ticker, 'open');
const last = this.safeString (ticker, 'last');
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, 'high'),
'low': this.safeString (ticker, 'low'),
'bid': this.safeString (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeString (ticker, 'ask'),
'askVolume': undefined,
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, false);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
// symbol is optional for hitbtc fetchTrades
request['symbols'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['from'] = since;
}
const response = await this.publicGetPublicTrades (this.extend (request, params));
const marketIds = Object.keys (response);
let trades = [];
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const market = this.market (marketId);
const rawTrades = response[marketId];
const parsed = this.parseTrades (rawTrades, market);
trades = this.arrayConcat (trades, parsed);
}
return trades;
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['from'] = since;
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchMyTrades', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryTrade',
'swap': 'privateGetFuturesHistoryTrade',
'margin': 'privateGetMarginHistoryTrade',
});
const response = await this[method] (this.extend (request, query));
return this.parseTrades (response, market, since, limit);
}
parseTrade (trade, market = undefined) {
//
// createOrder (market)
//
// {
// id: '1569252895',
// position_id: '0',
// quantity: '10',
// price: '0.03919424',
// fee: '0.000979856000',
// timestamp: '2022-01-25T19:38:36.153Z',
// taker: true
// }
//
// fetchTrades
//
// {
// id: 974786185,
// price: '0.032462',
// qty: '0.3673',
// side: 'buy',
// timestamp: '2020-10-16T12:57:39.846Z'
// }
//
// fetchMyTrades spot
//
// {
// id: 277210397,
// clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
// orderId: 28102855393,
// symbol: 'ETHBTC',
// side: 'sell',
// quantity: '0.002',
// price: '0.073365',
// fee: '0.000000147',
// timestamp: '2018-04-28T18:39:55.345Z',
// taker: true
// }
//
// fetchMyTrades swap and margin
//
// {
// "id": 4718564,
// "order_id": 58730811958,
// "client_order_id": "475c47d97f867f09726186eb22b4c3d4",
// "symbol": "BTCUSDT_PERP",
// "side": "sell",
// "quantity": "0.0001",
// "price": "41118.51",
// "fee": "0.002055925500",
// "timestamp": "2022-03-17T05:23:17.795Z",
// "taker": true,
// "position_id": 2350122,
// "pnl": "0.002255000000",
// "liquidation": false
// }
//
const timestamp = this.parse8601 (trade['timestamp']);
const marketId = this.safeString (trade, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let fee = undefined;
const feeCostString = this.safeString (trade, 'fee');
const taker = this.safeValue (trade, 'taker');
let takerOrMaker = undefined;
if (taker !== undefined) {
takerOrMaker = taker ? 'taker' : 'maker';
}
if (feeCostString !== undefined) {
const info = this.safeValue (market, 'info', {});
const feeCurrency = this.safeString (info, 'fee_currency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrency);
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
};
}
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const orderId = this.safeString (trade, 'clientOrderId');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString2 (trade, 'quantity', 'qty');
const side = this.safeString (trade, 'side');
const id = this.safeString (trade, 'id');
return this.safeTrade ({
'info': trade,
'id': id,
'order': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': undefined,
'fee': fee,
}, market);
}
async fetchTransactionsHelper (types, code, since, limit, params) {
await this.loadMarkets ();
const request = {
'types': types,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currencies'] = currency['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetWalletTransactions (this.extend (request, params));
//
// [
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
// ]
//
return this.parseTransactions (response, currency, since, limit, params);
}
parseTransactionStatus (status) {
const statuses = {
'PENDING': 'pending',
'FAILED': 'failed',
'SUCCESS': 'ok',
};
return this.safeString (statuses, status, status);
}
parseTransactionType (type) {
const types = {
'DEPOSIT': 'deposit',
'WITHDRAW': 'withdrawal',
};
return this.safeString (types, type, type);
}
parseTransaction (transaction, currency = undefined) {
//
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
//
// {
// "id": "102703545",
// "created_at": "2018-03-30T21:39:17.854Z",
// "updated_at": "2018-03-31T00:23:19.067Z",
// "status": "SUCCESS",
// "type": "WITHDRAW",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "5ecd7a85-ce5d-4d52-a916-b8b755e20926",
// "index": "918286359",
// "currency": "OMG",
// "amount": "2.45",
// "fee": "1.22",
// "hash": "0x1c621d89e7a0841342d5fb3b3587f60b95351590161e078c4a1daee353da4ca9",
// "address": "0x50227da7644cea0a43258a2e2d7444d01b43dcca",
// "confirmations": "0"
// }
// }
//
const id = this.safeString (transaction, 'id');
const timestamp = this.parse8601 (this.safeString (transaction, 'created_at'));
const updated = this.parse8601 (this.safeString (transaction, 'updated_at'));
const type = this.parseTransactionType (this.safeString (transaction, 'type'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const native = this.safeValue (transaction, 'native');
const currencyId = this.safeString (native, 'currency');
const code = this.safeCurrencyCode (currencyId);
const txhash = this.safeString (native, 'hash');
const address = this.safeString (native, 'address');
const addressTo = address;
const tag = this.safeString (native, 'payment_id');
const tagTo = tag;
const sender = this.safeValue (native, 'senders');
const addressFrom = this.safeString (sender, 0);
const amount = this.safeNumber (native, 'amount');
let fee = undefined;
const feeCost = this.safeNumber (native, 'fee');
if (feeCost !== undefined) {
fee = {
'code': code,
'cost': feeCost,
};
}
return {
'info': transaction,
'id': id,
'txid': txhash,
'code': code,
'amount': amount,
'network': undefined,
'address': address,
'addressFrom': addressFrom,
'addressTo': addressTo,
'tag': tag,
'tagFrom': undefined,
'tagTo': tagTo,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'updated': updated,
'status': status,
'type': type,
'fee': fee,
};
}
async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT,WITHDRAW', code, since, limit, params);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('WITHDRAW', code, since, limit, params);
}
async fetchOrderBooks (symbols = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
request['symbols'] = marketIds.join (',');
}
if (limit !== undefined) {
request['depth'] = limit;
}
const response = await this.publicGetPublicOrderbook (this.extend (request, params));
const result = {};
const marketIds = Object.keys (response);
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const orderbook = response[marketId];
const symbol = this.safeSymbol (marketId);
const timestamp = this.parse8601 (this.safeString (orderbook, 'timestamp'));
result[symbol] = this.parseOrderBook (response[marketId], symbol, timestamp, 'bid', 'ask');
}
return result;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
const result = await this.fetchOrderBooks ([ symbol ], limit, params);
return result[symbol];
}
parseTradingFee (fee, market = undefined) {
//
// {
// "symbol":"ARVUSDT", // returned from fetchTradingFees only
// "take_rate":"0.0009",
// "make_rate":"0.0009"
// }
//
const taker = this.safeNumber (fee, 'take_rate');
const maker = this.safeNumber (fee, 'make_rate');
const marketId = this.safeString (fee, 'symbol');
const symbol = this.safeSymbol (marketId, market);
return {
'info': fee,
'symbol': symbol,
'taker': taker,
'maker': maker,
};
}
async fetchTradingFee (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const method = this.getSupportedMapping (market['type'], {
'spot': 'privateGetSpotFeeSymbol',
'swap': 'privateGetFuturesFeeSymbol',
});
const response = await this[method] (this.extend (request, params));
//
// {
// "take_rate":"0.0009",
// "make_rate":"0.0009"
// }
//
return this.parseTradingFee (response, market);
}
async fetchTradingFees (symbols = undefined, params = {}) {
await this.loadMarkets ();
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchTradingFees', undefined, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotFee',
'swap': 'privateGetFuturesFee',
});
const response = await this[method] (query);
//
// [
// {
// "symbol":"ARVUSDT",
// "take_rate":"0.0009",
// "make_rate":"0.0009"
// }
// ]
//
const result = {};
for (let i = 0; i < response.length; i++) {
const fee = this.parseTradingFee (response[i]);
const symbol = fee['symbol'];
result[symbol] = fee;
}
return result;
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbols': market['id'],
'period': this.timeframes[timeframe],
};
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicCandles (this.extend (request, params));
//
// {
// "ETHUSDT": [
// {
// "timestamp": "2021-10-25T07:38:00.000Z",
// "open": "4173.391",
// "close": "4170.923",
// "min": "4170.923",
// "max": "4173.986",
// "volume": "0.1879",
// "volume_quote": "784.2517846"
// }
// ]
// }
//
const ohlcvs = this.safeValue (response, market['id']);
return this.parseOHLCVs (ohlcvs, market, timeframe, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// "timestamp":"2015-08-20T19:01:00.000Z",
// "open":"0.006",
// "close":"0.006",
// "min":"0.006",
// "max":"0.006",
// "volume":"0.003",
// "volume_quote":"0.000018"
// }
//
return [
this.parse8601 (this.safeString (ohlcv, 'timestamp')),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'max'),
this.safeNumber (ohlcv, 'min'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'volume'),
];
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchClosedOrders', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryOrder',
'swap': 'privateGetFuturesHistoryOrder',
});
const response = await this[method] (this.extend (request, query));
const parsed = this.parseOrders (response, market, since, limit);
return this.filterByArray (parsed, 'status', [ 'closed', 'canceled' ], false);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOrder', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryOrder',
'swap': 'privateGetFuturesHistoryOrder',
});
const request = {
'client_order_id': id,
};
const response = await this[method] (this.extend (request, query));
//
// [
// {
// "id": "685965182082",
// "client_order_id": "B3CBm9uGg9oYQlw96bBSEt38-6gbgBO0",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0",
// "price": "50000.00",
// "price_average": "0",
// "created_at": "2021-10-26T11:40:09.287Z",
// "updated_at": "2021-10-26T11:40:09.287Z"
// }
// ]
//
const order = this.safeValue (response, 0);
return this.parseOrder (order, market);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'order_id': id, // exchange assigned order id as oppose to the client order id
};
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOrderTrades', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryTrade',
'swap': 'privateGetFuturesHistoryTrade',
});
const response = await this[method] (this.extend (request, query));
//
// Spot
//
// [
// {
// "id": 1393448977,
// "order_id": 653496804534,
// "client_order_id": "065f6f0ff9d54547848454182263d7b4",
// "symbol": "DICEETH",
// "side": "buy",
// "quantity": "1.4",
// "price": "0.00261455",
// "fee": "0.000003294333",
// "timestamp": "2021-09-19T05:35:56.601Z",
// "taker": true
// }
// ]
//
// Swap
//
// [
// {
// "id": 4718551,
// "order_id": 58730748700,
// "client_order_id": "dcbcd8549e3445ee922665946002ef67",
// "symbol": "BTCUSDT_PERP",
// "side": "buy",
// "quantity": "0.0001",
// "price": "41095.96",
// "fee": "0.002054798000",
// "timestamp": "2022-03-17T05:23:02.217Z",
// "taker": true,
// "position_id": 2350122,
// "pnl": "0",
// "liquidation": false
// }
// ]
//
return this.parseTrades (response, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOpenOrders', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotOrder',
'swap': 'privateGetFuturesOrder',
});
const response = await this[method] (this.extend (request, query));
//
// [
// {
// "id": "488953123149",
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
// ]
//
return this.parseOrders (response, market, since, limit);
}
async fetchOpenOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOpenOrder', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotOrderClientOrderId',
'swap': 'privateGetFuturesOrderClientOrderId',
});
const request = {
'client_order_id': id,
};
const response = await this[method] (this.extend (request, query));
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('cancelAllOrders', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateDeleteSpotOrder',
'swap': 'privateDeleteFuturesOrder',
});
const response = await this[method] (this.extend (request, query));
return this.parseOrders (response, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
};
if (symbol !== undefined) {
market = this.market (symbol);
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('cancelOrder', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateDeleteSpotOrderClientOrderId',
'swap': 'privateDeleteFuturesOrderClientOrderId',
});
const response = await this[method] (this.extend (request, query));
return this.parseOrder (response, market);
}
async editOrder (id, symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
'quantity': this.amountToPrecision (symbol, amount),
};
if ((type === 'limit') || (type === 'stopLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' limit order requires price');
}
request['price'] = this.priceToPrecision (symbol, price);
}
if (symbol !== undefined) {
market = this.market (symbol);
}
const method = this.getSupportedMapping (market['type'], {
'spot': 'privatePatchSpotOrderClientOrderId',
'swap': 'privatePatchFuturesOrderClientOrderId',
});
const response = await this[method] (this.extend (request, params));
return this.parseOrder (response, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const reduceOnly = this.safeValue2 (params, 'reduce_only', 'reduceOnly');
if (reduceOnly !== undefined) {
if ((market['type'] !== 'swap') && (market['type'] !== 'margin')) {
throw new InvalidOrder (this.id + ' createOrder() does not support reduce_only for ' + market['type'] + ' orders, reduce_only orders are supported for swap and margin markets only');
}
}
const request = {
'type': type,
'side': side,
'quantity': this.amountToPrecision (symbol, amount),
'symbol': market['id'],
// 'client_order_id': 'r42gdPjNMZN-H_xs8RKl2wljg_dfgdg4', // Optional
// 'time_in_force': 'GTC', // Optional GTC, IOC, FOK, Day, GTD
// 'price': this.priceToPrecision (symbol, price), // Required if type is limit, stopLimit, or takeProfitLimit
// 'stop_price': this.safeNumber (params, 'stop_price'), // Required if type is stopLimit, stopMarket, takeProfitLimit, takeProfitMarket
// 'expire_time': '2021-06-15T17:01:05.092Z', // Required if timeInForce is GTD
// 'strict_validate': false,
// 'post_only': false, // Optional
// 'reduce_only': false, // Optional
// 'display_quantity': '0', // Optional
// 'take_rate': 0.001, // Optional
// 'make_rate': 0.001, // Optional
};
const timeInForce = this.safeString2 (params, 'timeInForce', 'time_in_force');
const expireTime = this.safeString (params, 'expire_time');
const stopPrice = this.safeNumber2 (params, 'stopPrice', 'stop_price');
if ((type === 'limit') || (type === 'stopLimit') || (type === 'takeProfitLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' createOrder() requires a price argument for limit orders');
}
request['price'] = this.priceToPrecision (symbol, price);
}
if ((timeInForce === 'GTD')) {
if (expireTime === undefined) {
throw new ExchangeError (this.id + ' createOrder() requires an expire_time parameter for a GTD order');
}
request['expire_time'] = expireTime;
}
if ((type === 'stopLimit') || (type === 'stopMarket') || (type === 'takeProfitLimit') || (type === 'takeProfitMarket')) {
if (stopPrice === undefined) {
throw new ExchangeError (this.id + ' createOrder() requires a stopPrice parameter for stop-loss and take-profit orders');
}
request['stop_price'] = this.priceToPrecision (symbol, stopPrice);
}
const method = this.getSupportedMapping (market['type'], {
'spot': 'privatePostSpotOrder',
'swap': 'privatePostFuturesOrder',
});
const response = await this[method] (this.extend (request, params));
return this.parseOrder (response, market);
}
async createReduceOnlyOrder (symbol, type, side, amount, price = undefined, params = {}) {
const request = {
'reduce_only': true,
};
return await this.createOrder (symbol, type, side, amount, price, this.extend (request, params));
}
parseOrderStatus (status) {
const statuses = {
'new': 'open',
'suspended': 'open',
'partiallyFilled': 'open',
'filled': 'closed',
'canceled': 'canceled',
'expired': 'failed',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// limit
// {
// "id": 488953123149,
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "price_average": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
//
// market
// {
// "id": "685877626834",
// "client_order_id": "Yshl7G-EjaREyXQYaGbsmdtVbW-nzQwu",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "filled",
// "type": "market",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0.00010",
// "post_only": false,
// "created_at": "2021-10-26T08:55:55.1Z",
// "updated_at": "2021-10-26T08:55:55.1Z",
// "trades": [
// {
// "id": "1437229630",
// "position_id": "0",
// "quantity": "0.00010",
// "price": "62884.78",
// "fee": "0.005659630200",
// "timestamp": "2021-10-26T08:55:55.1Z",
// "taker": true
// }
// ]
// }
//
// swap
//
// {
// "id": 58418961892,
// "client_order_id": "r42gdPjNMZN-H_xs8RKl2wljg_dfgdg4",
// "symbol": "BTCUSDT_PERP",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.0005",
// "quantity_cumulative": "0",
// "price": "30000.00",
// "post_only": false,
// "reduce_only": false,
// "created_at": "2022-03-16T08:16:53.039Z",
// "updated_at": "2022-03-16T08:16:53.039Z"
// }
//
const id = this.safeString (order, 'client_order_id');
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const side = this.safeString (order, 'side');
const type = this.safeString (order, 'type');
const amount = this.safeString (order, 'quantity');
const price = this.safeString (order, 'price');
const average = this.safeString (order, 'price_average');
const created = this.safeString (order, 'created_at');
const timestamp = this.parse8601 (created);
const updated = this.safeString (order, 'updated_at');
let lastTradeTimestamp = undefined;
if (updated !== created) {
lastTradeTimestamp = this.parse8601 (updated);
}
const filled = this.safeString (order, 'quantity_cumulative');
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const marketId = this.safeString (order, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
const postOnly = this.safeValue (order, 'post_only');
const timeInForce = this.safeString (order, 'time_in_force');
const rawTrades = this.safeValue (order, 'trades');
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'price': price,
'amount': amount,
'type': type,
'side': side,
'timeInForce': timeInForce,
'postOnly': postOnly,
'filled': filled,
'remaining': undefined,
'cost': undefined,
'status': status,
'average': average,
'trades': rawTrades,
'fee': undefined,
}, market);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
// account can be "spot", "wallet", or "derivatives"
await this.loadMarkets ();
const currency = this.currency (code);
const requestAmount = this.currencyToPrecision (code, amount);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
fromAccount = fromAccount.toLowerCase ();
toAccount = toAccount.toLowerCase ();
const fromId = this.safeString (accountsByType, fromAccount);
const toId = this.safeString (accountsByType, toAccount);
const keys = Object.keys (accountsByType);
if (fromId === undefined) {
throw new ArgumentsRequired (this.id + ' transfer() fromAccount argument must be one of ' + keys.join (', '));
}
if (toId === undefined) {
throw new ArgumentsRequired (this.id + ' transfer() toAccount argument must be one of ' + keys.join (', '));
}
if (fromId === toId) {
throw new BadRequest (this.id + ' transfer() fromAccount and toAccount arguments cannot be the same account');
}
const request = {
'currency': currency['id'],
'amount': requestAmount,
'source': fromId,
'destination': toId,
};
const response = await this.privatePostWalletTransfer (this.extend (request, params));
// [ '2db6ebab-fb26-4537-9ef8-1a689472d236' ]
const id = this.safeString (response, 0);
return {
'info': response,
'id': id,
'timestamp': undefined,
'datetime': undefined,
'amount': this.parseNumber (requestAmount),
'currency': code,
'fromAccount': fromAccount,
'toAccount': toAccount,
'status': undefined,
};
}
async convertCurrencyNetwork (code, amount, fromNetwork, toNetwork, params) {
await this.loadMarkets ();
if (code !== 'USDT') {
throw new ExchangeError (this.id + ' convertCurrencyNetwork() only supports USDT currently');
}
const networks = this.safeValue (this.options, 'networks', {});
fromNetwork = fromNetwork.toUpperCase ();
toNetwork = toNetwork.toUpperCase ();
fromNetwork = this.safeString (networks, fromNetwork); // handle ETH>ERC20 alias
toNetwork = this.safeString (networks, toNetwork); // handle ETH>ERC20 alias
if (fromNetwork === toNetwork) {
throw new BadRequest (this.id + ' fromNetwork cannot be the same as toNetwork');
}
if ((fromNetwork === undefined) || (toNetwork === undefined)) {
const keys = Object.keys (networks);
throw new ArgumentsRequired (this.id + ' convertCurrencyNetwork() requires a fromNetwork parameter and a toNetwork parameter, supported networks are ' + keys.join (', '));
}
const request = {
'from_currency': fromNetwork,
'to_currency': toNetwork,
'amount': this.currencyToPrecision (code, amount),
};
const response = await this.privatePostWalletConvert (this.extend (request, params));
// {"result":["587a1868-e62d-4d8e-b27c-dbdb2ee96149","e168df74-c041-41f2-b76c-e43e4fed5bc7"]}
return {
'info': response,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
await this.loadMarkets ();
this.checkAddress (address);
const currency = this.currency (code);
const request = {
'currency': currency['id'],
'amount': amount,
'address': address,
};
if (tag !== undefined) {
request['payment_id'] = tag;
}
const networks = this.safeValue (this.options, 'networks', {});
const network = this.safeStringUpper (params, 'network');
if ((network !== undefined) && (code === 'USDT')) {
const parsedNetwork = this.safeString (networks, network);
if (parsedNetwork !== undefined) {
request['currency'] = parsedNetwork;
}
params = this.omit (params, 'network');
}
const response = await this.privatePostWalletCryptoWithdraw (this.extend (request, params));
// {"id":"084cfcd5-06b9-4826-882e-fdb75ec3625d"}
const id = this.safeString (response, 'id');
return {
'info': response,
'id': id,
};
}
async fetchFundingRateHistory (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
// all arguments are optional
// 'symbols': Comma separated list of symbol codes,
// 'sort': 'DESC' or 'ASC'
// 'from': 'Datetime or Number',
// 'till': 'Datetime or Number',
// 'limit': 100,
// 'offset': 0,
};
if (symbol !== undefined) {
market = this.market (symbol);
symbol = market['symbol'];
request['symbols'] = market['id'];
}
if (since !== undefined) {
request['from'] = since;
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicFuturesHistoryFunding (this.extend (request, params));
//
// {
// "BTCUSDT_PERP": [
// {
// "timestamp": "2021-07-29T16:00:00.271Z",
// "funding_rate": "0.0001",
// "avg_premium_index": "0.000061858585213222",
// "next_funding_time": "2021-07-30T00:00:00.000Z",
// "interest_rate": "0.0001"
// },
// ...
// ],
// ...
// }
//
const contracts = Object.keys (response);
const rates = [];
for (let i = 0; i < contracts.length; i++) {
const marketId = contracts[i];
const market = this.safeMarket (marketId);
const fundingRateData = response[marketId];
for (let i = 0; i < fundingRateData.length; i++) {
const entry = fundingRateData[i];
const symbol = this.safeSymbol (market['symbol']);
const fundingRate = this.safeNumber (entry, 'funding_rate');
const datetime = this.safeString (entry, 'timestamp');
rates.push ({
'info': entry,
'symbol': symbol,
'fundingRate': fundingRate,
'timestamp': this.parse8601 (datetime),
'datetime': datetime,
});
}
}
const sorted = this.sortBy (rates, 'timestamp');
return this.filterBySymbolSinceLimit (sorted, symbol, since, limit);
}
async fetchPositions (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
const response = await this.privateGetFuturesAccount (this.extend (request, params));
//
// [
// {
// "symbol": "ETHUSDT_PERP",
// "type": "isolated",
// "leverage": "10.00",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z",
// currencies": [
// {
// "code": "USDT",
// "margin_balance": "7.478100643043",
// "reserved_orders": "0",
// "reserved_positions": "0.303530761300"
// }
// ],
// "positions": [
// {
// "id": 2470568,
// "symbol": "ETHUSDT_PERP",
// "quantity": "0.001",
// "price_entry": "2927.509",
// "price_margin_call": "0",
// "price_liquidation": "0",
// "pnl": "0",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z"
// }
// ]
// },
// ]
//
const result = [];
for (let i = 0; i < response.length; i++) {
result.push (this.parsePosition (response[i]));
}
return result;
}
parsePosition (position, market = undefined) {
//
// [
// {
// "symbol": "ETHUSDT_PERP",
// "type": "isolated",
// "leverage": "10.00",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z",
// currencies": [
// {
// "code": "USDT",
// "margin_balance": "7.478100643043",
// "reserved_orders": "0",
// "reserved_positions": "0.303530761300"
// }
// ],
// "positions": [
// {
// "id": 2470568,
// "symbol": "ETHUSDT_PERP",
// "quantity": "0.001",
// "price_entry": "2927.509",
// "price_margin_call": "0",
// "price_liquidation": "0",
// "pnl": "0",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z"
// }
// ]
// },
// ]
//
const marginType = this.safeString (position, 'type');
const leverage = this.safeNumber (position, 'leverage');
const datetime = this.safeString (position, 'updated_at');
const positions = this.safeValue (position, 'positions', []);
let liquidationPrice = undefined;
let entryPrice = undefined;
for (let i = 0; i < positions.length; i++) {
const entry = positions[i];
liquidationPrice = this.safeNumber (entry, 'price_liquidation');
entryPrice = this.safeNumber (entry, 'price_entry');
}
const currencies = this.safeValue (position, 'currencies', []);
let collateral = undefined;
for (let i = 0; i < currencies.length; i++) {
const entry = currencies[i];
collateral = this.safeNumber (entry, 'margin_balance');
}
const marketId = this.safeString (position, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
return {
'info': position,
'symbol': symbol,
'notional': undefined,
'marginType': marginType,
'liquidationPrice': liquidationPrice,
'entryPrice': entryPrice,
'unrealizedPnl': undefined,
'percentage': undefined,
'contracts': undefined,
'contractSize': undefined,
'markPrice': undefined,
'side': undefined,
'hedged': undefined,
'timestamp': this.parse8601 (datetime),
'datetime': datetime,
'maintenanceMargin': undefined,
'maintenanceMarginPercentage': undefined,
'collateral': collateral,
'initialMargin': undefined,
'initialMarginPercentage': undefined,
'leverage': leverage,
'marginRatio': undefined,
};
}
async fetchFundingRate (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (!market['swap']) {
throw new BadSymbol (this.id + ' fetchFundingRate() supports swap contracts only');
}
const request = {};
if (symbol !== undefined) {
symbol = market['symbol'];
request['symbols'] = market['id'];
}
const response = await this.publicGetPublicFuturesInfo (this.extend (request, params));
//
// {
// "BTCUSDT_PERP": {
// "contract_type": "perpetual",
// "mark_price": "42307.43",
// "index_price": "42303.27",
// "funding_rate": "0.0001",
// "open_interest": "30.9826",
// "next_funding_time": "2022-03-22T16:00:00.000Z",
// "indicative_funding_rate": "0.0001",
// "premium_index": "0",
// "avg_premium_index": "0.000029587712038098",
// "interest_rate": "0.0001",
// "timestamp": "2022-03-22T08:08:26.687Z"
// }
// }
//
const data = this.safeValue (response, market['id'], {});
return this.parseFundingRate (data, market);
}
parseFundingRate (contract, market = undefined) {
//
// {
// "contract_type": "perpetual",
// "mark_price": "42307.43",
// "index_price": "42303.27",
// "funding_rate": "0.0001",
// "open_interest": "30.9826",
// "next_funding_time": "2022-03-22T16:00:00.000Z",
// "indicative_funding_rate": "0.0001",
// "premium_index": "0",
// "avg_premium_index": "0.000029587712038098",
// "interest_rate": "0.0001",
// "timestamp": "2022-03-22T08:08:26.687Z"
// }
//
const nextFundingDatetime = this.safeString (contract, 'next_funding_time');
const datetime = this.safeString (contract, 'timestamp');
return {
'info': contract,
'symbol': this.safeSymbol (undefined, market),
'markPrice': this.safeNumber (contract, 'mark_price'),
'indexPrice': this.safeNumber (contract, 'index_price'),
'interestRate': this.safeNumber (contract, 'interest_rate'),
'estimatedSettlePrice': undefined,
'timestamp': this.parse8601 (datetime),
'datetime': datetime,
'fundingRate': this.safeNumber (contract, 'funding_rate'),
'fundingTimestamp': undefined,
'fundingDatetime': undefined,
'nextFundingRate': this.safeNumber (contract, 'indicative_funding_rate'),
'nextFundingTimestamp': this.parse8601 (nextFundingDatetime),
'nextFundingDatetime': nextFundingDatetime,
'previousFundingRate': undefined,
'previousFundingTimestamp': undefined,
'previousFundingDatetime': undefined,
};
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
//
// {
// "error": {
// "code": 20001,
// "message": "Insufficient funds",
// "description": "Check that the funds are sufficient, given commissions"
// }
// }
//
// {
// "error": {
// "code": "600",
// "message": "Action not allowed"
// }
// }
//
const error = this.safeValue (response, 'error');
const errorCode = this.safeString (error, 'code');
if (errorCode !== undefined) {
const feedback = this.id + ' ' + body;
const message = this.safeString2 (error, 'message', 'description');
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
throw new ExchangeError (feedback);
}
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const query = this.omit (params, this.extractParams (path));
const implodedPath = this.implodeParams (path, params);
let url = this.urls['api'][api] + '/' + implodedPath;
let getRequest = undefined;
const keys = Object.keys (query);
const queryLength = keys.length;
headers = {
'Content-Type': 'application/json',
};
if (method === 'GET') {
if (queryLength) {
getRequest = '?' + this.urlencode (query);
url = url + getRequest;
}
} else {
body = this.json (params);
}
if (api === 'private') {
this.checkRequiredCredentials ();
const timestamp = this.nonce ().toString ();
const payload = [ method, '/api/3/' + implodedPath ];
if (method === 'GET') {
if (getRequest !== undefined) {
payload.push (getRequest);
}
} else {
payload.push (body);
}
payload.push (timestamp);
const payloadString = payload.join ('');
const signature = this.hmac (this.encode (payloadString), this.encode (this.secret), 'sha256', 'hex');
const secondPayload = this.apiKey + ':' + signature + ':' + timestamp;
const encoded = this.decode (this.stringToBase64 (secondPayload));
headers['Authorization'] = 'HS256 ' + encoded;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
};
|
js/hitbtc3.js
|
const Exchange = require ('./base/Exchange');
const { TICK_SIZE } = require ('./base/functions/number');
const Precise = require ('./base/Precise');
const { BadSymbol, BadRequest, OnMaintenance, AccountSuspended, PermissionDenied, ExchangeError, RateLimitExceeded, ExchangeNotAvailable, OrderNotFound, InsufficientFunds, InvalidOrder, AuthenticationError, ArgumentsRequired } = require ('./base/errors');
module.exports = class hitbtc3 extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'hitbtc3',
'name': 'HitBTC',
'countries': [ 'HK' ],
// 300 requests per second => 1000ms / 300 = 3.333 (Trading: placing, replacing, deleting)
// 30 requests per second => ( 1000ms / rateLimit ) / 30 = cost = 10 (Market Data and other Public Requests)
// 20 requests per second => ( 1000ms / rateLimit ) / 20 = cost = 15 (All Other)
'rateLimit': 3.333, // TODO: optimize https://api.hitbtc.com/#rate-limiting
'version': '3',
'pro': true,
'has': {
'CORS': false,
'spot': true,
'margin': undefined, // has but not fully implemented
'swap': true,
'future': false,
'option': undefined,
'addMargin': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'createReduceOnlyOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchFundingHistory': false,
'fetchFundingRate': true,
'fetchFundingRateHistory': true,
'fetchFundingRates': false,
'fetchIndexOHLCV': undefined,
'fetchLeverageTiers': undefined,
'fetchMarketLeverageTiers': undefined,
'fetchMarkets': true,
'fetchMarkOHLCV': undefined,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrder': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrderBooks': true,
'fetchOrders': false,
'fetchOrderTrades': true,
'fetchPosition': false,
'fetchPositions': true,
'fetchPremiumIndexOHLCV': undefined,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchTradingFee': true,
'fetchTradingFees': true,
'fetchTransactions': true,
'fetchWithdrawals': true,
'reduceMargin': undefined,
'setLeverage': undefined,
'setMarginMode': false,
'setPositionMode': false,
'transfer': true,
'withdraw': true,
},
'precisionMode': TICK_SIZE,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'test': {
'public': 'https://api.demo.hitbtc.com',
'private': 'https://api.demo.hitbtc.com',
},
'api': {
'public': 'https://api.hitbtc.com/api/3',
'private': 'https://api.hitbtc.com/api/3',
},
'www': 'https://hitbtc.com',
'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
'doc': [
'https://api.hitbtc.com',
'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
],
'fees': [
'https://hitbtc.com/fees-and-limits',
'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
],
},
'api': {
'public': {
'get': {
'public/currency': 10,
'public/symbol': 10,
'public/ticker': 10,
'public/price/rate': 10,
'public/trades': 10,
'public/orderbook': 10,
'public/candles': 10,
'public/futures/info': 10,
'public/futures/history/funding': 10,
'public/futures/candles/index_price': 10,
'public/futures/candles/mark_price': 10,
'public/futures/candles/premium_index': 10,
'public/futures/candles/open_interest': 10,
},
},
'private': {
'get': {
'spot/balance': 15,
'spot/order': 15,
'spot/order/{client_order_id}': 15,
'spot/fee': 15,
'spot/fee/{symbol}': 15,
'spot/history/order': 15,
'spot/history/trade': 15,
'margin/account': 15,
'margin/account/isolated/{symbol}': 15,
'margin/order': 15,
'margin/order/{client_order_id}': 15,
'margin/history/order': 15,
'margin/history/trade': 15,
'futures/balance': 15,
'futures/account': 15,
'futures/account/isolated/{symbol}': 15,
'futures/order': 15,
'futures/order/{client_order_id}': 15,
'futures/fee': 15,
'futures/fee/{symbol}': 15,
'futures/history/order': 15,
'futures/history/trade': 15,
'wallet/balance': 15,
'wallet/crypto/address': 15,
'wallet/crypto/address/recent-deposit': 15,
'wallet/crypto/address/recent-withdraw': 15,
'wallet/crypto/address/check-mine': 15,
'wallet/transactions': 15,
'wallet/crypto/check-offchain-available': 15,
'wallet/crypto/fee/estimate': 15,
'sub-account': 15,
'sub-account/acl': 15,
'sub-account/balance/{subAccID}': 15,
'sub-account/crypto/address/{subAccID}/{currency}': 15,
},
'post': {
'spot/order': 1,
'margin/order': 1,
'futures/order': 1,
'wallet/convert': 15,
'wallet/crypto/withdraw': 15,
'wallet/transfer': 15,
'sub-account/freeze': 15,
'sub-account/activate': 15,
'sub-account/transfer': 15,
'sub-account/acl': 15,
},
'patch': {
'spot/order/{client_order_id}': 1,
'margin/order/{client_order_id}': 1,
'futures/order/{client_order_id}': 1,
},
'delete': {
'spot/order': 1,
'spot/order/{client_order_id}': 1,
'margin/position': 1,
'margin/position/isolated/{symbol}': 1,
'margin/order': 1,
'margin/order/{client_order_id}': 1,
'futures/position': 1,
'futures/position/isolated/{symbol}': 1,
'futures/order': 1,
'futures/order/{client_order_id}': 1,
'wallet/crypto/withdraw/{id}': 1,
},
'put': {
'margin/account/isolated/{symbol}': 1,
'futures/account/isolated/{symbol}': 1,
'wallet/crypto/withdraw/{id}': 1,
},
},
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0009'),
'maker': this.parseNumber ('0.0009'),
'tiers': {
'maker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0002') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0001') ],
[ this.parseNumber ('20000'), this.parseNumber ('0') ],
[ this.parseNumber ('50000'), this.parseNumber ('-0.0001') ],
[ this.parseNumber ('100000'), this.parseNumber ('-0.0001') ],
],
'taker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('20000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('50000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('100000'), this.parseNumber ('0.0002') ],
],
},
},
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30', // default
'1h': 'H1',
'4h': 'H4',
'1d': 'D1',
'1w': 'D7',
'1M': '1M',
},
'exceptions': {
'exact': {
'429': RateLimitExceeded,
'500': ExchangeError,
'503': ExchangeNotAvailable,
'504': ExchangeNotAvailable,
'600': PermissionDenied,
'800': ExchangeError,
'1002': AuthenticationError,
'1003': PermissionDenied,
'1004': AuthenticationError,
'1005': AuthenticationError,
'2001': BadSymbol,
'2002': BadRequest,
'2003': BadRequest,
'2010': BadRequest,
'2011': BadRequest,
'2012': BadRequest,
'2020': BadRequest,
'2022': BadRequest,
'10001': BadRequest,
'10021': AccountSuspended,
'10022': BadRequest,
'20001': InsufficientFunds,
'20002': OrderNotFound,
'20003': ExchangeError,
'20004': ExchangeError,
'20005': ExchangeError,
'20006': ExchangeError,
'20007': ExchangeError,
'20008': InvalidOrder,
'20009': InvalidOrder,
'20010': OnMaintenance,
'20011': ExchangeError,
'20012': ExchangeError,
'20014': ExchangeError,
'20016': ExchangeError,
'20031': ExchangeError,
'20032': ExchangeError,
'20033': ExchangeError,
'20034': ExchangeError,
'20040': ExchangeError,
'20041': ExchangeError,
'20042': ExchangeError,
'20043': ExchangeError,
'20044': PermissionDenied,
'20045': InvalidOrder,
'20080': ExchangeError,
'21001': ExchangeError,
'21003': AccountSuspended,
'21004': AccountSuspended,
},
'broad': {},
},
'options': {
'networks': {
'ETH': 'USDT20',
'ERC20': 'USDT20',
'TRX': 'USDTRX',
'TRC20': 'USDTRX',
'OMNI': 'USDT',
},
'accountsByType': {
'spot': 'spot',
'funding': 'wallet',
'wallet': 'wallet',
'future': 'derivatives',
'derivatives': 'derivatives',
},
},
});
}
nonce () {
return this.milliseconds ();
}
async fetchMarkets (params = {}) {
const response = await this.publicGetPublicSymbol (params);
//
// {
// "AAVEUSDT_PERP":{
// "type":"futures",
// "expiry":null,
// "underlying":"AAVE",
// "base_currency":null,
// "quote_currency":"USDT",
// "quantity_increment":"0.01",
// "tick_size":"0.001",
// "take_rate":"0.0005",
// "make_rate":"0.0002",
// "fee_currency":"USDT",
// "margin_trading":true,
// "max_initial_leverage":"50.00"
// },
// "MANAUSDT":{
// "type":"spot",
// "base_currency":"MANA",
// "quote_currency":"USDT",
// "quantity_increment":"1",
// "tick_size":"0.0000001",
// "take_rate":"0.0025",
// "make_rate":"0.001",
// "fee_currency":"USDT",
// "margin_trading":true,
// "max_initial_leverage":"5.00"
// },
// }
//
const result = [];
const ids = Object.keys (response);
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const market = this.safeValue (response, id);
const marketType = this.safeString (market, 'type');
const expiry = this.safeInteger (market, 'expiry');
const contract = (marketType === 'futures');
const spot = (marketType === 'spot');
const marginTrading = this.safeValue (market, 'margin_trading', false);
const margin = spot && marginTrading;
const future = (expiry !== undefined);
const swap = (contract && !future);
const option = false;
const baseId = this.safeString2 (market, 'base_currency', 'underlying');
const quoteId = this.safeString (market, 'quote_currency');
const feeCurrencyId = this.safeString (market, 'fee_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const feeCurrency = this.safeCurrencyCode (feeCurrencyId);
let settleId = undefined;
let settle = undefined;
let symbol = base + '/' + quote;
let type = 'spot';
let contractSize = undefined;
let linear = undefined;
let inverse = undefined;
if (contract) {
contractSize = this.parseNumber ('1');
settleId = feeCurrencyId;
settle = this.safeCurrencyCode (settleId);
linear = ((quote !== undefined) && (quote === settle));
inverse = !linear;
symbol = symbol + ':' + settle;
if (future) {
symbol = symbol + '-' + expiry;
type = 'future';
} else {
type = 'swap';
}
}
const lotString = this.safeString (market, 'quantity_increment');
const stepString = this.safeString (market, 'tick_size');
const lot = this.parseNumber (lotString);
const step = this.parseNumber (stepString);
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': spot,
'margin': margin,
'swap': swap,
'future': future,
'option': option,
'active': true,
'contract': contract,
'linear': linear,
'inverse': inverse,
'taker': this.safeNumber (market, 'take_rate'),
'maker': this.safeNumber (market, 'make_rate'),
'contractSize': contractSize,
'expiry': expiry,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'feeCurrency': feeCurrency,
'precision': {
'amount': lot,
'price': step,
},
'limits': {
'leverage': {
'min': this.parseNumber ('1'),
'max': this.safeNumber (market, 'max_initial_leverage', 1),
},
'amount': {
'min': lot,
'max': undefined,
},
'price': {
'min': step,
'max': undefined,
},
'cost': {
'min': this.parseNumber (Precise.stringMul (lotString, stepString)),
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.publicGetPublicCurrency (params);
//
// {
// "WEALTH": {
// "full_name": "ConnectWealth",
// "payin_enabled": false,
// "payout_enabled": false,
// "transfer_enabled": true,
// "precision_transfer": "0.001",
// "networks": [
// {
// "network": "ETH",
// "protocol": "ERC20",
// "default": true,
// "payin_enabled": false,
// "payout_enabled": false,
// "precision_payout": "0.001",
// "payout_fee": "0.016800000000",
// "payout_is_payment_id": false,
// "payin_payment_id": false,
// "payin_confirmations": "2"
// }
// ]
// }
// }
//
const result = {};
const currencies = Object.keys (response);
for (let i = 0; i < currencies.length; i++) {
const currencyId = currencies[i];
const code = this.safeCurrencyCode (currencyId);
const entry = response[currencyId];
const name = this.safeString (entry, 'full_name');
const precision = this.safeNumber (entry, 'precision_transfer');
const payinEnabled = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabled = this.safeValue (entry, 'payout_enabled', false);
const transferEnabled = this.safeValue (entry, 'transfer_enabled', false);
const active = payinEnabled && payoutEnabled && transferEnabled;
const rawNetworks = this.safeValue (entry, 'networks', []);
const networks = {};
let fee = undefined;
let depositEnabled = undefined;
let withdrawEnabled = undefined;
for (let j = 0; j < rawNetworks.length; j++) {
const rawNetwork = rawNetworks[j];
let networkId = this.safeString (rawNetwork, 'protocol');
if (networkId.length === 0) {
networkId = this.safeString (rawNetwork, 'network');
}
const network = this.safeNetwork (networkId);
fee = this.safeNumber (rawNetwork, 'payout_fee');
const precision = this.safeNumber (rawNetwork, 'precision_payout');
const payinEnabledNetwork = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabledNetwork = this.safeValue (entry, 'payout_enabled', false);
const activeNetwork = payinEnabledNetwork && payoutEnabledNetwork;
if (payinEnabledNetwork && !depositEnabled) {
depositEnabled = true;
} else if (!payinEnabledNetwork) {
depositEnabled = false;
}
if (payoutEnabledNetwork && !withdrawEnabled) {
withdrawEnabled = true;
} else if (!payoutEnabledNetwork) {
withdrawEnabled = false;
}
networks[network] = {
'info': rawNetwork,
'id': networkId,
'network': network,
'fee': fee,
'active': activeNetwork,
'deposit': payinEnabledNetwork,
'withdraw': payoutEnabledNetwork,
'precision': precision,
'limits': {
'withdraw': {
'min': undefined,
'max': undefined,
},
},
};
}
const networksKeys = Object.keys (networks);
const networksLength = networksKeys.length;
result[code] = {
'info': entry,
'code': code,
'id': currencyId,
'precision': precision,
'name': name,
'active': active,
'deposit': depositEnabled,
'withdraw': withdrawEnabled,
'networks': networks,
'fee': (networksLength <= 1) ? fee : undefined,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
},
};
}
return result;
}
safeNetwork (networkId) {
if (networkId === undefined) {
return undefined;
} else {
return networkId.toUpperCase ();
}
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const network = this.safeStringUpper (params, 'network');
if ((network !== undefined) && (code === 'USDT')) {
const networks = this.safeValue (this.options, 'networks');
const parsedNetwork = this.safeString (networks, network);
if (parsedNetwork !== undefined) {
request['currency'] = parsedNetwork;
}
params = this.omit (params, 'network');
}
const response = await this.privateGetWalletCryptoAddress (this.extend (request, params));
//
// [{"currency":"ETH","address":"0xd0d9aea60c41988c3e68417e2616065617b7afd3"}]
//
const firstAddress = this.safeValue (response, 0);
const address = this.safeString (firstAddress, 'address');
const currencyId = this.safeString (firstAddress, 'currency');
const tag = this.safeString (firstAddress, 'payment_id');
const parsedCode = this.safeCurrencyCode (currencyId);
return {
'info': response,
'address': address,
'tag': tag,
'code': parsedCode,
'network': undefined,
};
}
parseBalance (response) {
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const currencyId = this.safeString (entry, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (entry, 'available');
account['used'] = this.safeString (entry, 'reserved');
result[code] = account;
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
const type = this.safeStringLower (params, 'type', 'spot');
params = this.omit (params, [ 'type' ]);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
const account = this.safeString (accountsByType, type);
let response = undefined;
if (account === 'wallet') {
response = await this.privateGetWalletBalance (params);
} else if (account === 'spot') {
response = await this.privateGetSpotBalance (params);
} else if (account === 'derivatives') {
response = await this.privateGetFuturesBalance (params);
} else {
const keys = Object.keys (accountsByType);
throw new BadRequest (this.id + ' fetchBalance() type parameter must be one of ' + keys.join (', '));
}
//
// [
// {
// "currency": "PAXG",
// "available": "0",
// "reserved": "0",
// "reserved_margin": "0",
// },
// ...
// ]
//
return this.parseBalance (response);
}
async fetchTicker (symbol, params = {}) {
const response = await this.fetchTickers ([ symbol ], params);
return this.safeValue (response, symbol);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
const delimited = marketIds.join (',');
request['symbols'] = delimited;
}
const response = await this.publicGetPublicTicker (this.extend (request, params));
//
// {
// "BTCUSDT": {
// "ask": "63049.06",
// "bid": "63046.41",
// "last": "63048.36",
// "low": "62010.00",
// "high": "66657.99",
// "open": "64839.75",
// "volume": "15272.13278",
// "volume_quote": "976312127.6277998",
// "timestamp": "2021-10-22T04:25:47.573Z"
// }
// }
//
const result = {};
const keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
const marketId = keys[i];
const market = this.safeMarket (marketId);
const symbol = market['symbol'];
const entry = response[marketId];
result[symbol] = this.parseTicker (entry, market);
}
return this.filterByArray (result, 'symbol', symbols);
}
parseTicker (ticker, market = undefined) {
//
// {
// "ask": "62756.01",
// "bid": "62754.09",
// "last": "62755.87",
// "low": "62010.00",
// "high": "66657.99",
// "open": "65089.27",
// "volume": "16719.50366",
// "volume_quote": "1063422878.8156828",
// "timestamp": "2021-10-22T07:29:14.585Z"
// }
//
const timestamp = this.parse8601 (ticker['timestamp']);
const symbol = this.safeSymbol (undefined, market);
const baseVolume = this.safeString (ticker, 'volume');
const quoteVolume = this.safeString (ticker, 'volume_quote');
const open = this.safeString (ticker, 'open');
const last = this.safeString (ticker, 'last');
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, 'high'),
'low': this.safeString (ticker, 'low'),
'bid': this.safeString (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeString (ticker, 'ask'),
'askVolume': undefined,
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, false);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
// symbol is optional for hitbtc fetchTrades
request['symbols'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['from'] = since;
}
const response = await this.publicGetPublicTrades (this.extend (request, params));
const marketIds = Object.keys (response);
let trades = [];
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const market = this.market (marketId);
const rawTrades = response[marketId];
const parsed = this.parseTrades (rawTrades, market);
trades = this.arrayConcat (trades, parsed);
}
return trades;
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['from'] = since;
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchMyTrades', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryTrade',
'swap': 'privateGetFuturesHistoryTrade',
});
const response = await this[method] (this.extend (request, query));
return this.parseTrades (response, market, since, limit);
}
parseTrade (trade, market = undefined) {
//
// createOrder (market)
//
// {
// id: '1569252895',
// position_id: '0',
// quantity: '10',
// price: '0.03919424',
// fee: '0.000979856000',
// timestamp: '2022-01-25T19:38:36.153Z',
// taker: true
// }
//
// fetchTrades
//
// {
// id: 974786185,
// price: '0.032462',
// qty: '0.3673',
// side: 'buy',
// timestamp: '2020-10-16T12:57:39.846Z'
// }
//
// fetchMyTrades spot
//
// {
// id: 277210397,
// clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
// orderId: 28102855393,
// symbol: 'ETHBTC',
// side: 'sell',
// quantity: '0.002',
// price: '0.073365',
// fee: '0.000000147',
// timestamp: '2018-04-28T18:39:55.345Z',
// taker: true
// }
//
// fetchMyTrades swap
//
// {
// "id": 4718564,
// "order_id": 58730811958,
// "client_order_id": "475c47d97f867f09726186eb22b4c3d4",
// "symbol": "BTCUSDT_PERP",
// "side": "sell",
// "quantity": "0.0001",
// "price": "41118.51",
// "fee": "0.002055925500",
// "timestamp": "2022-03-17T05:23:17.795Z",
// "taker": true,
// "position_id": 2350122,
// "pnl": "0.002255000000",
// "liquidation": false
// }
//
const timestamp = this.parse8601 (trade['timestamp']);
const marketId = this.safeString (trade, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let fee = undefined;
const feeCostString = this.safeString (trade, 'fee');
const taker = this.safeValue (trade, 'taker');
let takerOrMaker = undefined;
if (taker !== undefined) {
takerOrMaker = taker ? 'taker' : 'maker';
}
if (feeCostString !== undefined) {
const info = this.safeValue (market, 'info', {});
const feeCurrency = this.safeString (info, 'fee_currency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrency);
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
};
}
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const orderId = this.safeString (trade, 'clientOrderId');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString2 (trade, 'quantity', 'qty');
const side = this.safeString (trade, 'side');
const id = this.safeString (trade, 'id');
return this.safeTrade ({
'info': trade,
'id': id,
'order': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': undefined,
'fee': fee,
}, market);
}
async fetchTransactionsHelper (types, code, since, limit, params) {
await this.loadMarkets ();
const request = {
'types': types,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currencies'] = currency['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetWalletTransactions (this.extend (request, params));
//
// [
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
// ]
//
return this.parseTransactions (response, currency, since, limit, params);
}
parseTransactionStatus (status) {
const statuses = {
'PENDING': 'pending',
'FAILED': 'failed',
'SUCCESS': 'ok',
};
return this.safeString (statuses, status, status);
}
parseTransactionType (type) {
const types = {
'DEPOSIT': 'deposit',
'WITHDRAW': 'withdrawal',
};
return this.safeString (types, type, type);
}
parseTransaction (transaction, currency = undefined) {
//
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
//
// {
// "id": "102703545",
// "created_at": "2018-03-30T21:39:17.854Z",
// "updated_at": "2018-03-31T00:23:19.067Z",
// "status": "SUCCESS",
// "type": "WITHDRAW",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "5ecd7a85-ce5d-4d52-a916-b8b755e20926",
// "index": "918286359",
// "currency": "OMG",
// "amount": "2.45",
// "fee": "1.22",
// "hash": "0x1c621d89e7a0841342d5fb3b3587f60b95351590161e078c4a1daee353da4ca9",
// "address": "0x50227da7644cea0a43258a2e2d7444d01b43dcca",
// "confirmations": "0"
// }
// }
//
const id = this.safeString (transaction, 'id');
const timestamp = this.parse8601 (this.safeString (transaction, 'created_at'));
const updated = this.parse8601 (this.safeString (transaction, 'updated_at'));
const type = this.parseTransactionType (this.safeString (transaction, 'type'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const native = this.safeValue (transaction, 'native');
const currencyId = this.safeString (native, 'currency');
const code = this.safeCurrencyCode (currencyId);
const txhash = this.safeString (native, 'hash');
const address = this.safeString (native, 'address');
const addressTo = address;
const tag = this.safeString (native, 'payment_id');
const tagTo = tag;
const sender = this.safeValue (native, 'senders');
const addressFrom = this.safeString (sender, 0);
const amount = this.safeNumber (native, 'amount');
let fee = undefined;
const feeCost = this.safeNumber (native, 'fee');
if (feeCost !== undefined) {
fee = {
'code': code,
'cost': feeCost,
};
}
return {
'info': transaction,
'id': id,
'txid': txhash,
'code': code,
'amount': amount,
'network': undefined,
'address': address,
'addressFrom': addressFrom,
'addressTo': addressTo,
'tag': tag,
'tagFrom': undefined,
'tagTo': tagTo,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'updated': updated,
'status': status,
'type': type,
'fee': fee,
};
}
async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT,WITHDRAW', code, since, limit, params);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('WITHDRAW', code, since, limit, params);
}
async fetchOrderBooks (symbols = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
request['symbols'] = marketIds.join (',');
}
if (limit !== undefined) {
request['depth'] = limit;
}
const response = await this.publicGetPublicOrderbook (this.extend (request, params));
const result = {};
const marketIds = Object.keys (response);
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const orderbook = response[marketId];
const symbol = this.safeSymbol (marketId);
const timestamp = this.parse8601 (this.safeString (orderbook, 'timestamp'));
result[symbol] = this.parseOrderBook (response[marketId], symbol, timestamp, 'bid', 'ask');
}
return result;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
const result = await this.fetchOrderBooks ([ symbol ], limit, params);
return result[symbol];
}
parseTradingFee (fee, market = undefined) {
//
// {
// "symbol":"ARVUSDT", // returned from fetchTradingFees only
// "take_rate":"0.0009",
// "make_rate":"0.0009"
// }
//
const taker = this.safeNumber (fee, 'take_rate');
const maker = this.safeNumber (fee, 'make_rate');
const marketId = this.safeString (fee, 'symbol');
const symbol = this.safeSymbol (marketId, market);
return {
'info': fee,
'symbol': symbol,
'taker': taker,
'maker': maker,
};
}
async fetchTradingFee (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const method = this.getSupportedMapping (market['type'], {
'spot': 'privateGetSpotFeeSymbol',
'swap': 'privateGetFuturesFeeSymbol',
});
const response = await this[method] (this.extend (request, params));
//
// {
// "take_rate":"0.0009",
// "make_rate":"0.0009"
// }
//
return this.parseTradingFee (response, market);
}
async fetchTradingFees (symbols = undefined, params = {}) {
await this.loadMarkets ();
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchTradingFees', undefined, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotFee',
'swap': 'privateGetFuturesFee',
});
const response = await this[method] (query);
//
// [
// {
// "symbol":"ARVUSDT",
// "take_rate":"0.0009",
// "make_rate":"0.0009"
// }
// ]
//
const result = {};
for (let i = 0; i < response.length; i++) {
const fee = this.parseTradingFee (response[i]);
const symbol = fee['symbol'];
result[symbol] = fee;
}
return result;
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbols': market['id'],
'period': this.timeframes[timeframe],
};
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicCandles (this.extend (request, params));
//
// {
// "ETHUSDT": [
// {
// "timestamp": "2021-10-25T07:38:00.000Z",
// "open": "4173.391",
// "close": "4170.923",
// "min": "4170.923",
// "max": "4173.986",
// "volume": "0.1879",
// "volume_quote": "784.2517846"
// }
// ]
// }
//
const ohlcvs = this.safeValue (response, market['id']);
return this.parseOHLCVs (ohlcvs, market, timeframe, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// "timestamp":"2015-08-20T19:01:00.000Z",
// "open":"0.006",
// "close":"0.006",
// "min":"0.006",
// "max":"0.006",
// "volume":"0.003",
// "volume_quote":"0.000018"
// }
//
return [
this.parse8601 (this.safeString (ohlcv, 'timestamp')),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'max'),
this.safeNumber (ohlcv, 'min'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'volume'),
];
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchClosedOrders', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryOrder',
'swap': 'privateGetFuturesHistoryOrder',
});
const response = await this[method] (this.extend (request, query));
const parsed = this.parseOrders (response, market, since, limit);
return this.filterByArray (parsed, 'status', [ 'closed', 'canceled' ], false);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOrder', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryOrder',
'swap': 'privateGetFuturesHistoryOrder',
});
const request = {
'client_order_id': id,
};
const response = await this[method] (this.extend (request, query));
//
// [
// {
// "id": "685965182082",
// "client_order_id": "B3CBm9uGg9oYQlw96bBSEt38-6gbgBO0",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0",
// "price": "50000.00",
// "price_average": "0",
// "created_at": "2021-10-26T11:40:09.287Z",
// "updated_at": "2021-10-26T11:40:09.287Z"
// }
// ]
//
const order = this.safeValue (response, 0);
return this.parseOrder (order, market);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'order_id': id, // exchange assigned order id as oppose to the client order id
};
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOrderTrades', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotHistoryTrade',
'swap': 'privateGetFuturesHistoryTrade',
});
const response = await this[method] (this.extend (request, query));
//
// Spot
//
// [
// {
// "id": 1393448977,
// "order_id": 653496804534,
// "client_order_id": "065f6f0ff9d54547848454182263d7b4",
// "symbol": "DICEETH",
// "side": "buy",
// "quantity": "1.4",
// "price": "0.00261455",
// "fee": "0.000003294333",
// "timestamp": "2021-09-19T05:35:56.601Z",
// "taker": true
// }
// ]
//
// Swap
//
// [
// {
// "id": 4718551,
// "order_id": 58730748700,
// "client_order_id": "dcbcd8549e3445ee922665946002ef67",
// "symbol": "BTCUSDT_PERP",
// "side": "buy",
// "quantity": "0.0001",
// "price": "41095.96",
// "fee": "0.002054798000",
// "timestamp": "2022-03-17T05:23:02.217Z",
// "taker": true,
// "position_id": 2350122,
// "pnl": "0",
// "liquidation": false
// }
// ]
//
return this.parseTrades (response, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOpenOrders', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotOrder',
'swap': 'privateGetFuturesOrder',
});
const response = await this[method] (this.extend (request, query));
//
// [
// {
// "id": "488953123149",
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
// ]
//
return this.parseOrders (response, market, since, limit);
}
async fetchOpenOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchOpenOrder', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateGetSpotOrderClientOrderId',
'swap': 'privateGetFuturesOrderClientOrderId',
});
const request = {
'client_order_id': id,
};
const response = await this[method] (this.extend (request, query));
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('cancelAllOrders', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateDeleteSpotOrder',
'swap': 'privateDeleteFuturesOrder',
});
const response = await this[method] (this.extend (request, query));
return this.parseOrders (response, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
};
if (symbol !== undefined) {
market = this.market (symbol);
}
const [ marketType, query ] = this.handleMarketTypeAndParams ('cancelOrder', market, params);
const method = this.getSupportedMapping (marketType, {
'spot': 'privateDeleteSpotOrderClientOrderId',
'swap': 'privateDeleteFuturesOrderClientOrderId',
});
const response = await this[method] (this.extend (request, query));
return this.parseOrder (response, market);
}
async editOrder (id, symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
'quantity': this.amountToPrecision (symbol, amount),
};
if ((type === 'limit') || (type === 'stopLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' limit order requires price');
}
request['price'] = this.priceToPrecision (symbol, price);
}
if (symbol !== undefined) {
market = this.market (symbol);
}
const method = this.getSupportedMapping (market['type'], {
'spot': 'privatePatchSpotOrderClientOrderId',
'swap': 'privatePatchFuturesOrderClientOrderId',
});
const response = await this[method] (this.extend (request, params));
return this.parseOrder (response, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const reduceOnly = this.safeValue2 (params, 'reduce_only', 'reduceOnly');
if (reduceOnly !== undefined) {
if ((market['type'] !== 'swap') && (market['type'] !== 'margin')) {
throw new InvalidOrder (this.id + ' createOrder() does not support reduce_only for ' + market['type'] + ' orders, reduce_only orders are supported for swap and margin markets only');
}
}
const request = {
'type': type,
'side': side,
'quantity': this.amountToPrecision (symbol, amount),
'symbol': market['id'],
// 'client_order_id': 'r42gdPjNMZN-H_xs8RKl2wljg_dfgdg4', // Optional
// 'time_in_force': 'GTC', // Optional GTC, IOC, FOK, Day, GTD
// 'price': this.priceToPrecision (symbol, price), // Required if type is limit, stopLimit, or takeProfitLimit
// 'stop_price': this.safeNumber (params, 'stop_price'), // Required if type is stopLimit, stopMarket, takeProfitLimit, takeProfitMarket
// 'expire_time': '2021-06-15T17:01:05.092Z', // Required if timeInForce is GTD
// 'strict_validate': false,
// 'post_only': false, // Optional
// 'reduce_only': false, // Optional
// 'display_quantity': '0', // Optional
// 'take_rate': 0.001, // Optional
// 'make_rate': 0.001, // Optional
};
const timeInForce = this.safeString2 (params, 'timeInForce', 'time_in_force');
const expireTime = this.safeString (params, 'expire_time');
const stopPrice = this.safeNumber2 (params, 'stopPrice', 'stop_price');
if ((type === 'limit') || (type === 'stopLimit') || (type === 'takeProfitLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' createOrder() requires a price argument for limit orders');
}
request['price'] = this.priceToPrecision (symbol, price);
}
if ((timeInForce === 'GTD')) {
if (expireTime === undefined) {
throw new ExchangeError (this.id + ' createOrder() requires an expire_time parameter for a GTD order');
}
request['expire_time'] = expireTime;
}
if ((type === 'stopLimit') || (type === 'stopMarket') || (type === 'takeProfitLimit') || (type === 'takeProfitMarket')) {
if (stopPrice === undefined) {
throw new ExchangeError (this.id + ' createOrder() requires a stopPrice parameter for stop-loss and take-profit orders');
}
request['stop_price'] = this.priceToPrecision (symbol, stopPrice);
}
const method = this.getSupportedMapping (market['type'], {
'spot': 'privatePostSpotOrder',
'swap': 'privatePostFuturesOrder',
});
const response = await this[method] (this.extend (request, params));
return this.parseOrder (response, market);
}
async createReduceOnlyOrder (symbol, type, side, amount, price = undefined, params = {}) {
const request = {
'reduce_only': true,
};
return await this.createOrder (symbol, type, side, amount, price, this.extend (request, params));
}
parseOrderStatus (status) {
const statuses = {
'new': 'open',
'suspended': 'open',
'partiallyFilled': 'open',
'filled': 'closed',
'canceled': 'canceled',
'expired': 'failed',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// limit
// {
// "id": 488953123149,
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "price_average": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
//
// market
// {
// "id": "685877626834",
// "client_order_id": "Yshl7G-EjaREyXQYaGbsmdtVbW-nzQwu",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "filled",
// "type": "market",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0.00010",
// "post_only": false,
// "created_at": "2021-10-26T08:55:55.1Z",
// "updated_at": "2021-10-26T08:55:55.1Z",
// "trades": [
// {
// "id": "1437229630",
// "position_id": "0",
// "quantity": "0.00010",
// "price": "62884.78",
// "fee": "0.005659630200",
// "timestamp": "2021-10-26T08:55:55.1Z",
// "taker": true
// }
// ]
// }
//
// swap
//
// {
// "id": 58418961892,
// "client_order_id": "r42gdPjNMZN-H_xs8RKl2wljg_dfgdg4",
// "symbol": "BTCUSDT_PERP",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.0005",
// "quantity_cumulative": "0",
// "price": "30000.00",
// "post_only": false,
// "reduce_only": false,
// "created_at": "2022-03-16T08:16:53.039Z",
// "updated_at": "2022-03-16T08:16:53.039Z"
// }
//
const id = this.safeString (order, 'client_order_id');
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const side = this.safeString (order, 'side');
const type = this.safeString (order, 'type');
const amount = this.safeString (order, 'quantity');
const price = this.safeString (order, 'price');
const average = this.safeString (order, 'price_average');
const created = this.safeString (order, 'created_at');
const timestamp = this.parse8601 (created);
const updated = this.safeString (order, 'updated_at');
let lastTradeTimestamp = undefined;
if (updated !== created) {
lastTradeTimestamp = this.parse8601 (updated);
}
const filled = this.safeString (order, 'quantity_cumulative');
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const marketId = this.safeString (order, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
const postOnly = this.safeValue (order, 'post_only');
const timeInForce = this.safeString (order, 'time_in_force');
const rawTrades = this.safeValue (order, 'trades');
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'price': price,
'amount': amount,
'type': type,
'side': side,
'timeInForce': timeInForce,
'postOnly': postOnly,
'filled': filled,
'remaining': undefined,
'cost': undefined,
'status': status,
'average': average,
'trades': rawTrades,
'fee': undefined,
}, market);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
// account can be "spot", "wallet", or "derivatives"
await this.loadMarkets ();
const currency = this.currency (code);
const requestAmount = this.currencyToPrecision (code, amount);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
fromAccount = fromAccount.toLowerCase ();
toAccount = toAccount.toLowerCase ();
const fromId = this.safeString (accountsByType, fromAccount);
const toId = this.safeString (accountsByType, toAccount);
const keys = Object.keys (accountsByType);
if (fromId === undefined) {
throw new ArgumentsRequired (this.id + ' transfer() fromAccount argument must be one of ' + keys.join (', '));
}
if (toId === undefined) {
throw new ArgumentsRequired (this.id + ' transfer() toAccount argument must be one of ' + keys.join (', '));
}
if (fromId === toId) {
throw new BadRequest (this.id + ' transfer() fromAccount and toAccount arguments cannot be the same account');
}
const request = {
'currency': currency['id'],
'amount': requestAmount,
'source': fromId,
'destination': toId,
};
const response = await this.privatePostWalletTransfer (this.extend (request, params));
// [ '2db6ebab-fb26-4537-9ef8-1a689472d236' ]
const id = this.safeString (response, 0);
return {
'info': response,
'id': id,
'timestamp': undefined,
'datetime': undefined,
'amount': this.parseNumber (requestAmount),
'currency': code,
'fromAccount': fromAccount,
'toAccount': toAccount,
'status': undefined,
};
}
async convertCurrencyNetwork (code, amount, fromNetwork, toNetwork, params) {
await this.loadMarkets ();
if (code !== 'USDT') {
throw new ExchangeError (this.id + ' convertCurrencyNetwork() only supports USDT currently');
}
const networks = this.safeValue (this.options, 'networks', {});
fromNetwork = fromNetwork.toUpperCase ();
toNetwork = toNetwork.toUpperCase ();
fromNetwork = this.safeString (networks, fromNetwork); // handle ETH>ERC20 alias
toNetwork = this.safeString (networks, toNetwork); // handle ETH>ERC20 alias
if (fromNetwork === toNetwork) {
throw new BadRequest (this.id + ' fromNetwork cannot be the same as toNetwork');
}
if ((fromNetwork === undefined) || (toNetwork === undefined)) {
const keys = Object.keys (networks);
throw new ArgumentsRequired (this.id + ' convertCurrencyNetwork() requires a fromNetwork parameter and a toNetwork parameter, supported networks are ' + keys.join (', '));
}
const request = {
'from_currency': fromNetwork,
'to_currency': toNetwork,
'amount': this.currencyToPrecision (code, amount),
};
const response = await this.privatePostWalletConvert (this.extend (request, params));
// {"result":["587a1868-e62d-4d8e-b27c-dbdb2ee96149","e168df74-c041-41f2-b76c-e43e4fed5bc7"]}
return {
'info': response,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
await this.loadMarkets ();
this.checkAddress (address);
const currency = this.currency (code);
const request = {
'currency': currency['id'],
'amount': amount,
'address': address,
};
if (tag !== undefined) {
request['payment_id'] = tag;
}
const networks = this.safeValue (this.options, 'networks', {});
const network = this.safeStringUpper (params, 'network');
if ((network !== undefined) && (code === 'USDT')) {
const parsedNetwork = this.safeString (networks, network);
if (parsedNetwork !== undefined) {
request['currency'] = parsedNetwork;
}
params = this.omit (params, 'network');
}
const response = await this.privatePostWalletCryptoWithdraw (this.extend (request, params));
// {"id":"084cfcd5-06b9-4826-882e-fdb75ec3625d"}
const id = this.safeString (response, 'id');
return {
'info': response,
'id': id,
};
}
async fetchFundingRateHistory (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
// all arguments are optional
// 'symbols': Comma separated list of symbol codes,
// 'sort': 'DESC' or 'ASC'
// 'from': 'Datetime or Number',
// 'till': 'Datetime or Number',
// 'limit': 100,
// 'offset': 0,
};
if (symbol !== undefined) {
market = this.market (symbol);
symbol = market['symbol'];
request['symbols'] = market['id'];
}
if (since !== undefined) {
request['from'] = since;
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicFuturesHistoryFunding (this.extend (request, params));
//
// {
// "BTCUSDT_PERP": [
// {
// "timestamp": "2021-07-29T16:00:00.271Z",
// "funding_rate": "0.0001",
// "avg_premium_index": "0.000061858585213222",
// "next_funding_time": "2021-07-30T00:00:00.000Z",
// "interest_rate": "0.0001"
// },
// ...
// ],
// ...
// }
//
const contracts = Object.keys (response);
const rates = [];
for (let i = 0; i < contracts.length; i++) {
const marketId = contracts[i];
const market = this.safeMarket (marketId);
const fundingRateData = response[marketId];
for (let i = 0; i < fundingRateData.length; i++) {
const entry = fundingRateData[i];
const symbol = this.safeSymbol (market['symbol']);
const fundingRate = this.safeNumber (entry, 'funding_rate');
const datetime = this.safeString (entry, 'timestamp');
rates.push ({
'info': entry,
'symbol': symbol,
'fundingRate': fundingRate,
'timestamp': this.parse8601 (datetime),
'datetime': datetime,
});
}
}
const sorted = this.sortBy (rates, 'timestamp');
return this.filterBySymbolSinceLimit (sorted, symbol, since, limit);
}
async fetchPositions (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
const response = await this.privateGetFuturesAccount (this.extend (request, params));
//
// [
// {
// "symbol": "ETHUSDT_PERP",
// "type": "isolated",
// "leverage": "10.00",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z",
// currencies": [
// {
// "code": "USDT",
// "margin_balance": "7.478100643043",
// "reserved_orders": "0",
// "reserved_positions": "0.303530761300"
// }
// ],
// "positions": [
// {
// "id": 2470568,
// "symbol": "ETHUSDT_PERP",
// "quantity": "0.001",
// "price_entry": "2927.509",
// "price_margin_call": "0",
// "price_liquidation": "0",
// "pnl": "0",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z"
// }
// ]
// },
// ]
//
const result = [];
for (let i = 0; i < response.length; i++) {
result.push (this.parsePosition (response[i]));
}
return result;
}
parsePosition (position, market = undefined) {
//
// [
// {
// "symbol": "ETHUSDT_PERP",
// "type": "isolated",
// "leverage": "10.00",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z",
// currencies": [
// {
// "code": "USDT",
// "margin_balance": "7.478100643043",
// "reserved_orders": "0",
// "reserved_positions": "0.303530761300"
// }
// ],
// "positions": [
// {
// "id": 2470568,
// "symbol": "ETHUSDT_PERP",
// "quantity": "0.001",
// "price_entry": "2927.509",
// "price_margin_call": "0",
// "price_liquidation": "0",
// "pnl": "0",
// "created_at": "2022-03-19T07:54:35.24Z",
// "updated_at": "2022-03-19T07:54:58.922Z"
// }
// ]
// },
// ]
//
const marginType = this.safeString (position, 'type');
const leverage = this.safeNumber (position, 'leverage');
const datetime = this.safeString (position, 'updated_at');
const positions = this.safeValue (position, 'positions', []);
let liquidationPrice = undefined;
let entryPrice = undefined;
for (let i = 0; i < positions.length; i++) {
const entry = positions[i];
liquidationPrice = this.safeNumber (entry, 'price_liquidation');
entryPrice = this.safeNumber (entry, 'price_entry');
}
const currencies = this.safeValue (position, 'currencies', []);
let collateral = undefined;
for (let i = 0; i < currencies.length; i++) {
const entry = currencies[i];
collateral = this.safeNumber (entry, 'margin_balance');
}
const marketId = this.safeString (position, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
return {
'info': position,
'symbol': symbol,
'notional': undefined,
'marginType': marginType,
'liquidationPrice': liquidationPrice,
'entryPrice': entryPrice,
'unrealizedPnl': undefined,
'percentage': undefined,
'contracts': undefined,
'contractSize': undefined,
'markPrice': undefined,
'side': undefined,
'hedged': undefined,
'timestamp': this.parse8601 (datetime),
'datetime': datetime,
'maintenanceMargin': undefined,
'maintenanceMarginPercentage': undefined,
'collateral': collateral,
'initialMargin': undefined,
'initialMarginPercentage': undefined,
'leverage': leverage,
'marginRatio': undefined,
};
}
async fetchFundingRate (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (!market['swap']) {
throw new BadSymbol (this.id + ' fetchFundingRate() supports swap contracts only');
}
const request = {};
if (symbol !== undefined) {
symbol = market['symbol'];
request['symbols'] = market['id'];
}
const response = await this.publicGetPublicFuturesInfo (this.extend (request, params));
//
// {
// "BTCUSDT_PERP": {
// "contract_type": "perpetual",
// "mark_price": "42307.43",
// "index_price": "42303.27",
// "funding_rate": "0.0001",
// "open_interest": "30.9826",
// "next_funding_time": "2022-03-22T16:00:00.000Z",
// "indicative_funding_rate": "0.0001",
// "premium_index": "0",
// "avg_premium_index": "0.000029587712038098",
// "interest_rate": "0.0001",
// "timestamp": "2022-03-22T08:08:26.687Z"
// }
// }
//
const data = this.safeValue (response, market['id'], {});
return this.parseFundingRate (data, market);
}
parseFundingRate (contract, market = undefined) {
//
// {
// "contract_type": "perpetual",
// "mark_price": "42307.43",
// "index_price": "42303.27",
// "funding_rate": "0.0001",
// "open_interest": "30.9826",
// "next_funding_time": "2022-03-22T16:00:00.000Z",
// "indicative_funding_rate": "0.0001",
// "premium_index": "0",
// "avg_premium_index": "0.000029587712038098",
// "interest_rate": "0.0001",
// "timestamp": "2022-03-22T08:08:26.687Z"
// }
//
const nextFundingDatetime = this.safeString (contract, 'next_funding_time');
const datetime = this.safeString (contract, 'timestamp');
return {
'info': contract,
'symbol': this.safeSymbol (undefined, market),
'markPrice': this.safeNumber (contract, 'mark_price'),
'indexPrice': this.safeNumber (contract, 'index_price'),
'interestRate': this.safeNumber (contract, 'interest_rate'),
'estimatedSettlePrice': undefined,
'timestamp': this.parse8601 (datetime),
'datetime': datetime,
'fundingRate': this.safeNumber (contract, 'funding_rate'),
'fundingTimestamp': undefined,
'fundingDatetime': undefined,
'nextFundingRate': this.safeNumber (contract, 'indicative_funding_rate'),
'nextFundingTimestamp': this.parse8601 (nextFundingDatetime),
'nextFundingDatetime': nextFundingDatetime,
'previousFundingRate': undefined,
'previousFundingTimestamp': undefined,
'previousFundingDatetime': undefined,
};
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
//
// {
// "error": {
// "code": 20001,
// "message": "Insufficient funds",
// "description": "Check that the funds are sufficient, given commissions"
// }
// }
//
// {
// "error": {
// "code": "600",
// "message": "Action not allowed"
// }
// }
//
const error = this.safeValue (response, 'error');
const errorCode = this.safeString (error, 'code');
if (errorCode !== undefined) {
const feedback = this.id + ' ' + body;
const message = this.safeString2 (error, 'message', 'description');
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
throw new ExchangeError (feedback);
}
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const query = this.omit (params, this.extractParams (path));
const implodedPath = this.implodeParams (path, params);
let url = this.urls['api'][api] + '/' + implodedPath;
let getRequest = undefined;
const keys = Object.keys (query);
const queryLength = keys.length;
headers = {
'Content-Type': 'application/json',
};
if (method === 'GET') {
if (queryLength) {
getRequest = '?' + this.urlencode (query);
url = url + getRequest;
}
} else {
body = this.json (params);
}
if (api === 'private') {
this.checkRequiredCredentials ();
const timestamp = this.nonce ().toString ();
const payload = [ method, '/api/3/' + implodedPath ];
if (method === 'GET') {
if (getRequest !== undefined) {
payload.push (getRequest);
}
} else {
payload.push (body);
}
payload.push (timestamp);
const payloadString = payload.join ('');
const signature = this.hmac (this.encode (payloadString), this.encode (this.secret), 'sha256', 'hex');
const secondPayload = this.apiKey + ':' + signature + ':' + timestamp;
const encoded = this.decode (this.stringToBase64 (secondPayload));
headers['Authorization'] = 'HS256 ' + encoded;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
};
|
Hitbtc3 fetchMyTrades
Added margin functionality to fetchMyTrades:
```
hitbtc3.fetchMyTrades ()
2022-03-24T01:52:55.193Z iteration 0 passed in 224 ms
id | order | timestamp | datetime | symbol | type | side | takerOrMaker | price | amount
| cost | fee | fees
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1655137410 | | 1648086557205 | 2022-03-24T01:49:17.205Z | BTC/USDT | | buy | taker | 42754.43 | 0.00002
| 0.8550886 | {"cost":0.0021377215,"currency":"USDT"} | [{"currency":"USDT","cost":0.0021377215}]
1 objects
```
|
js/hitbtc3.js
|
Hitbtc3 fetchMyTrades
|
<ide><path>s/hitbtc3.js
<ide> const method = this.getSupportedMapping (marketType, {
<ide> 'spot': 'privateGetSpotHistoryTrade',
<ide> 'swap': 'privateGetFuturesHistoryTrade',
<add> 'margin': 'privateGetMarginHistoryTrade',
<ide> });
<ide> const response = await this[method] (this.extend (request, query));
<ide> return this.parseTrades (response, market, since, limit);
<ide> // taker: true
<ide> // }
<ide> //
<del> // fetchMyTrades swap
<add> // fetchMyTrades swap and margin
<ide> //
<ide> // {
<ide> // "id": 4718564,
|
|
Java
|
isc
|
46a3fa85677d73a2c7b03e030b51d01533244780
| 0 |
plues/model-generator,plues/model-generator
|
package org.hibernate.usertype;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
public class SQLiteDateTimeType implements UserType {
static final String sqliteTextTimeStamp = "yyyy-MM-dd kk:mm:ss"; // e.g. 2016-04-27 15:40:18
@Override
public int[] sqlTypes() {
return new int[] { Types.TIMESTAMP };
}
@Override
public Class returnedClass() {
return java.util.Date.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return Objects.equals(x, y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return Objects.hashCode(x);
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
assert names.length == 1;
String dateStr = rs.getString(names[0]);
Date d;
try {
d = new SimpleDateFormat(sqliteTextTimeStamp).parse(dateStr.toString());
} catch (ParseException e) {
e.printStackTrace();
throw new HibernateException(e.getMessage());
} catch (NullPointerException e) {
e.printStackTrace();
throw new HibernateException(e.getMessage());
}
return d;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
try {
st.setString(index, new SimpleDateFormat(sqliteTextTimeStamp).format(value));
} catch(IllegalArgumentException e) {
e.printStackTrace();
throw new HibernateException(e.getMessage());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return ((Date) value).getTime();
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
throw new HibernateException("Currently not supported");
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
throw new HibernateException("Currently not supported");
}
}
|
src/main/java/org/hibernate/usertype/SQLiteDateTimeType.java
|
package org.hibernate.usertype;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
public class SQLiteDateTimeType implements UserType {
static final SimpleDateFormat sqliteTextTimeStamp = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); // e.g. 2016-04-27 15:40:18
@Override
public int[] sqlTypes() {
return new int[] { Types.TIMESTAMP };
}
@Override
public Class returnedClass() {
return java.util.Date.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return Objects.equals(x, y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return Objects.hashCode(x);
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
assert names.length == 1;
String dateStr = rs.getString(names[0]);
Date d;
try {
d = sqliteTextTimeStamp.parse(dateStr.toString());
} catch (ParseException e) {
e.printStackTrace();
throw new HibernateException(e.getMessage());
} catch (NullPointerException e) {
e.printStackTrace();
throw new HibernateException(e.getMessage());
}
return d;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
try {
st.setString(index, sqliteTextTimeStamp.format(value));
} catch(IllegalArgumentException e) {
e.printStackTrace();
throw new HibernateException(e.getMessage());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return ((Date) value).getTime();
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
throw new HibernateException("Currently not supported");
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
throw new HibernateException("Currently not supported");
}
}
|
FindBugs recommended changes to SQLiteDateTimeType
|
src/main/java/org/hibernate/usertype/SQLiteDateTimeType.java
|
FindBugs recommended changes to SQLiteDateTimeType
|
<ide><path>rc/main/java/org/hibernate/usertype/SQLiteDateTimeType.java
<ide> import java.util.Objects;
<ide>
<ide> public class SQLiteDateTimeType implements UserType {
<del> static final SimpleDateFormat sqliteTextTimeStamp = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); // e.g. 2016-04-27 15:40:18
<add> static final String sqliteTextTimeStamp = "yyyy-MM-dd kk:mm:ss"; // e.g. 2016-04-27 15:40:18
<ide> @Override
<ide> public int[] sqlTypes() {
<ide> return new int[] { Types.TIMESTAMP };
<ide> String dateStr = rs.getString(names[0]);
<ide> Date d;
<ide> try {
<del> d = sqliteTextTimeStamp.parse(dateStr.toString());
<add> d = new SimpleDateFormat(sqliteTextTimeStamp).parse(dateStr.toString());
<ide> } catch (ParseException e) {
<ide> e.printStackTrace();
<ide> throw new HibernateException(e.getMessage());
<ide> @Override
<ide> public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
<ide> try {
<del> st.setString(index, sqliteTextTimeStamp.format(value));
<add> st.setString(index, new SimpleDateFormat(sqliteTextTimeStamp).format(value));
<ide> } catch(IllegalArgumentException e) {
<ide> e.printStackTrace();
<ide> throw new HibernateException(e.getMessage());
|
|
Java
|
mit
|
error: pathspec 'relaxng/datatype/java/src/org/whattf/datatype/data/LanguageData.java' did not match any file(s) known to git
|
5e67587a633d047928ca897dafda142cd5bb3d23
| 1 |
sammuelyee/validator,tripu/validator,takenspc/validator,tripu/validator,sammuelyee/validator,tripu/validator,validator/validator,YOTOV-LIMITED/validator,takenspc/validator,validator/validator,sammuelyee/validator,takenspc/validator,sammuelyee/validator,takenspc/validator,tripu/validator,YOTOV-LIMITED/validator,YOTOV-LIMITED/validator,validator/validator,tripu/validator,validator/validator,takenspc/validator,sammuelyee/validator,validator/validator,YOTOV-LIMITED/validator,YOTOV-LIMITED/validator
|
package org.whattf.datatype.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
public class LanguageData {
private static final String PREFIX = "prefix: ";
private static final String SUPPRESS_SCRIPT = "suppress-script: ";
private static final String SUBTAG = "subtag: ";
private static final String TYPE = "type: ";
private BufferedReader in;
private SortedSet languageSet = new TreeSet();
private SortedSet scriptSet = new TreeSet();
private SortedSet regionSet = new TreeSet();
private SortedSet variantSet = new TreeSet();
private String[] languages = null;
private String[] scripts = null;
private String[] regions = null;
private String[] variants = null;
private int[] suppressedScriptByLanguage = null;
private String[][] prefixesByVariant = null;
public LanguageData() throws IOException {
super();
consumeRegistry();
prepareArrays();
}
private void consumeRegistry() throws IOException {
while(consumeRecord());
}
private void prepareArrays() throws IOException {
int i = 0;
scripts = new String[scriptSet.size()];
for (Iterator iter = scriptSet.iterator(); iter.hasNext();) {
String str = (String) iter.next();
scripts[i] = str.intern();
i++;
}
i = 0;
languages = new String[languageSet.size()];
suppressedScriptByLanguage = new int[languageSet.size()];
for (Iterator iter = languageSet.iterator(); iter.hasNext();) {
StringPair pair = (StringPair) iter.next();
languages[i] = pair.getMain().intern();
String suppressed = (String)pair.getOther();
if (suppressed == null) {
suppressedScriptByLanguage[i] = -1;
} else {
int index = Arrays.binarySearch(scripts, suppressed);
if (index < 0) {
throw new IOException("Malformed registry: reference to non-existent script.");
}
suppressedScriptByLanguage[i] = index;
}
i++;
}
i = 0;
regions = new String[regionSet.size()];
for (Iterator iter = regionSet.iterator(); iter.hasNext();) {
String str = (String) iter.next();
regions[i] = str.intern();
i++;
}
i = 0;
variants = new String[variantSet.size()];
prefixesByVariant = new String[variantSet.size()][];
for (Iterator iter = variantSet.iterator(); iter.hasNext();) {
StringPair pair = (StringPair) iter.next();
variants[i] = pair.getMain().intern();
SortedSet other = (SortedSet) pair.getOther();
String[] prefixArr = new String[other.size()];
int j = 0;
for (Iterator iterator = other.iterator(); iterator.hasNext();) {
String str = (String) iterator.next();
prefixArr[j] = str.intern();
j++;
}
prefixesByVariant[i] = prefixArr;
i++;
}
}
private boolean consumeRecord() throws IOException {
boolean hasMore = true;
String type = null;
String subtag = null;
String suppressScript = null;
SortedSet prefixes = new TreeSet();
String line = null;
for (;;) {
line = in.readLine();
if (line == null) {
hasMore = false;
break;
}
line = line.toLowerCase();
if ("%%".equals(line)) {
break;
} else if (line.startsWith(TYPE)) {
type = line.substring(TYPE.length()).trim();
} else if (line.startsWith(SUBTAG)) {
subtag = line.substring(SUBTAG.length()).trim();
} else if (line.startsWith(SUPPRESS_SCRIPT)) {
suppressScript = line.substring(SUPPRESS_SCRIPT.length()).trim();
} else if (line.startsWith(PREFIX)) {
prefixes.add(line.substring(PREFIX.length()).trim());
}
}
if (subtag == null) {
return hasMore;
}
if ("language".equals(type)) {
languageSet.add(new StringPair(subtag, suppressScript));
} else if ("region".equals(type)) {
regionSet.add(subtag);
} else if ("script".equals(type)) {
scriptSet.add(subtag);
} else if ("variant".equals(type)) {
variantSet.add(new StringPair(subtag, prefixes));
}
return hasMore;
}
private class StringPair implements Comparable{
private String main;
private Object other;
/**
* Returns the main.
*
* @return the main
*/
public String getMain() {
return main;
}
/**
* Returns the other.
*
* @return the other
*/
public Object getOther() {
return other;
}
/**
* @param main
* @param other
*/
public StringPair(String main, Object other) {
this.main = main;
this.other = other;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object arg0) {
return main.equals(((StringPair)arg0).main);
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return main.hashCode();
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object arg0) {
return main.compareTo(((StringPair)arg0).main);
}
}
}
|
relaxng/datatype/java/src/org/whattf/datatype/data/LanguageData.java
|
Incomplete draft code for reading IANA language registry data
--HG--
extra : convert_revision : svn%3Ae7398766-c432-0410-9565-638d39ca0058/trunk%40115
|
relaxng/datatype/java/src/org/whattf/datatype/data/LanguageData.java
|
Incomplete draft code for reading IANA language registry data
|
<ide><path>elaxng/datatype/java/src/org/whattf/datatype/data/LanguageData.java
<add>package org.whattf.datatype.data;
<add>
<add>import java.io.BufferedReader;
<add>import java.io.IOException;
<add>import java.util.Arrays;
<add>import java.util.Iterator;
<add>import java.util.SortedSet;
<add>import java.util.TreeSet;
<add>
<add>public class LanguageData {
<add>
<add> private static final String PREFIX = "prefix: ";
<add>
<add> private static final String SUPPRESS_SCRIPT = "suppress-script: ";
<add>
<add> private static final String SUBTAG = "subtag: ";
<add>
<add> private static final String TYPE = "type: ";
<add>
<add> private BufferedReader in;
<add>
<add> private SortedSet languageSet = new TreeSet();
<add>
<add> private SortedSet scriptSet = new TreeSet();
<add>
<add> private SortedSet regionSet = new TreeSet();
<add>
<add> private SortedSet variantSet = new TreeSet();
<add>
<add> private String[] languages = null;
<add>
<add> private String[] scripts = null;
<add>
<add> private String[] regions = null;
<add>
<add> private String[] variants = null;
<add>
<add> private int[] suppressedScriptByLanguage = null;
<add>
<add> private String[][] prefixesByVariant = null;
<add>
<add> public LanguageData() throws IOException {
<add> super();
<add> consumeRegistry();
<add> prepareArrays();
<add> }
<add>
<add> private void consumeRegistry() throws IOException {
<add> while(consumeRecord());
<add> }
<add>
<add> private void prepareArrays() throws IOException {
<add> int i = 0;
<add> scripts = new String[scriptSet.size()];
<add> for (Iterator iter = scriptSet.iterator(); iter.hasNext();) {
<add> String str = (String) iter.next();
<add> scripts[i] = str.intern();
<add> i++;
<add> }
<add>
<add> i = 0;
<add> languages = new String[languageSet.size()];
<add> suppressedScriptByLanguage = new int[languageSet.size()];
<add> for (Iterator iter = languageSet.iterator(); iter.hasNext();) {
<add> StringPair pair = (StringPair) iter.next();
<add> languages[i] = pair.getMain().intern();
<add> String suppressed = (String)pair.getOther();
<add> if (suppressed == null) {
<add> suppressedScriptByLanguage[i] = -1;
<add> } else {
<add> int index = Arrays.binarySearch(scripts, suppressed);
<add> if (index < 0) {
<add> throw new IOException("Malformed registry: reference to non-existent script.");
<add> }
<add> suppressedScriptByLanguage[i] = index;
<add> }
<add> i++;
<add> }
<add>
<add> i = 0;
<add> regions = new String[regionSet.size()];
<add> for (Iterator iter = regionSet.iterator(); iter.hasNext();) {
<add> String str = (String) iter.next();
<add> regions[i] = str.intern();
<add> i++;
<add> }
<add>
<add> i = 0;
<add> variants = new String[variantSet.size()];
<add> prefixesByVariant = new String[variantSet.size()][];
<add> for (Iterator iter = variantSet.iterator(); iter.hasNext();) {
<add> StringPair pair = (StringPair) iter.next();
<add> variants[i] = pair.getMain().intern();
<add> SortedSet other = (SortedSet) pair.getOther();
<add> String[] prefixArr = new String[other.size()];
<add> int j = 0;
<add> for (Iterator iterator = other.iterator(); iterator.hasNext();) {
<add> String str = (String) iterator.next();
<add> prefixArr[j] = str.intern();
<add> j++;
<add> }
<add> prefixesByVariant[i] = prefixArr;
<add> i++;
<add> }
<add> }
<add>
<add> private boolean consumeRecord() throws IOException {
<add> boolean hasMore = true;
<add> String type = null;
<add> String subtag = null;
<add> String suppressScript = null;
<add> SortedSet prefixes = new TreeSet();
<add> String line = null;
<add> for (;;) {
<add> line = in.readLine();
<add> if (line == null) {
<add> hasMore = false;
<add> break;
<add> }
<add> line = line.toLowerCase();
<add> if ("%%".equals(line)) {
<add> break;
<add> } else if (line.startsWith(TYPE)) {
<add> type = line.substring(TYPE.length()).trim();
<add> } else if (line.startsWith(SUBTAG)) {
<add> subtag = line.substring(SUBTAG.length()).trim();
<add> } else if (line.startsWith(SUPPRESS_SCRIPT)) {
<add> suppressScript = line.substring(SUPPRESS_SCRIPT.length()).trim();
<add> } else if (line.startsWith(PREFIX)) {
<add> prefixes.add(line.substring(PREFIX.length()).trim());
<add> }
<add> }
<add> if (subtag == null) {
<add> return hasMore;
<add> }
<add> if ("language".equals(type)) {
<add> languageSet.add(new StringPair(subtag, suppressScript));
<add> } else if ("region".equals(type)) {
<add> regionSet.add(subtag);
<add> } else if ("script".equals(type)) {
<add> scriptSet.add(subtag);
<add> } else if ("variant".equals(type)) {
<add> variantSet.add(new StringPair(subtag, prefixes));
<add> }
<add> return hasMore;
<add> }
<add>
<add> private class StringPair implements Comparable{
<add>
<add> private String main;
<add>
<add> private Object other;
<add>
<add> /**
<add> * Returns the main.
<add> *
<add> * @return the main
<add> */
<add> public String getMain() {
<add> return main;
<add> }
<add>
<add> /**
<add> * Returns the other.
<add> *
<add> * @return the other
<add> */
<add> public Object getOther() {
<add> return other;
<add> }
<add>
<add> /**
<add> * @param main
<add> * @param other
<add> */
<add> public StringPair(String main, Object other) {
<add> this.main = main;
<add> this.other = other;
<add> }
<add>
<add> /**
<add> * @see java.lang.Object#equals(java.lang.Object)
<add> */
<add> public boolean equals(Object arg0) {
<add> return main.equals(((StringPair)arg0).main);
<add> }
<add>
<add> /**
<add> * @see java.lang.Object#hashCode()
<add> */
<add> public int hashCode() {
<add> return main.hashCode();
<add> }
<add>
<add> /**
<add> * @see java.lang.Comparable#compareTo(java.lang.Object)
<add> */
<add> public int compareTo(Object arg0) {
<add> return main.compareTo(((StringPair)arg0).main);
<add> }
<add> }
<add>}
|
|
Java
|
apache-2.0
|
9e193b62bc9c25044da1563b58f4deea48195152
| 0 |
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
|
package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DocumentStoredFieldVisitor;
import org.apache.lucene.index.codecs.PerDocValues;
import org.apache.lucene.index.values.IndexDocValues;
import org.apache.lucene.search.FieldCache; // javadocs
import org.apache.lucene.search.SearcherManager; // javadocs
import org.apache.lucene.store.*;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.ReaderUtil; // for javadocs
/** IndexReader is an abstract class, providing an interface for accessing an
index. Search of an index is done entirely through this abstract interface,
so that any subclass which implements it is searchable.
<p> Concrete subclasses of IndexReader are usually constructed with a call to
one of the static <code>open()</code> methods, e.g. {@link
#open(Directory)}.
<p> For efficiency, in this API documents are often referred to via
<i>document numbers</i>, non-negative integers which each name a unique
document in the index. These document numbers are ephemeral--they may change
as documents are added to and deleted from an index. Clients should thus not
rely on a given document having the same number between sessions.
<p>
<b>NOTE</b>: for backwards API compatibility, several methods are not listed
as abstract, but have no useful implementations in this base class and
instead always throw UnsupportedOperationException. Subclasses are
strongly encouraged to override these methods, but in many cases may not
need to.
</p>
<p>
<a name="thread-safety"></a><p><b>NOTE</b>: {@link
IndexReader} instances are completely thread
safe, meaning multiple threads can call any of its methods,
concurrently. If your application requires external
synchronization, you should <b>not</b> synchronize on the
<code>IndexReader</code> instance; use your own
(non-Lucene) objects instead.
*/
public abstract class IndexReader implements Cloneable,Closeable {
/**
* A custom listener that's invoked when the IndexReader
* is finished.
*
* <p>For a SegmentReader, this listener is called only
* once all SegmentReaders sharing the same core are
* closed. At this point it is safe for apps to evict
* this reader from any caches keyed on {@link
* #getCoreCacheKey}. This is the same interface that
* {@link FieldCache} uses, internally, to evict
* entries.</p>
*
* <p>For other readers, this listener is called when they
* are closed.</p>
*
* @lucene.experimental
*/
public static interface ReaderFinishedListener {
public void finished(IndexReader reader);
}
// Impls must set this if they may call add/removeReaderFinishedListener:
protected volatile Collection<ReaderFinishedListener> readerFinishedListeners;
/** Expert: adds a {@link ReaderFinishedListener}. The
* provided listener is also added to any sub-readers, if
* this is a composite reader. Also, any reader reopened
* or cloned from this one will also copy the listeners at
* the time of reopen.
*
* @lucene.experimental */
public void addReaderFinishedListener(ReaderFinishedListener listener) {
ensureOpen();
readerFinishedListeners.add(listener);
}
/** Expert: remove a previously added {@link ReaderFinishedListener}.
*
* @lucene.experimental */
public void removeReaderFinishedListener(ReaderFinishedListener listener) {
ensureOpen();
readerFinishedListeners.remove(listener);
}
protected void notifyReaderFinishedListeners() {
// Defensive (should never be null -- all impls must set
// this):
if (readerFinishedListeners != null) {
for(ReaderFinishedListener listener : readerFinishedListeners) {
listener.finished(this);
}
}
}
protected void readerFinished() {
notifyReaderFinishedListeners();
}
/**
* Constants describing field properties, for example used for
* {@link IndexReader#getFieldNames(FieldOption)}.
*/
public static enum FieldOption {
/** All fields */
ALL,
/** All indexed fields */
INDEXED,
/** All fields that store payloads */
STORES_PAYLOADS,
/** All fields that omit tf */
OMIT_TERM_FREQ_AND_POSITIONS,
/** All fields that omit positions */
OMIT_POSITIONS,
/** All fields which are not indexed */
UNINDEXED,
/** All fields which are indexed with termvectors enabled */
INDEXED_WITH_TERMVECTOR,
/** All fields which are indexed but don't have termvectors enabled */
INDEXED_NO_TERMVECTOR,
/** All fields with termvectors enabled. Please note that only standard termvector fields are returned */
TERMVECTOR,
/** All fields with termvectors with position values enabled */
TERMVECTOR_WITH_POSITION,
/** All fields with termvectors with offset values enabled */
TERMVECTOR_WITH_OFFSET,
/** All fields with termvectors with offset values and position values enabled */
TERMVECTOR_WITH_POSITION_OFFSET,
/** All fields holding doc values */
DOC_VALUES
}
private volatile boolean closed;
private final AtomicInteger refCount = new AtomicInteger();
static int DEFAULT_TERMS_INDEX_DIVISOR = 1;
/** Expert: returns the current refCount for this reader */
public final int getRefCount() {
return refCount.get();
}
/**
* Expert: increments the refCount of this IndexReader
* instance. RefCounts are used to determine when a
* reader can be closed safely, i.e. as soon as there are
* no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause;
* otherwise the reader may never be closed. Note that
* {@link #close} simply calls decRef(), which means that
* the IndexReader will not really be closed until {@link
* #decRef} has been called for all outstanding
* references.
*
* @see #decRef
* @see #tryIncRef
*/
public final void incRef() {
ensureOpen();
refCount.incrementAndGet();
}
/**
* Expert: increments the refCount of this IndexReader
* instance only if the IndexReader has not been closed yet
* and returns <code>true</code> iff the refCount was
* successfully incremented, otherwise <code>false</code>.
* If this method returns <code>false</code> the reader is either
* already closed or is currently been closed. Either way this
* reader instance shouldn't be used by an application unless
* <code>true</code> is returned.
* <p>
* RefCounts are used to determine when a
* reader can be closed safely, i.e. as soon as there are
* no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause;
* otherwise the reader may never be closed. Note that
* {@link #close} simply calls decRef(), which means that
* the IndexReader will not really be closed until {@link
* #decRef} has been called for all outstanding
* references.
*
* @see #decRef
* @see #incRef
*/
public final boolean tryIncRef() {
int count;
while ((count = refCount.get()) > 0) {
if (refCount.compareAndSet(count, count+1)) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append(getClass().getSimpleName());
buffer.append('(');
final IndexReader[] subReaders = getSequentialSubReaders();
if ((subReaders != null) && (subReaders.length > 0)) {
buffer.append(subReaders[0]);
for (int i = 1; i < subReaders.length; ++i) {
buffer.append(" ").append(subReaders[i]);
}
}
buffer.append(')');
return buffer.toString();
}
/**
* Expert: decreases the refCount of this IndexReader
* instance. If the refCount drops to 0, then pending
* changes (if any) are committed to the index and this
* reader is closed. If an exception is hit, the refCount
* is unchanged.
*
* @throws IOException in case an IOException occurs in commit() or doClose()
*
* @see #incRef
*/
public final void decRef() throws IOException {
ensureOpen();
final int rc = refCount.decrementAndGet();
if (rc == 0) {
boolean success = false;
try {
doClose();
success = true;
} finally {
if (!success) {
// Put reference back on failure
refCount.incrementAndGet();
}
}
readerFinished();
} else if (rc < 0) {
throw new IllegalStateException("too many decRef calls: refCount is " + rc + " after decrement");
}
}
protected IndexReader() {
refCount.set(1);
}
/**
* @throws AlreadyClosedException if this IndexReader is closed
*/
protected final void ensureOpen() throws AlreadyClosedException {
if (refCount.get() <= 0) {
throw new AlreadyClosedException("this IndexReader is closed");
}
}
/** Returns a IndexReader reading the index in the given
* Directory
* @param directory the index directory
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final Directory directory) throws CorruptIndexException, IOException {
return DirectoryReader.open(directory, null, DEFAULT_TERMS_INDEX_DIVISOR);
}
/** Expert: Returns a IndexReader reading the index in the given
* Directory with the given termInfosIndexDivisor.
* @param directory the index directory
* @param termInfosIndexDivisor Subsamples which indexed
* terms are loaded into RAM. This has the same effect as {@link
* IndexWriterConfig#setTermIndexInterval} except that setting
* must be done at indexing time while this setting can be
* set per reader. When set to N, then one in every
* N*termIndexInterval terms in the index is loaded into
* memory. By setting this to a value > 1 you can reduce
* memory usage, at the expense of higher latency when
* loading a TermInfo. The default value is 1. Set this
* to -1 to skip loading the terms index entirely.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final Directory directory, int termInfosIndexDivisor) throws CorruptIndexException, IOException {
return DirectoryReader.open(directory, null, termInfosIndexDivisor);
}
/**
* Open a near real time IndexReader from the {@link org.apache.lucene.index.IndexWriter}.
*
* @param writer The IndexWriter to open from
* @param applyAllDeletes If true, all buffered deletes will
* be applied (made visible) in the returned reader. If
* false, the deletes are not applied but remain buffered
* (in IndexWriter) so that they will be applied in the
* future. Applying deletes can be costly, so if your app
* can tolerate deleted documents being returned you might
* gain some performance by passing false.
* @return The new IndexReader
* @throws CorruptIndexException
* @throws IOException if there is a low-level IO error
*
* @see #openIfChanged(IndexReader,IndexWriter,boolean)
*
* @lucene.experimental
*/
public static IndexReader open(final IndexWriter writer, boolean applyAllDeletes) throws CorruptIndexException, IOException {
return writer.getReader(applyAllDeletes);
}
/** Expert: returns an IndexReader reading the index in the given
* {@link IndexCommit}.
* @param commit the commit point to open
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final IndexCommit commit) throws CorruptIndexException, IOException {
return DirectoryReader.open(commit.getDirectory(), commit, DEFAULT_TERMS_INDEX_DIVISOR);
}
/** Expert: returns an IndexReader reading the index in the given
* {@link IndexCommit} and termInfosIndexDivisor.
* @param commit the commit point to open
* @param termInfosIndexDivisor Subsamples which indexed
* terms are loaded into RAM. This has the same effect as {@link
* IndexWriterConfig#setTermIndexInterval} except that setting
* must be done at indexing time while this setting can be
* set per reader. When set to N, then one in every
* N*termIndexInterval terms in the index is loaded into
* memory. By setting this to a value > 1 you can reduce
* memory usage, at the expense of higher latency when
* loading a TermInfo. The default value is 1. Set this
* to -1 to skip loading the terms index entirely.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final IndexCommit commit, int termInfosIndexDivisor) throws CorruptIndexException, IOException {
return DirectoryReader.open(commit.getDirectory(), commit, termInfosIndexDivisor);
}
/**
* If the index has changed since the provided reader was
* opened, open and return a new reader; else, return
* null. The new reader, if not null, will be the same
* type of reader as the previous one, ie an NRT reader
* will open a new NRT reader, a MultiReader will open a
* new MultiReader, etc.
*
* <p>This method is typically far less costly than opening a
* fully new <code>IndexReader</code> as it shares
* resources (for example sub-readers) with the provided
* <code>IndexReader</code>, when possible.
*
* <p>The provided reader is not closed (you are responsible
* for doing so); if a new reader is returned you also
* must eventually close it. Be sure to never close a
* reader while other threads are still using it; see
* {@link SearcherManager} to simplify managing this.
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
* @return null if there are no changes; else, a new
* IndexReader instance which you must eventually close
*/
public static IndexReader openIfChanged(IndexReader oldReader) throws IOException {
final IndexReader newReader = oldReader.doOpenIfChanged();
assert newReader != oldReader;
return newReader;
}
/**
* If the IndexCommit differs from what the
* provided reader is searching, open and return a new
* reader; else, return null.
*
* @see #openIfChanged(IndexReader)
*/
public static IndexReader openIfChanged(IndexReader oldReader, IndexCommit commit) throws IOException {
final IndexReader newReader = oldReader.doOpenIfChanged(commit);
assert newReader != oldReader;
return newReader;
}
/**
* Expert: If there changes (committed or not) in the
* {@link IndexWriter} versus what the provided reader is
* searching, then open and return a new
* IndexReader searching both committed and uncommitted
* changes from the writer; else, return null (though, the
* current implementation never returns null).
*
* <p>This provides "near real-time" searching, in that
* changes made during an {@link IndexWriter} session can be
* quickly made available for searching without closing
* the writer nor calling {@link IndexWriter#commit}.
*
* <p>It's <i>near</i> real-time because there is no hard
* guarantee on how quickly you can get a new reader after
* making changes with IndexWriter. You'll have to
* experiment in your situation to determine if it's
* fast enough. As this is a new and experimental
* feature, please report back on your findings so we can
* learn, improve and iterate.</p>
*
* <p>The very first time this method is called, this
* writer instance will make every effort to pool the
* readers that it opens for doing merges, applying
* deletes, etc. This means additional resources (RAM,
* file descriptors, CPU time) will be consumed.</p>
*
* <p>For lower latency on reopening a reader, you should
* call {@link IndexWriterConfig#setMergedSegmentWarmer} to
* pre-warm a newly merged segment before it's committed
* to the index. This is important for minimizing
* index-to-search delay after a large merge. </p>
*
* <p>If an addIndexes* call is running in another thread,
* then this reader will only search those segments from
* the foreign index that have been successfully copied
* over, so far.</p>
*
* <p><b>NOTE</b>: Once the writer is closed, any
* outstanding readers may continue to be used. However,
* if you attempt to reopen any of those readers, you'll
* hit an {@link AlreadyClosedException}.</p>
*
* @return IndexReader that covers entire index plus all
* changes made so far by this IndexWriter instance, or
* null if there are no new changes
*
* @param writer The IndexWriter to open from
*
* @param applyAllDeletes If true, all buffered deletes will
* be applied (made visible) in the returned reader. If
* false, the deletes are not applied but remain buffered
* (in IndexWriter) so that they will be applied in the
* future. Applying deletes can be costly, so if your app
* can tolerate deleted documents being returned you might
* gain some performance by passing false.
*
* @throws IOException
*
* @lucene.experimental
*/
public static IndexReader openIfChanged(IndexReader oldReader, IndexWriter writer, boolean applyAllDeletes) throws IOException {
final IndexReader newReader = oldReader.doOpenIfChanged(writer, applyAllDeletes);
assert newReader != oldReader;
return newReader;
}
/**
* If the index has changed since it was opened, open and return a new reader;
* else, return {@code null}.
*
* @see #openIfChanged(IndexReader)
*/
protected IndexReader doOpenIfChanged() throws CorruptIndexException, IOException {
throw new UnsupportedOperationException("This reader does not support reopen().");
}
/**
* If the index has changed since it was opened, open and return a new reader;
* else, return {@code null}.
*
* @see #openIfChanged(IndexReader, IndexCommit)
*/
protected IndexReader doOpenIfChanged(final IndexCommit commit) throws CorruptIndexException, IOException {
throw new UnsupportedOperationException("This reader does not support reopen(IndexCommit).");
}
/**
* If the index has changed since it was opened, open and return a new reader;
* else, return {@code null}.
*
* @see #openIfChanged(IndexReader, IndexWriter, boolean)
*/
protected IndexReader doOpenIfChanged(IndexWriter writer, boolean applyAllDeletes) throws CorruptIndexException, IOException {
return writer.getReader(applyAllDeletes);
}
/**
* Efficiently clones the IndexReader (sharing most
* internal state).
*/
@Override
public synchronized Object clone() {
throw new UnsupportedOperationException("This reader does not implement clone()");
}
/**
* Returns the directory associated with this index. The Default
* implementation returns the directory specified by subclasses when
* delegating to the IndexReader(Directory) constructor, or throws an
* UnsupportedOperationException if one was not specified.
* @throws UnsupportedOperationException if no directory
*/
public Directory directory() {
ensureOpen();
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Returns the time the index in the named directory was last modified.
* Do not use this to check whether the reader is still up-to-date, use
* {@link #isCurrent()} instead.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static long lastModified(final Directory directory2) throws CorruptIndexException, IOException {
return ((Long) new SegmentInfos.FindSegmentsFile(directory2) {
@Override
public Object doBody(String segmentFileName) throws IOException {
return Long.valueOf(directory2.fileModified(segmentFileName));
}
}.run()).longValue();
}
/**
* Reads version number from segments files. The version number is
* initialized with a timestamp and then increased by one for each change of
* the index.
*
* @param directory where the index resides.
* @return version number.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static long getCurrentVersion(Directory directory) throws CorruptIndexException, IOException {
return SegmentInfos.readCurrentVersion(directory);
}
/**
* Reads commitUserData, previously passed to {@link
* IndexWriter#commit(Map)}, from current index
* segments file. This will return null if {@link
* IndexWriter#commit(Map)} has never been called for
* this index.
*
* @param directory where the index resides.
* @return commit userData.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*
* @see #getCommitUserData()
*/
public static Map<String, String> getCommitUserData(Directory directory) throws CorruptIndexException, IOException {
return SegmentInfos.readCurrentUserData(directory);
}
/**
* Version number when this IndexReader was opened. Not
* implemented in the IndexReader base class.
*
* <p>If this reader is based on a Directory (ie, was
* created by calling {@link #open}, or {@link #openIfChanged} on
* a reader based on a Directory), then this method
* returns the version recorded in the commit that the
* reader opened. This version is advanced every time
* {@link IndexWriter#commit} is called.</p>
*
* <p>If instead this reader is a near real-time reader
* (ie, obtained by a call to {@link
* IndexWriter#getReader}, or by calling {@link #openIfChanged}
* on a near real-time reader), then this method returns
* the version of the last commit done by the writer.
* Note that even as further changes are made with the
* writer, the version will not changed until a commit is
* completed. Thus, you should not rely on this method to
* determine when a near real-time reader should be
* opened. Use {@link #isCurrent} instead.</p>
*
* @throws UnsupportedOperationException unless overridden in subclass
*/
public long getVersion() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Retrieve the String userData optionally passed to
* IndexWriter#commit. This will return null if {@link
* IndexWriter#commit(Map)} has never been called for
* this index.
*
* @see #getCommitUserData(Directory)
*/
public Map<String,String> getCommitUserData() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Check whether any new changes have occurred to the
* index since this reader was opened.
*
* <p>If this reader is based on a Directory (ie, was
* created by calling {@link #open}, or {@link #openIfChanged} on
* a reader based on a Directory), then this method checks
* if any further commits (see {@link IndexWriter#commit}
* have occurred in that directory).</p>
*
* <p>If instead this reader is a near real-time reader
* (ie, obtained by a call to {@link
* IndexWriter#getReader}, or by calling {@link #openIfChanged}
* on a near real-time reader), then this method checks if
* either a new commit has occurred, or any new
* uncommitted changes have taken place via the writer.
* Note that even if the writer has only performed
* merging, this method will still return false.</p>
*
* <p>In any event, if this returns false, you should call
* {@link #openIfChanged} to get a new reader that sees the
* changes.</p>
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
* @throws UnsupportedOperationException unless overridden in subclass
*/
public boolean isCurrent() throws CorruptIndexException, IOException {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/** Retrieve term vectors for this document, or null if
* term vectors were not indexed. The returned Fields
* instance acts like a single-document inverted index
* (the docID will be 0). */
public abstract Fields getTermVectors(int docID)
throws IOException;
/** Retrieve term vector for this document and field, or
* null if term vectors were not indexed. The returned
* Fields instance acts like a single-document inverted
* index (the docID will be 0). */
public final Terms getTermVector(int docID, String field)
throws IOException {
Fields vectors = getTermVectors(docID);
if (vectors == null) {
return null;
}
return vectors.terms(field);
}
/**
* Returns <code>true</code> if an index exists at the specified directory.
* @param directory the directory to check for an index
* @return <code>true</code> if an index exists; <code>false</code> otherwise
* @throws IOException if there is a problem with accessing the index
*/
public static boolean indexExists(Directory directory) throws IOException {
try {
new SegmentInfos().read(directory);
return true;
} catch (IOException ioe) {
return false;
}
}
/** Returns the number of documents in this index. */
public abstract int numDocs();
/** Returns one greater than the largest possible document number.
* This may be used to, e.g., determine how big to allocate an array which
* will have an element for every document number in an index.
*/
public abstract int maxDoc();
/** Returns the number of deleted documents. */
public final int numDeletedDocs() {
return maxDoc() - numDocs();
}
/** Expert: visits the fields of a stored document, for
* custom processing/loading of each field. If you
* simply want to load all fields, use {@link
* #document(int)}. If you want to load a subset, use
* {@link DocumentStoredFieldVisitor}. */
public abstract void document(int docID, StoredFieldVisitor visitor) throws CorruptIndexException, IOException;
/**
* Returns the stored fields of the <code>n</code><sup>th</sup>
* <code>Document</code> in this index. This is just
* sugar for using {@link DocumentStoredFieldVisitor}.
* <p>
* <b>NOTE:</b> for performance reasons, this method does not check if the
* requested document is deleted, and therefore asking for a deleted document
* may yield unspecified results. Usually this is not required, however you
* can test if the doc is deleted by checking the {@link
* Bits} returned from {@link MultiFields#getLiveDocs}.
*
* <b>NOTE:</b> only the content of a field is returned,
* if that field was stored during indexing. Metadata
* like boost, omitNorm, IndexOptions, tokenized, etc.,
* are not preserved.
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
// TODO: we need a separate StoredField, so that the
// Document returned here contains that class not
// IndexableField
public final Document document(int docID) throws CorruptIndexException, IOException {
ensureOpen();
final DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor();
document(docID, visitor);
return visitor.getDocument();
}
/** Returns true if any documents have been deleted */
public abstract boolean hasDeletions();
/** Returns true if there are norms stored for this field. */
public boolean hasNorms(String field) throws IOException {
// backward compatible implementation.
// SegmentReader has an efficient implementation.
ensureOpen();
return norms(field) != null;
}
/** Returns the byte-encoded normalization factor for the named field of
* every document. This is used by the search code to score documents.
* Returns null if norms were not indexed for this field.
*
* @see org.apache.lucene.document.Field#setBoost(float)
*/
public abstract byte[] norms(String field) throws IOException;
/**
* Returns {@link Fields} for this reader.
* This method may return null if the reader has no
* postings.
*
* <p><b>NOTE</b>: if this is a multi reader ({@link
* #getSequentialSubReaders} is not null) then this
* method will throw UnsupportedOperationException. If
* you really need a {@link Fields} for such a reader,
* use {@link MultiFields#getFields}. However, for
* performance reasons, it's best to get all sub-readers
* using {@link ReaderUtil#gatherSubReaders} and iterate
* through them yourself. */
public abstract Fields fields() throws IOException;
/**
* Returns {@link PerDocValues} for this reader.
* This method may return null if the reader has no per-document
* values stored.
*
* <p><b>NOTE</b>: if this is a multi reader ({@link
* #getSequentialSubReaders} is not null) then this
* method will throw UnsupportedOperationException. If
* you really need {@link PerDocValues} for such a reader,
* use {@link MultiPerDocValues#getPerDocs(IndexReader)}. However, for
* performance reasons, it's best to get all sub-readers
* using {@link ReaderUtil#gatherSubReaders} and iterate
* through them yourself. */
public abstract PerDocValues perDocValues() throws IOException;
public final int docFreq(Term term) throws IOException {
return docFreq(term.field(), term.bytes());
}
/** Returns the number of documents containing the term
* <code>t</code>. This method returns 0 if the term or
* field does not exists. This method does not take into
* account deleted documents that have not yet been merged
* away. */
public int docFreq(String field, BytesRef term) throws IOException {
final Fields fields = fields();
if (fields == null) {
return 0;
}
final Terms terms = fields.terms(field);
if (terms == null) {
return 0;
}
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.docFreq();
} else {
return 0;
}
}
/** Returns the number of documents containing the term
* <code>t</code>. This method returns 0 if the term or
* field does not exists. This method does not take into
* account deleted documents that have not yet been merged
* away. */
public final long totalTermFreq(String field, BytesRef term) throws IOException {
final Fields fields = fields();
if (fields == null) {
return 0;
}
final Terms terms = fields.terms(field);
if (terms == null) {
return 0;
}
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.totalTermFreq();
} else {
return 0;
}
}
/** This may return null if the field does not exist.*/
public final Terms terms(String field) throws IOException {
final Fields fields = fields();
if (fields == null) {
return null;
}
return fields.terms(field);
}
/** Returns {@link DocsEnum} for the specified field &
* term. This may return null, if either the field or
* term does not exist. */
public final DocsEnum termDocsEnum(Bits liveDocs, String field, BytesRef term, boolean needsFreqs) throws IOException {
assert field != null;
assert term != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.docs(liveDocs, null, needsFreqs);
}
}
}
return null;
}
/** Returns {@link DocsAndPositionsEnum} for the specified
* field & term. This may return null, if either the
* field or term does not exist, or, positions were not
* indexed for this field. */
public final DocsAndPositionsEnum termPositionsEnum(Bits liveDocs, String field, BytesRef term) throws IOException {
assert field != null;
assert term != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.docsAndPositions(liveDocs, null);
}
}
}
return null;
}
/**
* Returns {@link DocsEnum} for the specified field and
* {@link TermState}. This may return null, if either the field or the term
* does not exists or the {@link TermState} is invalid for the underlying
* implementation.*/
public final DocsEnum termDocsEnum(Bits liveDocs, String field, BytesRef term, TermState state, boolean needsFreqs) throws IOException {
assert state != null;
assert field != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
termsEnum.seekExact(term, state);
return termsEnum.docs(liveDocs, null, needsFreqs);
}
}
return null;
}
/**
* Returns {@link DocsAndPositionsEnum} for the specified field and
* {@link TermState}. This may return null, if either the field or the term
* does not exists, the {@link TermState} is invalid for the underlying
* implementation, or positions were not indexed for this field. */
public final DocsAndPositionsEnum termPositionsEnum(Bits liveDocs, String field, BytesRef term, TermState state) throws IOException {
assert state != null;
assert field != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
termsEnum.seekExact(term, state);
return termsEnum.docsAndPositions(liveDocs, null);
}
}
return null;
}
/**
* Closes files associated with this index.
* Also saves any new deletions to disk.
* No other methods should be called after this has been called.
* @throws IOException if there is a low-level IO error
*/
public final synchronized void close() throws IOException {
if (!closed) {
decRef();
closed = true;
}
}
/** Implements close. */
protected abstract void doClose() throws IOException;
/**
* Get a list of unique field names that exist in this index and have the specified
* field option information.
* @param fldOption specifies which field option should be available for the returned fields
* @return Collection of Strings indicating the names of the fields.
* @see IndexReader.FieldOption
*/
public abstract Collection<String> getFieldNames(FieldOption fldOption);
/** Returns the {@link Bits} representing live (not
* deleted) docs. A set bit indicates the doc ID has not
* been deleted. If this method returns null it means
* there are no deleted documents (all documents are
* live).
*
* The returned instance has been safely published for
* use by multiple threads without additional
* synchronization.
* @lucene.experimental */
public abstract Bits getLiveDocs();
/**
* Expert: return the IndexCommit that this reader has
* opened. This method is only implemented by those
* readers that correspond to a Directory with its own
* segments_N file.
*
* @lucene.experimental
*/
public IndexCommit getIndexCommit() throws IOException {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Prints the filename and size of each file within a given compound file.
* Add the -extract flag to extract files to the current working directory.
* In order to make the extracted version of the index work, you have to copy
* the segments file from the compound index into the directory where the extracted files are stored.
* @param args Usage: org.apache.lucene.index.IndexReader [-extract] <cfsfile>
*/
public static void main(String [] args) {
String filename = null;
boolean extract = false;
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-extract")) {
extract = true;
} else if (filename == null) {
filename = args[i];
}
}
if (filename == null) {
System.out.println("Usage: org.apache.lucene.index.IndexReader [-extract] <cfsfile>");
return;
}
Directory dir = null;
CompoundFileDirectory cfr = null;
IOContext context = IOContext.READ;
try {
File file = new File(filename);
String dirname = file.getAbsoluteFile().getParent();
filename = file.getName();
dir = FSDirectory.open(new File(dirname));
cfr = new CompoundFileDirectory(dir, filename, IOContext.DEFAULT, false);
String [] files = cfr.listAll();
ArrayUtil.mergeSort(files); // sort the array of filename so that the output is more readable
for (int i = 0; i < files.length; ++i) {
long len = cfr.fileLength(files[i]);
if (extract) {
System.out.println("extract " + files[i] + " with " + len + " bytes to local directory...");
IndexInput ii = cfr.openInput(files[i], context);
FileOutputStream f = new FileOutputStream(files[i]);
// read and write with a small buffer, which is more effective than reading byte by byte
byte[] buffer = new byte[1024];
int chunk = buffer.length;
while(len > 0) {
final int bufLen = (int) Math.min(chunk, len);
ii.readBytes(buffer, 0, bufLen);
f.write(buffer, 0, bufLen);
len -= bufLen;
}
f.close();
ii.close();
}
else
System.out.println(files[i] + ": " + len + " bytes");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (dir != null)
dir.close();
if (cfr != null)
cfr.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/** Returns all commit points that exist in the Directory.
* Normally, because the default is {@link
* KeepOnlyLastCommitDeletionPolicy}, there would be only
* one commit point. But if you're using a custom {@link
* IndexDeletionPolicy} then there could be many commits.
* Once you have a given commit, you can open a reader on
* it by calling {@link IndexReader#open(IndexCommit)}
* There must be at least one commit in
* the Directory, else this method throws {@link
* IndexNotFoundException}. Note that if a commit is in
* progress while this method is running, that commit
* may or may not be returned.
*
* @return a sorted list of {@link IndexCommit}s, from oldest
* to latest. */
public static List<IndexCommit> listCommits(Directory dir) throws IOException {
return DirectoryReader.listCommits(dir);
}
/** Expert: returns the sequential sub readers that this
* reader is logically composed of. If this reader is not composed
* of sequential child readers, it should return null.
* If this method returns an empty array, that means this
* reader is a null reader (for example a MultiReader
* that has no sub readers).
* <p>
* NOTE: You should not try using sub-readers returned by
* this method to make any changes (deleteDocument,
* etc.). While this might succeed for one composite reader
* (like MultiReader), it will most likely lead to index
* corruption for other readers (like DirectoryReader obtained
* through {@link #open}. Use the parent reader directly. */
public IndexReader[] getSequentialSubReaders() {
ensureOpen();
return null;
}
/**
* Expert: Returns a the root {@link ReaderContext} for this
* {@link IndexReader}'s sub-reader tree. Iff this reader is composed of sub
* readers ,ie. this reader being a composite reader, this method returns a
* {@link CompositeReaderContext} holding the reader's direct children as well as a
* view of the reader tree's atomic leaf contexts. All sub-
* {@link ReaderContext} instances referenced from this readers top-level
* context are private to this reader and are not shared with another context
* tree. For example, IndexSearcher uses this API to drive searching by one
* atomic leaf reader at a time. If this reader is not composed of child
* readers, this method returns an {@link AtomicReaderContext}.
* <p>
* Note: Any of the sub-{@link CompositeReaderContext} instances reference from this
* top-level context holds a <code>null</code> {@link CompositeReaderContext#leaves}
* reference. Only the top-level context maintains the convenience leaf-view
* for performance reasons.
*
* @lucene.experimental
*/
public abstract ReaderContext getTopReaderContext();
/** Expert */
public Object getCoreCacheKey() {
// Don't can ensureOpen since FC calls this (to evict)
// on close
return this;
}
/** Returns the number of unique terms (across all fields)
* in this reader.
*
* @return number of unique terms or -1 if this count
* cannot be easily determined (eg Multi*Readers).
* Instead, you should call {@link
* #getSequentialSubReaders} and ask each sub reader for
* its unique term count. */
public final long getUniqueTermCount() throws IOException {
if (!getTopReaderContext().isAtomic) {
return -1;
}
final Fields fields = fields();
if (fields == null) {
return 0;
}
return fields.getUniqueTermCount();
}
/** For IndexReader implementations that use
* TermInfosReader to read terms, this returns the
* current indexDivisor as specified when the reader was
* opened.
*/
public int getTermInfosIndexDivisor() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
public final IndexDocValues docValues(String field) throws IOException {
ensureOpen();
final PerDocValues perDoc = perDocValues();
if (perDoc == null) {
return null;
}
return perDoc.docValues(field);
}
private volatile Fields fields;
/** @lucene.internal */
void storeFields(Fields fields) {
ensureOpen();
this.fields = fields;
}
/** @lucene.internal */
Fields retrieveFields() {
ensureOpen();
return fields;
}
private volatile PerDocValues perDocValues;
/** @lucene.internal */
void storePerDoc(PerDocValues perDocValues) {
ensureOpen();
this.perDocValues = perDocValues;
}
/** @lucene.internal */
PerDocValues retrievePerDoc() {
ensureOpen();
return perDocValues;
}
/**
* A struct like class that represents a hierarchical relationship between
* {@link IndexReader} instances.
* @lucene.experimental
*/
public static abstract class ReaderContext {
/** The reader context for this reader's immediate parent, or null if none */
public final ReaderContext parent;
/** The actual reader */
public final IndexReader reader;
/** <code>true</code> iff the reader is an atomic reader */
public final boolean isAtomic;
/** <code>true</code> if this context struct represents the top level reader within the hierarchical context */
public final boolean isTopLevel;
/** the doc base for this reader in the parent, <tt>0</tt> if parent is null */
public final int docBaseInParent;
/** the ord for this reader in the parent, <tt>0</tt> if parent is null */
public final int ordInParent;
ReaderContext(ReaderContext parent, IndexReader reader,
boolean isAtomic, int ordInParent, int docBaseInParent) {
this.parent = parent;
this.reader = reader;
this.isAtomic = isAtomic;
this.docBaseInParent = docBaseInParent;
this.ordInParent = ordInParent;
this.isTopLevel = parent==null;
}
/**
* Returns the context's leaves if this context is a top-level context
* otherwise <code>null</code>.
* <p>
* Note: this is convenience method since leaves can always be obtained by
* walking the context tree.
*/
public AtomicReaderContext[] leaves() {
return null;
}
/**
* Returns the context's children iff this context is a composite context
* otherwise <code>null</code>.
* <p>
* Note: this method is a convenience method to prevent
* <code>instanceof</code> checks and type-casts to
* {@link CompositeReaderContext}.
*/
public ReaderContext[] children() {
return null;
}
}
/**
* {@link ReaderContext} for composite {@link IndexReader} instance.
* @lucene.experimental
*/
public static final class CompositeReaderContext extends ReaderContext {
/** the composite readers immediate children */
public final ReaderContext[] children;
/** the composite readers leaf reader contexts if this is the top level reader in this context */
public final AtomicReaderContext[] leaves;
/**
* Creates a {@link CompositeReaderContext} for intermediate readers that aren't
* not top-level readers in the current context
*/
public CompositeReaderContext(ReaderContext parent, IndexReader reader,
int ordInParent, int docbaseInParent, ReaderContext[] children) {
this(parent, reader, ordInParent, docbaseInParent, children, null);
}
/**
* Creates a {@link CompositeReaderContext} for top-level readers with parent set to <code>null</code>
*/
public CompositeReaderContext(IndexReader reader, ReaderContext[] children, AtomicReaderContext[] leaves) {
this(null, reader, 0, 0, children, leaves);
}
private CompositeReaderContext(ReaderContext parent, IndexReader reader,
int ordInParent, int docbaseInParent, ReaderContext[] children,
AtomicReaderContext[] leaves) {
super(parent, reader, false, ordInParent, docbaseInParent);
this.children = children;
this.leaves = leaves;
}
@Override
public AtomicReaderContext[] leaves() {
return leaves;
}
@Override
public ReaderContext[] children() {
return children;
}
}
/**
* {@link ReaderContext} for atomic {@link IndexReader} instances
* @lucene.experimental
*/
public static final class AtomicReaderContext extends ReaderContext {
/** The readers ord in the top-level's leaves array */
public final int ord;
/** The readers absolute doc base */
public final int docBase;
/**
* Creates a new {@link AtomicReaderContext}
*/
public AtomicReaderContext(ReaderContext parent, IndexReader reader,
int ord, int docBase, int leafOrd, int leafDocBase) {
super(parent, reader, true, ord, docBase);
assert reader.getSequentialSubReaders() == null : "Atomic readers must not have subreaders";
this.ord = leafOrd;
this.docBase = leafDocBase;
}
/**
* Creates a new {@link AtomicReaderContext} for a atomic reader without an immediate
* parent.
*/
public AtomicReaderContext(IndexReader atomicReader) {
this(null, atomicReader, 0, 0, 0, 0);
}
}
}
|
lucene/src/java/org/apache/lucene/index/IndexReader.java
|
package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DocumentStoredFieldVisitor;
import org.apache.lucene.index.codecs.PerDocValues;
import org.apache.lucene.index.values.IndexDocValues;
import org.apache.lucene.search.FieldCache; // javadocs
import org.apache.lucene.search.SearcherManager; // javadocs
import org.apache.lucene.store.*;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.ReaderUtil; // for javadocs
/** IndexReader is an abstract class, providing an interface for accessing an
index. Search of an index is done entirely through this abstract interface,
so that any subclass which implements it is searchable.
<p> Concrete subclasses of IndexReader are usually constructed with a call to
one of the static <code>open()</code> methods, e.g. {@link
#open(Directory)}.
<p> For efficiency, in this API documents are often referred to via
<i>document numbers</i>, non-negative integers which each name a unique
document in the index. These document numbers are ephemeral--they may change
as documents are added to and deleted from an index. Clients should thus not
rely on a given document having the same number between sessions.
<p>
<b>NOTE</b>: for backwards API compatibility, several methods are not listed
as abstract, but have no useful implementations in this base class and
instead always throw UnsupportedOperationException. Subclasses are
strongly encouraged to override these methods, but in many cases may not
need to.
</p>
<p>
<a name="thread-safety"></a><p><b>NOTE</b>: {@link
IndexReader} instances are completely thread
safe, meaning multiple threads can call any of its methods,
concurrently. If your application requires external
synchronization, you should <b>not</b> synchronize on the
<code>IndexReader</code> instance; use your own
(non-Lucene) objects instead.
*/
public abstract class IndexReader implements Cloneable,Closeable {
/**
* A custom listener that's invoked when the IndexReader
* is finished.
*
* <p>For a SegmentReader, this listener is called only
* once all SegmentReaders sharing the same core are
* closed. At this point it is safe for apps to evict
* this reader from any caches keyed on {@link
* #getCoreCacheKey}. This is the same interface that
* {@link FieldCache} uses, internally, to evict
* entries.</p>
*
* <p>For other readers, this listener is called when they
* are closed.</p>
*
* @lucene.experimental
*/
public static interface ReaderFinishedListener {
public void finished(IndexReader reader);
}
// Impls must set this if they may call add/removeReaderFinishedListener:
protected volatile Collection<ReaderFinishedListener> readerFinishedListeners;
/** Expert: adds a {@link ReaderFinishedListener}. The
* provided listener is also added to any sub-readers, if
* this is a composite reader. Also, any reader reopened
* or cloned from this one will also copy the listeners at
* the time of reopen.
*
* @lucene.experimental */
public void addReaderFinishedListener(ReaderFinishedListener listener) {
ensureOpen();
readerFinishedListeners.add(listener);
}
/** Expert: remove a previously added {@link ReaderFinishedListener}.
*
* @lucene.experimental */
public void removeReaderFinishedListener(ReaderFinishedListener listener) {
ensureOpen();
readerFinishedListeners.remove(listener);
}
protected void notifyReaderFinishedListeners() {
// Defensive (should never be null -- all impls must set
// this):
if (readerFinishedListeners != null) {
for(ReaderFinishedListener listener : readerFinishedListeners) {
listener.finished(this);
}
}
}
protected void readerFinished() {
notifyReaderFinishedListeners();
}
/**
* Constants describing field properties, for example used for
* {@link IndexReader#getFieldNames(FieldOption)}.
*/
public static enum FieldOption {
/** All fields */
ALL,
/** All indexed fields */
INDEXED,
/** All fields that store payloads */
STORES_PAYLOADS,
/** All fields that omit tf */
OMIT_TERM_FREQ_AND_POSITIONS,
/** All fields that omit positions */
OMIT_POSITIONS,
/** All fields which are not indexed */
UNINDEXED,
/** All fields which are indexed with termvectors enabled */
INDEXED_WITH_TERMVECTOR,
/** All fields which are indexed but don't have termvectors enabled */
INDEXED_NO_TERMVECTOR,
/** All fields with termvectors enabled. Please note that only standard termvector fields are returned */
TERMVECTOR,
/** All fields with termvectors with position values enabled */
TERMVECTOR_WITH_POSITION,
/** All fields with termvectors with offset values enabled */
TERMVECTOR_WITH_OFFSET,
/** All fields with termvectors with offset values and position values enabled */
TERMVECTOR_WITH_POSITION_OFFSET,
/** All fields holding doc values */
DOC_VALUES
}
private volatile boolean closed;
private final AtomicInteger refCount = new AtomicInteger();
static int DEFAULT_TERMS_INDEX_DIVISOR = 1;
/** Expert: returns the current refCount for this reader */
public final int getRefCount() {
return refCount.get();
}
/**
* Expert: increments the refCount of this IndexReader
* instance. RefCounts are used to determine when a
* reader can be closed safely, i.e. as soon as there are
* no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause;
* otherwise the reader may never be closed. Note that
* {@link #close} simply calls decRef(), which means that
* the IndexReader will not really be closed until {@link
* #decRef} has been called for all outstanding
* references.
*
* @see #decRef
* @see #tryIncRef
*/
public final void incRef() {
ensureOpen();
refCount.incrementAndGet();
}
/**
* Expert: increments the refCount of this IndexReader
* instance only if the IndexReader has not been closed yet
* and returns <code>true</code> iff the refCount was
* successfully incremented, otherwise <code>false</code>.
* If this method returns <code>false</code> the reader is either
* already closed or is currently been closed. Either way this
* reader instance shouldn't be used by an application unless
* <code>true</code> is returned.
* <p>
* RefCounts are used to determine when a
* reader can be closed safely, i.e. as soon as there are
* no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause;
* otherwise the reader may never be closed. Note that
* {@link #close} simply calls decRef(), which means that
* the IndexReader will not really be closed until {@link
* #decRef} has been called for all outstanding
* references.
*
* @see #decRef
* @see #incRef
*/
public final boolean tryIncRef() {
int count;
while ((count = refCount.get()) > 0) {
if (refCount.compareAndSet(count, count+1)) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append(getClass().getSimpleName());
buffer.append('(');
final IndexReader[] subReaders = getSequentialSubReaders();
if ((subReaders != null) && (subReaders.length > 0)) {
buffer.append(subReaders[0]);
for (int i = 1; i < subReaders.length; ++i) {
buffer.append(" ").append(subReaders[i]);
}
}
buffer.append(')');
return buffer.toString();
}
/**
* Expert: decreases the refCount of this IndexReader
* instance. If the refCount drops to 0, then pending
* changes (if any) are committed to the index and this
* reader is closed. If an exception is hit, the refCount
* is unchanged.
*
* @throws IOException in case an IOException occurs in commit() or doClose()
*
* @see #incRef
*/
public final void decRef() throws IOException {
ensureOpen();
final int rc = refCount.getAndDecrement();
if (rc == 1) {
boolean success = false;
try {
doClose();
success = true;
} finally {
if (!success) {
// Put reference back on failure
refCount.incrementAndGet();
}
}
readerFinished();
} else if (rc <= 0) {
throw new IllegalStateException("too many decRef calls: refCount was " + rc + " before decrement");
}
}
protected IndexReader() {
refCount.set(1);
}
/**
* @throws AlreadyClosedException if this IndexReader is closed
*/
protected final void ensureOpen() throws AlreadyClosedException {
if (refCount.get() <= 0) {
throw new AlreadyClosedException("this IndexReader is closed");
}
}
/** Returns a IndexReader reading the index in the given
* Directory
* @param directory the index directory
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final Directory directory) throws CorruptIndexException, IOException {
return DirectoryReader.open(directory, null, DEFAULT_TERMS_INDEX_DIVISOR);
}
/** Expert: Returns a IndexReader reading the index in the given
* Directory with the given termInfosIndexDivisor.
* @param directory the index directory
* @param termInfosIndexDivisor Subsamples which indexed
* terms are loaded into RAM. This has the same effect as {@link
* IndexWriterConfig#setTermIndexInterval} except that setting
* must be done at indexing time while this setting can be
* set per reader. When set to N, then one in every
* N*termIndexInterval terms in the index is loaded into
* memory. By setting this to a value > 1 you can reduce
* memory usage, at the expense of higher latency when
* loading a TermInfo. The default value is 1. Set this
* to -1 to skip loading the terms index entirely.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final Directory directory, int termInfosIndexDivisor) throws CorruptIndexException, IOException {
return DirectoryReader.open(directory, null, termInfosIndexDivisor);
}
/**
* Open a near real time IndexReader from the {@link org.apache.lucene.index.IndexWriter}.
*
* @param writer The IndexWriter to open from
* @param applyAllDeletes If true, all buffered deletes will
* be applied (made visible) in the returned reader. If
* false, the deletes are not applied but remain buffered
* (in IndexWriter) so that they will be applied in the
* future. Applying deletes can be costly, so if your app
* can tolerate deleted documents being returned you might
* gain some performance by passing false.
* @return The new IndexReader
* @throws CorruptIndexException
* @throws IOException if there is a low-level IO error
*
* @see #openIfChanged(IndexReader,IndexWriter,boolean)
*
* @lucene.experimental
*/
public static IndexReader open(final IndexWriter writer, boolean applyAllDeletes) throws CorruptIndexException, IOException {
return writer.getReader(applyAllDeletes);
}
/** Expert: returns an IndexReader reading the index in the given
* {@link IndexCommit}.
* @param commit the commit point to open
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final IndexCommit commit) throws CorruptIndexException, IOException {
return DirectoryReader.open(commit.getDirectory(), commit, DEFAULT_TERMS_INDEX_DIVISOR);
}
/** Expert: returns an IndexReader reading the index in the given
* {@link IndexCommit} and termInfosIndexDivisor.
* @param commit the commit point to open
* @param termInfosIndexDivisor Subsamples which indexed
* terms are loaded into RAM. This has the same effect as {@link
* IndexWriterConfig#setTermIndexInterval} except that setting
* must be done at indexing time while this setting can be
* set per reader. When set to N, then one in every
* N*termIndexInterval terms in the index is loaded into
* memory. By setting this to a value > 1 you can reduce
* memory usage, at the expense of higher latency when
* loading a TermInfo. The default value is 1. Set this
* to -1 to skip loading the terms index entirely.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static IndexReader open(final IndexCommit commit, int termInfosIndexDivisor) throws CorruptIndexException, IOException {
return DirectoryReader.open(commit.getDirectory(), commit, termInfosIndexDivisor);
}
/**
* If the index has changed since the provided reader was
* opened, open and return a new reader; else, return
* null. The new reader, if not null, will be the same
* type of reader as the previous one, ie an NRT reader
* will open a new NRT reader, a MultiReader will open a
* new MultiReader, etc.
*
* <p>This method is typically far less costly than opening a
* fully new <code>IndexReader</code> as it shares
* resources (for example sub-readers) with the provided
* <code>IndexReader</code>, when possible.
*
* <p>The provided reader is not closed (you are responsible
* for doing so); if a new reader is returned you also
* must eventually close it. Be sure to never close a
* reader while other threads are still using it; see
* {@link SearcherManager} to simplify managing this.
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
* @return null if there are no changes; else, a new
* IndexReader instance which you must eventually close
*/
public static IndexReader openIfChanged(IndexReader oldReader) throws IOException {
final IndexReader newReader = oldReader.doOpenIfChanged();
assert newReader != oldReader;
return newReader;
}
/**
* If the IndexCommit differs from what the
* provided reader is searching, open and return a new
* reader; else, return null.
*
* @see #openIfChanged(IndexReader)
*/
public static IndexReader openIfChanged(IndexReader oldReader, IndexCommit commit) throws IOException {
final IndexReader newReader = oldReader.doOpenIfChanged(commit);
assert newReader != oldReader;
return newReader;
}
/**
* Expert: If there changes (committed or not) in the
* {@link IndexWriter} versus what the provided reader is
* searching, then open and return a new
* IndexReader searching both committed and uncommitted
* changes from the writer; else, return null (though, the
* current implementation never returns null).
*
* <p>This provides "near real-time" searching, in that
* changes made during an {@link IndexWriter} session can be
* quickly made available for searching without closing
* the writer nor calling {@link IndexWriter#commit}.
*
* <p>It's <i>near</i> real-time because there is no hard
* guarantee on how quickly you can get a new reader after
* making changes with IndexWriter. You'll have to
* experiment in your situation to determine if it's
* fast enough. As this is a new and experimental
* feature, please report back on your findings so we can
* learn, improve and iterate.</p>
*
* <p>The very first time this method is called, this
* writer instance will make every effort to pool the
* readers that it opens for doing merges, applying
* deletes, etc. This means additional resources (RAM,
* file descriptors, CPU time) will be consumed.</p>
*
* <p>For lower latency on reopening a reader, you should
* call {@link IndexWriterConfig#setMergedSegmentWarmer} to
* pre-warm a newly merged segment before it's committed
* to the index. This is important for minimizing
* index-to-search delay after a large merge. </p>
*
* <p>If an addIndexes* call is running in another thread,
* then this reader will only search those segments from
* the foreign index that have been successfully copied
* over, so far.</p>
*
* <p><b>NOTE</b>: Once the writer is closed, any
* outstanding readers may continue to be used. However,
* if you attempt to reopen any of those readers, you'll
* hit an {@link AlreadyClosedException}.</p>
*
* @return IndexReader that covers entire index plus all
* changes made so far by this IndexWriter instance, or
* null if there are no new changes
*
* @param writer The IndexWriter to open from
*
* @param applyAllDeletes If true, all buffered deletes will
* be applied (made visible) in the returned reader. If
* false, the deletes are not applied but remain buffered
* (in IndexWriter) so that they will be applied in the
* future. Applying deletes can be costly, so if your app
* can tolerate deleted documents being returned you might
* gain some performance by passing false.
*
* @throws IOException
*
* @lucene.experimental
*/
public static IndexReader openIfChanged(IndexReader oldReader, IndexWriter writer, boolean applyAllDeletes) throws IOException {
final IndexReader newReader = oldReader.doOpenIfChanged(writer, applyAllDeletes);
assert newReader != oldReader;
return newReader;
}
/**
* If the index has changed since it was opened, open and return a new reader;
* else, return {@code null}.
*
* @see #openIfChanged(IndexReader)
*/
protected IndexReader doOpenIfChanged() throws CorruptIndexException, IOException {
throw new UnsupportedOperationException("This reader does not support reopen().");
}
/**
* If the index has changed since it was opened, open and return a new reader;
* else, return {@code null}.
*
* @see #openIfChanged(IndexReader, IndexCommit)
*/
protected IndexReader doOpenIfChanged(final IndexCommit commit) throws CorruptIndexException, IOException {
throw new UnsupportedOperationException("This reader does not support reopen(IndexCommit).");
}
/**
* If the index has changed since it was opened, open and return a new reader;
* else, return {@code null}.
*
* @see #openIfChanged(IndexReader, IndexWriter, boolean)
*/
protected IndexReader doOpenIfChanged(IndexWriter writer, boolean applyAllDeletes) throws CorruptIndexException, IOException {
return writer.getReader(applyAllDeletes);
}
/**
* Efficiently clones the IndexReader (sharing most
* internal state).
*/
@Override
public synchronized Object clone() {
throw new UnsupportedOperationException("This reader does not implement clone()");
}
/**
* Returns the directory associated with this index. The Default
* implementation returns the directory specified by subclasses when
* delegating to the IndexReader(Directory) constructor, or throws an
* UnsupportedOperationException if one was not specified.
* @throws UnsupportedOperationException if no directory
*/
public Directory directory() {
ensureOpen();
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Returns the time the index in the named directory was last modified.
* Do not use this to check whether the reader is still up-to-date, use
* {@link #isCurrent()} instead.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static long lastModified(final Directory directory2) throws CorruptIndexException, IOException {
return ((Long) new SegmentInfos.FindSegmentsFile(directory2) {
@Override
public Object doBody(String segmentFileName) throws IOException {
return Long.valueOf(directory2.fileModified(segmentFileName));
}
}.run()).longValue();
}
/**
* Reads version number from segments files. The version number is
* initialized with a timestamp and then increased by one for each change of
* the index.
*
* @param directory where the index resides.
* @return version number.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public static long getCurrentVersion(Directory directory) throws CorruptIndexException, IOException {
return SegmentInfos.readCurrentVersion(directory);
}
/**
* Reads commitUserData, previously passed to {@link
* IndexWriter#commit(Map)}, from current index
* segments file. This will return null if {@link
* IndexWriter#commit(Map)} has never been called for
* this index.
*
* @param directory where the index resides.
* @return commit userData.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*
* @see #getCommitUserData()
*/
public static Map<String, String> getCommitUserData(Directory directory) throws CorruptIndexException, IOException {
return SegmentInfos.readCurrentUserData(directory);
}
/**
* Version number when this IndexReader was opened. Not
* implemented in the IndexReader base class.
*
* <p>If this reader is based on a Directory (ie, was
* created by calling {@link #open}, or {@link #openIfChanged} on
* a reader based on a Directory), then this method
* returns the version recorded in the commit that the
* reader opened. This version is advanced every time
* {@link IndexWriter#commit} is called.</p>
*
* <p>If instead this reader is a near real-time reader
* (ie, obtained by a call to {@link
* IndexWriter#getReader}, or by calling {@link #openIfChanged}
* on a near real-time reader), then this method returns
* the version of the last commit done by the writer.
* Note that even as further changes are made with the
* writer, the version will not changed until a commit is
* completed. Thus, you should not rely on this method to
* determine when a near real-time reader should be
* opened. Use {@link #isCurrent} instead.</p>
*
* @throws UnsupportedOperationException unless overridden in subclass
*/
public long getVersion() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Retrieve the String userData optionally passed to
* IndexWriter#commit. This will return null if {@link
* IndexWriter#commit(Map)} has never been called for
* this index.
*
* @see #getCommitUserData(Directory)
*/
public Map<String,String> getCommitUserData() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Check whether any new changes have occurred to the
* index since this reader was opened.
*
* <p>If this reader is based on a Directory (ie, was
* created by calling {@link #open}, or {@link #openIfChanged} on
* a reader based on a Directory), then this method checks
* if any further commits (see {@link IndexWriter#commit}
* have occurred in that directory).</p>
*
* <p>If instead this reader is a near real-time reader
* (ie, obtained by a call to {@link
* IndexWriter#getReader}, or by calling {@link #openIfChanged}
* on a near real-time reader), then this method checks if
* either a new commit has occurred, or any new
* uncommitted changes have taken place via the writer.
* Note that even if the writer has only performed
* merging, this method will still return false.</p>
*
* <p>In any event, if this returns false, you should call
* {@link #openIfChanged} to get a new reader that sees the
* changes.</p>
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
* @throws UnsupportedOperationException unless overridden in subclass
*/
public boolean isCurrent() throws CorruptIndexException, IOException {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/** Retrieve term vectors for this document, or null if
* term vectors were not indexed. The returned Fields
* instance acts like a single-document inverted index
* (the docID will be 0). */
public abstract Fields getTermVectors(int docID)
throws IOException;
/** Retrieve term vector for this document and field, or
* null if term vectors were not indexed. The returned
* Fields instance acts like a single-document inverted
* index (the docID will be 0). */
public final Terms getTermVector(int docID, String field)
throws IOException {
Fields vectors = getTermVectors(docID);
if (vectors == null) {
return null;
}
return vectors.terms(field);
}
/**
* Returns <code>true</code> if an index exists at the specified directory.
* @param directory the directory to check for an index
* @return <code>true</code> if an index exists; <code>false</code> otherwise
* @throws IOException if there is a problem with accessing the index
*/
public static boolean indexExists(Directory directory) throws IOException {
try {
new SegmentInfos().read(directory);
return true;
} catch (IOException ioe) {
return false;
}
}
/** Returns the number of documents in this index. */
public abstract int numDocs();
/** Returns one greater than the largest possible document number.
* This may be used to, e.g., determine how big to allocate an array which
* will have an element for every document number in an index.
*/
public abstract int maxDoc();
/** Returns the number of deleted documents. */
public final int numDeletedDocs() {
return maxDoc() - numDocs();
}
/** Expert: visits the fields of a stored document, for
* custom processing/loading of each field. If you
* simply want to load all fields, use {@link
* #document(int)}. If you want to load a subset, use
* {@link DocumentStoredFieldVisitor}. */
public abstract void document(int docID, StoredFieldVisitor visitor) throws CorruptIndexException, IOException;
/**
* Returns the stored fields of the <code>n</code><sup>th</sup>
* <code>Document</code> in this index. This is just
* sugar for using {@link DocumentStoredFieldVisitor}.
* <p>
* <b>NOTE:</b> for performance reasons, this method does not check if the
* requested document is deleted, and therefore asking for a deleted document
* may yield unspecified results. Usually this is not required, however you
* can test if the doc is deleted by checking the {@link
* Bits} returned from {@link MultiFields#getLiveDocs}.
*
* <b>NOTE:</b> only the content of a field is returned,
* if that field was stored during indexing. Metadata
* like boost, omitNorm, IndexOptions, tokenized, etc.,
* are not preserved.
*
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
// TODO: we need a separate StoredField, so that the
// Document returned here contains that class not
// IndexableField
public final Document document(int docID) throws CorruptIndexException, IOException {
ensureOpen();
final DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor();
document(docID, visitor);
return visitor.getDocument();
}
/** Returns true if any documents have been deleted */
public abstract boolean hasDeletions();
/** Returns true if there are norms stored for this field. */
public boolean hasNorms(String field) throws IOException {
// backward compatible implementation.
// SegmentReader has an efficient implementation.
ensureOpen();
return norms(field) != null;
}
/** Returns the byte-encoded normalization factor for the named field of
* every document. This is used by the search code to score documents.
* Returns null if norms were not indexed for this field.
*
* @see org.apache.lucene.document.Field#setBoost(float)
*/
public abstract byte[] norms(String field) throws IOException;
/**
* Returns {@link Fields} for this reader.
* This method may return null if the reader has no
* postings.
*
* <p><b>NOTE</b>: if this is a multi reader ({@link
* #getSequentialSubReaders} is not null) then this
* method will throw UnsupportedOperationException. If
* you really need a {@link Fields} for such a reader,
* use {@link MultiFields#getFields}. However, for
* performance reasons, it's best to get all sub-readers
* using {@link ReaderUtil#gatherSubReaders} and iterate
* through them yourself. */
public abstract Fields fields() throws IOException;
/**
* Returns {@link PerDocValues} for this reader.
* This method may return null if the reader has no per-document
* values stored.
*
* <p><b>NOTE</b>: if this is a multi reader ({@link
* #getSequentialSubReaders} is not null) then this
* method will throw UnsupportedOperationException. If
* you really need {@link PerDocValues} for such a reader,
* use {@link MultiPerDocValues#getPerDocs(IndexReader)}. However, for
* performance reasons, it's best to get all sub-readers
* using {@link ReaderUtil#gatherSubReaders} and iterate
* through them yourself. */
public abstract PerDocValues perDocValues() throws IOException;
public final int docFreq(Term term) throws IOException {
return docFreq(term.field(), term.bytes());
}
/** Returns the number of documents containing the term
* <code>t</code>. This method returns 0 if the term or
* field does not exists. This method does not take into
* account deleted documents that have not yet been merged
* away. */
public int docFreq(String field, BytesRef term) throws IOException {
final Fields fields = fields();
if (fields == null) {
return 0;
}
final Terms terms = fields.terms(field);
if (terms == null) {
return 0;
}
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.docFreq();
} else {
return 0;
}
}
/** Returns the number of documents containing the term
* <code>t</code>. This method returns 0 if the term or
* field does not exists. This method does not take into
* account deleted documents that have not yet been merged
* away. */
public final long totalTermFreq(String field, BytesRef term) throws IOException {
final Fields fields = fields();
if (fields == null) {
return 0;
}
final Terms terms = fields.terms(field);
if (terms == null) {
return 0;
}
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.totalTermFreq();
} else {
return 0;
}
}
/** This may return null if the field does not exist.*/
public final Terms terms(String field) throws IOException {
final Fields fields = fields();
if (fields == null) {
return null;
}
return fields.terms(field);
}
/** Returns {@link DocsEnum} for the specified field &
* term. This may return null, if either the field or
* term does not exist. */
public final DocsEnum termDocsEnum(Bits liveDocs, String field, BytesRef term, boolean needsFreqs) throws IOException {
assert field != null;
assert term != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.docs(liveDocs, null, needsFreqs);
}
}
}
return null;
}
/** Returns {@link DocsAndPositionsEnum} for the specified
* field & term. This may return null, if either the
* field or term does not exist, or, positions were not
* indexed for this field. */
public final DocsAndPositionsEnum termPositionsEnum(Bits liveDocs, String field, BytesRef term) throws IOException {
assert field != null;
assert term != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
if (termsEnum.seekExact(term, true)) {
return termsEnum.docsAndPositions(liveDocs, null);
}
}
}
return null;
}
/**
* Returns {@link DocsEnum} for the specified field and
* {@link TermState}. This may return null, if either the field or the term
* does not exists or the {@link TermState} is invalid for the underlying
* implementation.*/
public final DocsEnum termDocsEnum(Bits liveDocs, String field, BytesRef term, TermState state, boolean needsFreqs) throws IOException {
assert state != null;
assert field != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
termsEnum.seekExact(term, state);
return termsEnum.docs(liveDocs, null, needsFreqs);
}
}
return null;
}
/**
* Returns {@link DocsAndPositionsEnum} for the specified field and
* {@link TermState}. This may return null, if either the field or the term
* does not exists, the {@link TermState} is invalid for the underlying
* implementation, or positions were not indexed for this field. */
public final DocsAndPositionsEnum termPositionsEnum(Bits liveDocs, String field, BytesRef term, TermState state) throws IOException {
assert state != null;
assert field != null;
final Fields fields = fields();
if (fields != null) {
final Terms terms = fields.terms(field);
if (terms != null) {
final TermsEnum termsEnum = terms.iterator(null);
termsEnum.seekExact(term, state);
return termsEnum.docsAndPositions(liveDocs, null);
}
}
return null;
}
/**
* Closes files associated with this index.
* Also saves any new deletions to disk.
* No other methods should be called after this has been called.
* @throws IOException if there is a low-level IO error
*/
public final synchronized void close() throws IOException {
if (!closed) {
decRef();
closed = true;
}
}
/** Implements close. */
protected abstract void doClose() throws IOException;
/**
* Get a list of unique field names that exist in this index and have the specified
* field option information.
* @param fldOption specifies which field option should be available for the returned fields
* @return Collection of Strings indicating the names of the fields.
* @see IndexReader.FieldOption
*/
public abstract Collection<String> getFieldNames(FieldOption fldOption);
/** Returns the {@link Bits} representing live (not
* deleted) docs. A set bit indicates the doc ID has not
* been deleted. If this method returns null it means
* there are no deleted documents (all documents are
* live).
*
* The returned instance has been safely published for
* use by multiple threads without additional
* synchronization.
* @lucene.experimental */
public abstract Bits getLiveDocs();
/**
* Expert: return the IndexCommit that this reader has
* opened. This method is only implemented by those
* readers that correspond to a Directory with its own
* segments_N file.
*
* @lucene.experimental
*/
public IndexCommit getIndexCommit() throws IOException {
throw new UnsupportedOperationException("This reader does not support this method.");
}
/**
* Prints the filename and size of each file within a given compound file.
* Add the -extract flag to extract files to the current working directory.
* In order to make the extracted version of the index work, you have to copy
* the segments file from the compound index into the directory where the extracted files are stored.
* @param args Usage: org.apache.lucene.index.IndexReader [-extract] <cfsfile>
*/
public static void main(String [] args) {
String filename = null;
boolean extract = false;
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-extract")) {
extract = true;
} else if (filename == null) {
filename = args[i];
}
}
if (filename == null) {
System.out.println("Usage: org.apache.lucene.index.IndexReader [-extract] <cfsfile>");
return;
}
Directory dir = null;
CompoundFileDirectory cfr = null;
IOContext context = IOContext.READ;
try {
File file = new File(filename);
String dirname = file.getAbsoluteFile().getParent();
filename = file.getName();
dir = FSDirectory.open(new File(dirname));
cfr = new CompoundFileDirectory(dir, filename, IOContext.DEFAULT, false);
String [] files = cfr.listAll();
ArrayUtil.mergeSort(files); // sort the array of filename so that the output is more readable
for (int i = 0; i < files.length; ++i) {
long len = cfr.fileLength(files[i]);
if (extract) {
System.out.println("extract " + files[i] + " with " + len + " bytes to local directory...");
IndexInput ii = cfr.openInput(files[i], context);
FileOutputStream f = new FileOutputStream(files[i]);
// read and write with a small buffer, which is more effective than reading byte by byte
byte[] buffer = new byte[1024];
int chunk = buffer.length;
while(len > 0) {
final int bufLen = (int) Math.min(chunk, len);
ii.readBytes(buffer, 0, bufLen);
f.write(buffer, 0, bufLen);
len -= bufLen;
}
f.close();
ii.close();
}
else
System.out.println(files[i] + ": " + len + " bytes");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (dir != null)
dir.close();
if (cfr != null)
cfr.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/** Returns all commit points that exist in the Directory.
* Normally, because the default is {@link
* KeepOnlyLastCommitDeletionPolicy}, there would be only
* one commit point. But if you're using a custom {@link
* IndexDeletionPolicy} then there could be many commits.
* Once you have a given commit, you can open a reader on
* it by calling {@link IndexReader#open(IndexCommit)}
* There must be at least one commit in
* the Directory, else this method throws {@link
* IndexNotFoundException}. Note that if a commit is in
* progress while this method is running, that commit
* may or may not be returned.
*
* @return a sorted list of {@link IndexCommit}s, from oldest
* to latest. */
public static List<IndexCommit> listCommits(Directory dir) throws IOException {
return DirectoryReader.listCommits(dir);
}
/** Expert: returns the sequential sub readers that this
* reader is logically composed of. If this reader is not composed
* of sequential child readers, it should return null.
* If this method returns an empty array, that means this
* reader is a null reader (for example a MultiReader
* that has no sub readers).
* <p>
* NOTE: You should not try using sub-readers returned by
* this method to make any changes (deleteDocument,
* etc.). While this might succeed for one composite reader
* (like MultiReader), it will most likely lead to index
* corruption for other readers (like DirectoryReader obtained
* through {@link #open}. Use the parent reader directly. */
public IndexReader[] getSequentialSubReaders() {
ensureOpen();
return null;
}
/**
* Expert: Returns a the root {@link ReaderContext} for this
* {@link IndexReader}'s sub-reader tree. Iff this reader is composed of sub
* readers ,ie. this reader being a composite reader, this method returns a
* {@link CompositeReaderContext} holding the reader's direct children as well as a
* view of the reader tree's atomic leaf contexts. All sub-
* {@link ReaderContext} instances referenced from this readers top-level
* context are private to this reader and are not shared with another context
* tree. For example, IndexSearcher uses this API to drive searching by one
* atomic leaf reader at a time. If this reader is not composed of child
* readers, this method returns an {@link AtomicReaderContext}.
* <p>
* Note: Any of the sub-{@link CompositeReaderContext} instances reference from this
* top-level context holds a <code>null</code> {@link CompositeReaderContext#leaves}
* reference. Only the top-level context maintains the convenience leaf-view
* for performance reasons.
*
* @lucene.experimental
*/
public abstract ReaderContext getTopReaderContext();
/** Expert */
public Object getCoreCacheKey() {
// Don't can ensureOpen since FC calls this (to evict)
// on close
return this;
}
/** Returns the number of unique terms (across all fields)
* in this reader.
*
* @return number of unique terms or -1 if this count
* cannot be easily determined (eg Multi*Readers).
* Instead, you should call {@link
* #getSequentialSubReaders} and ask each sub reader for
* its unique term count. */
public final long getUniqueTermCount() throws IOException {
if (!getTopReaderContext().isAtomic) {
return -1;
}
final Fields fields = fields();
if (fields == null) {
return 0;
}
return fields.getUniqueTermCount();
}
/** For IndexReader implementations that use
* TermInfosReader to read terms, this returns the
* current indexDivisor as specified when the reader was
* opened.
*/
public int getTermInfosIndexDivisor() {
throw new UnsupportedOperationException("This reader does not support this method.");
}
public final IndexDocValues docValues(String field) throws IOException {
ensureOpen();
final PerDocValues perDoc = perDocValues();
if (perDoc == null) {
return null;
}
return perDoc.docValues(field);
}
private volatile Fields fields;
/** @lucene.internal */
void storeFields(Fields fields) {
ensureOpen();
this.fields = fields;
}
/** @lucene.internal */
Fields retrieveFields() {
ensureOpen();
return fields;
}
private volatile PerDocValues perDocValues;
/** @lucene.internal */
void storePerDoc(PerDocValues perDocValues) {
ensureOpen();
this.perDocValues = perDocValues;
}
/** @lucene.internal */
PerDocValues retrievePerDoc() {
ensureOpen();
return perDocValues;
}
/**
* A struct like class that represents a hierarchical relationship between
* {@link IndexReader} instances.
* @lucene.experimental
*/
public static abstract class ReaderContext {
/** The reader context for this reader's immediate parent, or null if none */
public final ReaderContext parent;
/** The actual reader */
public final IndexReader reader;
/** <code>true</code> iff the reader is an atomic reader */
public final boolean isAtomic;
/** <code>true</code> if this context struct represents the top level reader within the hierarchical context */
public final boolean isTopLevel;
/** the doc base for this reader in the parent, <tt>0</tt> if parent is null */
public final int docBaseInParent;
/** the ord for this reader in the parent, <tt>0</tt> if parent is null */
public final int ordInParent;
ReaderContext(ReaderContext parent, IndexReader reader,
boolean isAtomic, int ordInParent, int docBaseInParent) {
this.parent = parent;
this.reader = reader;
this.isAtomic = isAtomic;
this.docBaseInParent = docBaseInParent;
this.ordInParent = ordInParent;
this.isTopLevel = parent==null;
}
/**
* Returns the context's leaves if this context is a top-level context
* otherwise <code>null</code>.
* <p>
* Note: this is convenience method since leaves can always be obtained by
* walking the context tree.
*/
public AtomicReaderContext[] leaves() {
return null;
}
/**
* Returns the context's children iff this context is a composite context
* otherwise <code>null</code>.
* <p>
* Note: this method is a convenience method to prevent
* <code>instanceof</code> checks and type-casts to
* {@link CompositeReaderContext}.
*/
public ReaderContext[] children() {
return null;
}
}
/**
* {@link ReaderContext} for composite {@link IndexReader} instance.
* @lucene.experimental
*/
public static final class CompositeReaderContext extends ReaderContext {
/** the composite readers immediate children */
public final ReaderContext[] children;
/** the composite readers leaf reader contexts if this is the top level reader in this context */
public final AtomicReaderContext[] leaves;
/**
* Creates a {@link CompositeReaderContext} for intermediate readers that aren't
* not top-level readers in the current context
*/
public CompositeReaderContext(ReaderContext parent, IndexReader reader,
int ordInParent, int docbaseInParent, ReaderContext[] children) {
this(parent, reader, ordInParent, docbaseInParent, children, null);
}
/**
* Creates a {@link CompositeReaderContext} for top-level readers with parent set to <code>null</code>
*/
public CompositeReaderContext(IndexReader reader, ReaderContext[] children, AtomicReaderContext[] leaves) {
this(null, reader, 0, 0, children, leaves);
}
private CompositeReaderContext(ReaderContext parent, IndexReader reader,
int ordInParent, int docbaseInParent, ReaderContext[] children,
AtomicReaderContext[] leaves) {
super(parent, reader, false, ordInParent, docbaseInParent);
this.children = children;
this.leaves = leaves;
}
@Override
public AtomicReaderContext[] leaves() {
return leaves;
}
@Override
public ReaderContext[] children() {
return children;
}
}
/**
* {@link ReaderContext} for atomic {@link IndexReader} instances
* @lucene.experimental
*/
public static final class AtomicReaderContext extends ReaderContext {
/** The readers ord in the top-level's leaves array */
public final int ord;
/** The readers absolute doc base */
public final int docBase;
/**
* Creates a new {@link AtomicReaderContext}
*/
public AtomicReaderContext(ReaderContext parent, IndexReader reader,
int ord, int docBase, int leafOrd, int leafDocBase) {
super(parent, reader, true, ord, docBase);
assert reader.getSequentialSubReaders() == null : "Atomic readers must not have subreaders";
this.ord = leafOrd;
this.docBase = leafDocBase;
}
/**
* Creates a new {@link AtomicReaderContext} for a atomic reader without an immediate
* parent.
*/
public AtomicReaderContext(IndexReader atomicReader) {
this(null, atomicReader, 0, 0, 0, 0);
}
}
}
|
LUCENE-3637: change IndexReader.decRef to call decrementAndGet
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1213033 13f79535-47bb-0310-9956-ffa450edef68
|
lucene/src/java/org/apache/lucene/index/IndexReader.java
|
LUCENE-3637: change IndexReader.decRef to call decrementAndGet
|
<ide><path>ucene/src/java/org/apache/lucene/index/IndexReader.java
<ide> */
<ide> public final void decRef() throws IOException {
<ide> ensureOpen();
<del> final int rc = refCount.getAndDecrement();
<del> if (rc == 1) {
<add> final int rc = refCount.decrementAndGet();
<add> if (rc == 0) {
<ide> boolean success = false;
<ide> try {
<ide> doClose();
<ide> }
<ide> }
<ide> readerFinished();
<del> } else if (rc <= 0) {
<del> throw new IllegalStateException("too many decRef calls: refCount was " + rc + " before decrement");
<add> } else if (rc < 0) {
<add> throw new IllegalStateException("too many decRef calls: refCount is " + rc + " after decrement");
<ide> }
<ide> }
<ide>
|
|
Java
|
mit
|
3aeb83f5f78a19117c7fb877b855a910e612f717
| 0 |
subwoofer359/AMCChessGame,subwoofer359/AMCChessGame,subwoofer359/AMCChessGame,subwoofer359/AMCChessGame
|
package org.amc.game.chess;
import org.amc.game.chess.ChessBoard.ChessPieceLocation;
import java.text.ParseException;
import java.util.List;
public class ChessBoardFactoryImpl implements ChessBoardFactory {
private final ChessBoardSetupNotation notation;
public ChessBoardFactoryImpl(ChessBoardSetupNotation notation) {
this.notation = notation;
}
/* (non-Javadoc)
* @see org.amc.game.chess.ChessBoardFactory#getChessBoard(java.lang.String)
*/
@Override
public ChessBoard getChessBoard(String setupNotation) throws ParseException {
if (notation.isInputValid(setupNotation)) {
List<ChessPieceLocation> cpl = notation.getChessPieceLocations(setupNotation);
return getChessBoard(cpl);
} else {
throw new ParseException("Not valid setup notation", 0);
}
}
private ChessBoard getChessBoard(List<ChessPieceLocation> pieceLocations) {
ChessBoard board = new ChessBoard();
for (ChessPieceLocation cpl : pieceLocations) {
board.putPieceOnBoardAt(cpl.getPiece(), cpl.getLocation());
}
return board;
}
}
|
src/main/java/org/amc/game/chess/ChessBoardFactoryImpl.java
|
package org.amc.game.chess;
import org.amc.game.chess.ChessBoard.ChessPieceLocation;
import java.text.ParseException;
import java.util.List;
public class ChessBoardFactoryImpl implements ChessBoardFactory {
private final SimpleChessBoardSetupNotation notation;
public ChessBoardFactoryImpl(SimpleChessBoardSetupNotation notation) {
this.notation = notation;
}
/* (non-Javadoc)
* @see org.amc.game.chess.ChessBoardFactory#getChessBoard(java.lang.String)
*/
@Override
public ChessBoard getChessBoard(String setupNotation) throws ParseException {
if (notation.isInputValid(setupNotation)) {
List<ChessPieceLocation> cpl = notation.getChessPieceLocations(setupNotation);
return getChessBoard(cpl);
} else {
throw new ParseException("Not valid setup notation", 0);
}
}
private ChessBoard getChessBoard(List<ChessPieceLocation> pieceLocations) {
ChessBoard board = new ChessBoard();
for (ChessPieceLocation cpl : pieceLocations) {
board.putPieceOnBoardAt(cpl.getPiece(), cpl.getLocation());
}
return board;
}
}
|
modify ChessBoardFactoryImpl to use interface for ChessBoardSetupNotation
|
src/main/java/org/amc/game/chess/ChessBoardFactoryImpl.java
|
modify ChessBoardFactoryImpl to use interface for ChessBoardSetupNotation
|
<ide><path>rc/main/java/org/amc/game/chess/ChessBoardFactoryImpl.java
<ide>
<ide> public class ChessBoardFactoryImpl implements ChessBoardFactory {
<ide>
<del> private final SimpleChessBoardSetupNotation notation;
<add> private final ChessBoardSetupNotation notation;
<ide>
<del> public ChessBoardFactoryImpl(SimpleChessBoardSetupNotation notation) {
<add> public ChessBoardFactoryImpl(ChessBoardSetupNotation notation) {
<ide> this.notation = notation;
<ide> }
<ide>
|
|
Java
|
bsd-3-clause
|
a4f68d780258106514c6514151fd5254e4826add
| 0 |
luxiaohan/openxal-csns-luxh,openxal/openxal,EuropeanSpallationSource/openxal,luxiaohan/openxal-csns-luxh,luxiaohan/openxal-csns-luxh,openxal/openxal,EuropeanSpallationSource/openxal,openxal/openxal,openxal/openxal,EuropeanSpallationSource/openxal,EuropeanSpallationSource/openxal,EuropeanSpallationSource/openxal,openxal/openxal,luxiaohan/openxal-csns-luxh
|
/*
* ParseWirefile.java
*
* Created on November 12, 2004 */
package xal.app.wireanalysis;
import xal.tools.*;
import xal.smf.*;
import xal.smf.impl.*;
import xal.ca.*;
import xal.tools.messaging.*;
import xal.tools.statistics.*;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* Read and parse a wirescan file, extract data and send out as HashMap.
*
* @author cp3
*/
public class ParseWireFile{
public ArrayList<Object> wiredata = new ArrayList<Object>();
/** Creates new ParseWireFile */
public ParseWireFile() {
}
public ArrayList<Object> parseFile(File newfile) throws IOException {
String s;
String firstName;
String header;
String name = null;
Integer PVLoggerID = new Integer(0);
String[] tokens;
int nvalues = 0;
double num1, num2, num3;
double xoffset = 1.0;
double xdelta = 1.0;
double yoffset = 1.0;
double ydelta = 1.0;
double zoffset = 1.0;
double zdelta = 1.0;
boolean readfit = false;
boolean readraw = false;
boolean zerodata = false;
boolean baddata = false;
boolean harpdata = false;
boolean elsdata = false;
boolean elsx = false;
boolean elsy = false;
ArrayList<Double> fitparams = new ArrayList<Double>();
ArrayList<Double> xraw = new ArrayList<Double>();
ArrayList<Double> yraw = new ArrayList<Double>();
ArrayList<Double> zraw = new ArrayList<Double>();
ArrayList<Double> sraw = new ArrayList<Double>();
ArrayList<Double> sxraw = new ArrayList<Double>();
ArrayList<Double> syraw = new ArrayList<Double>();
ArrayList<Double> szraw = new ArrayList<Double>();
//Open the file.
URL url = newfile.toURI().toURL();
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while((s=br.readLine()) != null){
tokens = s.split("\\s+");
nvalues = tokens.length;
firstName = tokens[0];
if((tokens[0]).length()==0){ //Skip blank lines
readraw = false;
readfit = false;
continue;
}
if( (nvalues == 4) && (!firstName.startsWith("---")) ){
//System.out.println("tokens[0]" + tokens[0]);
if( (Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.) ){
zerodata = true;
}
else{
zerodata = false;
}
if( tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")){
baddata = true;
}
else{
baddata = false;
}
}
if(firstName.startsWith("start")){
header = s;
}
if((firstName.indexOf("WS") > 0) || (firstName.indexOf("LW") > 0)){
if(name != null){
dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw);
}
name = tokens[0];
readraw = false;
readfit = false;
zerodata = false;
baddata = false;
harpdata=false;
fitparams.clear();
xraw.clear();
yraw.clear();
zraw.clear();
sraw.clear();
sxraw.clear();
syraw.clear();
szraw.clear();
}
//unused
// if(firstName.startsWith("Area")) ;
// if(firstName.startsWith("Ampl")) ;
// if(firstName.startsWith("Mean")) ;
if(firstName.startsWith("Sigma")){
fitparams.add(new Double(Double.parseDouble(tokens[3]))); //zfit
fitparams.add(new Double(Double.parseDouble(tokens[1]))); //yfit
fitparams.add(new Double(Double.parseDouble(tokens[5]))); //xfit
}
// if(firstName.startsWith("Offset")) ;
// if(firstName.startsWith("Slope")) ;
if((firstName.equals("Position")) && ((tokens[2]).equals("Raw")) ){
readraw = true;
continue;
}
if((firstName.equals("Position")) && ((tokens[2]).equals("Fit")) ){
readfit = true;
continue;
}
if((firstName.contains("Harp"))){
xraw.clear();
yraw.clear();
zraw.clear();
sraw.clear();
sxraw.clear();
syraw.clear();
szraw.clear();
fitparams.clear();
harpdata = true;
readraw = true;
name = tokens[0];
fitparams.add(new Double(0.0)); //xfit
fitparams.add(new Double(0.0)); //yfit
fitparams.add(new Double(0.0)); //zfit
continue;
}
if((firstName.contains("ELS"))){
elsdata=true;
name = tokens[0];
fitparams.add(new Double(0.0)); //xfit
fitparams.add(new Double(0.0)); //yfit
fitparams.add(new Double(0.0)); //zfit
continue;
}
if(elsdata && firstName.contains("X_Position")){
System.out.println("Found X for ELS");
elsx = true;
elsy = false;
xraw.clear();
yraw.clear();
zraw.clear();
sraw.clear();
sxraw.clear();
syraw.clear();
szraw.clear();
fitparams.clear();
//elsdata = true;
readraw = true;
continue;
}
if(elsdata && firstName.contains("Y_Position")){
System.out.println("Found Y for ELS");
elsx = false;
elsy = true;
continue;
}
if(firstName.startsWith("---")) continue ;
if(harpdata==true){
if((tokens[0]).length()!=0){ //Skip blank lines
if(firstName.startsWith("PVLogger")){
try{
PVLoggerID = new Integer(Integer.parseInt(tokens[2]));
}
catch(NumberFormatException e){
}
}
else{
sxraw.add(new Double(Double.parseDouble(tokens[0])));
xraw.add(new Double(Double.parseDouble(tokens[1])));
syraw.add(new Double(Double.parseDouble(tokens[2])));
yraw.add(new Double(Double.parseDouble(tokens[3])));
szraw.add(new Double(Double.parseDouble(tokens[4])));
zraw.add(new Double(Double.parseDouble(tokens[5])));
}
}
continue;
}
if(elsdata==true){
if(elsx == true){
if((tokens[0]).length()!=0){ //Skip blank lines
sxraw.add(new Double(Double.parseDouble(tokens[0])));
xraw.add(new Double(Double.parseDouble(tokens[1])));
}
}
if(elsy == true){
if((tokens[0]).length()!=0){ //Skip blank lines
syraw.add(new Double(Double.parseDouble(tokens[0])));
yraw.add(new Double(Double.parseDouble(tokens[1])));
szraw.add(new Double(0.0));
zraw.add(new Double(0.0));
}
}
continue;
}
if(readraw && (!zerodata) && (!baddata) ){
if(tokens.length == 7){
sraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
sxraw.add(new Double(Double.parseDouble(tokens[4])));
syraw.add(new Double(Double.parseDouble(tokens[5])));
szraw.add(new Double(Double.parseDouble(tokens[6])));
yraw.add(new Double(Double.parseDouble(tokens[1])));
zraw.add(new Double(Double.parseDouble(tokens[2])));
xraw.add(new Double(Double.parseDouble(tokens[3])));
}
else{
sraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
sxraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
syraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
szraw.add(new Double(Double.parseDouble(tokens[0])));
yraw.add(new Double(Double.parseDouble(tokens[1])));
zraw.add(new Double(Double.parseDouble(tokens[2])));
xraw.add(new Double(Double.parseDouble(tokens[3])));
}
}
if(firstName.startsWith("PVLogger")){
try{
PVLoggerID = new Integer(Integer.parseInt(tokens[2]));
}
catch(NumberFormatException e){
}
}
}
dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw);
//writeData();
wiredata.add(PVLoggerID);
return wiredata;
}
private void dumpData(String label, ArrayList<Double> fitparams, ArrayList<Double> sraw, ArrayList<Double> sxraw, ArrayList<Double> syraw, ArrayList<Double> szraw, ArrayList<Double> yraw, ArrayList<Double> zraw, ArrayList<Double> xraw){
HashMap<String,Object> data = new HashMap<String, Object>();
data.put("name", label);
data.put("fitparams", new ArrayList<Double>(fitparams));
data.put("sdata", new ArrayList<Double>(sraw));
data.put("sxdata", new ArrayList<Double>(sxraw));
data.put("sydata", new ArrayList<Double>(syraw));
data.put("szdata", new ArrayList<Double>(szraw));
data.put("xdata", new ArrayList<Double>(xraw));
data.put("ydata", new ArrayList<Double>(yraw));
data.put("zdata", new ArrayList<Double>(zraw));
wiredata.add((HashMap)data);
}
@SuppressWarnings ("unchecked") //Had to suppress because wiredata holds multiple types.
private void writeData(){
//This is just a routine to write out the current data set.
Iterator<Object> itr = wiredata.iterator();
while(itr.hasNext()){
HashMap<String, ArrayList<Double>> map = (HashMap<String, ArrayList<Double>>)itr.next();
ArrayList<Double> fitlist = map.get("fitparams");
ArrayList<Double> slist = map.get("sdata");
ArrayList<Double> ylist = map.get("ydata");
ArrayList<Double> zlist = map.get("zdata");
ArrayList<Double> xlist = map.get("xdata");
int ssize = slist.size();
int xsize = xlist.size();
int ysize = ylist.size();
int zsize = zlist.size();
System.out.println("This is " + map.get("name"));
System.out.println("With fit params " + fitlist.get(0) + " " + fitlist.get (1) + " " +fitlist.get(2));
if((ssize == xsize ) && (xsize == ysize) && (ysize == zsize)){
for(int i = 0; i<ssize; i++){
System.out.println(slist.get(i) + " " + ylist.get(i) + " " + zlist.get(i) + " " + xlist.get(i));
}
}
else{
System.out.println("Oops, a problem with array sizing.");
System.out.println(ssize + " " + xsize + " " + ysize + " " + zsize);
}
}
}
}
|
apps/wireanalysis/src/xal/app/wireanalysis/ParseWireFile.java
|
/*
* ParseWirefile.java
*
* Created on November 12, 2004 */
package xal.app.wireanalysis;
import xal.tools.*;
import xal.smf.*;
import xal.smf.impl.*;
import xal.ca.*;
import xal.tools.messaging.*;
import xal.tools.statistics.*;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* Read and parse a wirescan file, extract data and send out as HashMap.
*
* @author cp3
*/
public class ParseWireFile{
public ArrayList<Object> wiredata = new ArrayList<Object>();
/** Creates new ParseWireFile */
public ParseWireFile() {
}
public ArrayList<Object> parseFile(File newfile) throws IOException {
String s;
String firstName;
String header;
String name = null;
Integer PVLoggerID = new Integer(0);
String[] tokens;
int nvalues = 0;
double num1, num2, num3;
double xoffset = 1.0;
double xdelta = 1.0;
double yoffset = 1.0;
double ydelta = 1.0;
double zoffset = 1.0;
double zdelta = 1.0;
boolean readfit = false;
boolean readraw = false;
boolean zerodata = false;
boolean baddata = false;
boolean harpdata = false;
boolean elsdata = false;
boolean elsx = false;
boolean elsy = false;
ArrayList<Double> fitparams = new ArrayList<Double>();
ArrayList<Double> xraw = new ArrayList<Double>();
ArrayList<Double> yraw = new ArrayList<Double>();
ArrayList<Double> zraw = new ArrayList<Double>();
ArrayList<Double> sraw = new ArrayList<Double>();
ArrayList<Double> sxraw = new ArrayList<Double>();
ArrayList<Double> syraw = new ArrayList<Double>();
ArrayList<Double> szraw = new ArrayList<Double>();
//Open the file.
//URL url = getClass().getResource(filename);
URL url = newfile.toURI().toURL();
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while((s=br.readLine()) != null){
tokens = s.split("\\s+");
nvalues = tokens.length;
firstName = tokens[0];
if((tokens[0]).length()==0){ //Skip blank lines
readraw = false;
readfit = false;
continue;
}
if( (nvalues == 4) && (!firstName.startsWith("---")) ){
//System.out.println("tokens[0]" + tokens[0]);
if( (Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.) ){
zerodata = true;
}
else{
zerodata = false;
}
if( tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")){
baddata = true;
}
else{
baddata = false;
}
}
if(firstName.startsWith("start")){
header = s;
}
if((firstName.indexOf("WS") > 0) || (firstName.indexOf("LW") > 0)){
if(name != null){
dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw);
}
name = tokens[0];
readraw = false;
readfit = false;
zerodata = false;
baddata = false;
harpdata=false;
fitparams.clear();
xraw.clear();
yraw.clear();
zraw.clear();
sraw.clear();
sxraw.clear();
syraw.clear();
szraw.clear();
}
//unused
// if(firstName.startsWith("Area")) ;
// if(firstName.startsWith("Ampl")) ;
// if(firstName.startsWith("Mean")) ;
if(firstName.startsWith("Sigma")){
fitparams.add(new Double(Double.parseDouble(tokens[3]))); //zfit
fitparams.add(new Double(Double.parseDouble(tokens[1]))); //yfit
fitparams.add(new Double(Double.parseDouble(tokens[5]))); //xfit
}
// if(firstName.startsWith("Offset")) ;
// if(firstName.startsWith("Slope")) ;
if((firstName.equals("Position")) && ((tokens[2]).equals("Raw")) ){
readraw = true;
continue;
}
if((firstName.equals("Position")) && ((tokens[2]).equals("Fit")) ){
readfit = true;
continue;
}
if((firstName.contains("Harp"))){
xraw.clear();
yraw.clear();
zraw.clear();
sraw.clear();
sxraw.clear();
syraw.clear();
szraw.clear();
fitparams.clear();
harpdata = true;
readraw = true;
name = tokens[0];
fitparams.add(new Double(0.0)); //xfit
fitparams.add(new Double(0.0)); //yfit
fitparams.add(new Double(0.0)); //zfit
continue;
}
if((firstName.contains("ELS"))){
elsdata=true;
name = tokens[0];
fitparams.add(new Double(0.0)); //xfit
fitparams.add(new Double(0.0)); //yfit
fitparams.add(new Double(0.0)); //zfit
continue;
}
if(elsdata && firstName.contains("X_Position")){
System.out.println("Found X for ELS");
elsx = true;
elsy = false;
xraw.clear();
yraw.clear();
zraw.clear();
sraw.clear();
sxraw.clear();
syraw.clear();
szraw.clear();
fitparams.clear();
//elsdata = true;
readraw = true;
continue;
}
if(elsdata && firstName.contains("Y_Position")){
System.out.println("Found Y for ELS");
elsx = false;
elsy = true;
continue;
}
if(firstName.startsWith("---")) continue ;
if(harpdata==true){
if((tokens[0]).length()!=0){ //Skip blank lines
if(firstName.startsWith("PVLogger")){
try{
PVLoggerID = new Integer(Integer.parseInt(tokens[2]));
}
catch(NumberFormatException e){
}
}
else{
sxraw.add(new Double(Double.parseDouble(tokens[0])));
xraw.add(new Double(Double.parseDouble(tokens[1])));
syraw.add(new Double(Double.parseDouble(tokens[2])));
yraw.add(new Double(Double.parseDouble(tokens[3])));
szraw.add(new Double(Double.parseDouble(tokens[4])));
zraw.add(new Double(Double.parseDouble(tokens[5])));
}
}
continue;
}
if(elsdata==true){
if(elsx == true){
if((tokens[0]).length()!=0){ //Skip blank lines
sxraw.add(new Double(Double.parseDouble(tokens[0])));
xraw.add(new Double(Double.parseDouble(tokens[1])));
}
}
if(elsy == true){
if((tokens[0]).length()!=0){ //Skip blank lines
syraw.add(new Double(Double.parseDouble(tokens[0])));
yraw.add(new Double(Double.parseDouble(tokens[1])));
szraw.add(new Double(0.0));
zraw.add(new Double(0.0));
}
}
continue;
}
if(readraw && (!zerodata) && (!baddata) ){
if(tokens.length == 7){
sraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
sxraw.add(new Double(Double.parseDouble(tokens[4])));
syraw.add(new Double(Double.parseDouble(tokens[5])));
szraw.add(new Double(Double.parseDouble(tokens[6])));
yraw.add(new Double(Double.parseDouble(tokens[1])));
zraw.add(new Double(Double.parseDouble(tokens[2])));
xraw.add(new Double(Double.parseDouble(tokens[3])));
}
else{
sraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
sxraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
syraw.add(new Double(Double.parseDouble(tokens[0])/Math.sqrt(2.0)));
szraw.add(new Double(Double.parseDouble(tokens[0])));
yraw.add(new Double(Double.parseDouble(tokens[1])));
zraw.add(new Double(Double.parseDouble(tokens[2])));
xraw.add(new Double(Double.parseDouble(tokens[3])));
}
}
if(firstName.startsWith("PVLogger")){
try{
PVLoggerID = new Integer(Integer.parseInt(tokens[2]));
}
catch(NumberFormatException e){
}
}
}
dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw);
//writeData();
wiredata.add(PVLoggerID);
return wiredata;
}
private void dumpData(String label, ArrayList<Double> fitparams, ArrayList<Double> sraw, ArrayList<Double> sxraw, ArrayList<Double> syraw, ArrayList<Double> szraw, ArrayList<Double> yraw, ArrayList<Double> zraw, ArrayList<Double> xraw){
HashMap<String,Object> data = new HashMap<String, Object>();
data.put("name", label);
data.put("fitparams", new ArrayList<Double>(fitparams));
data.put("sdata", new ArrayList<Double>(sraw));
data.put("sxdata", new ArrayList<Double>(sxraw));
data.put("sydata", new ArrayList<Double>(syraw));
data.put("szdata", new ArrayList<Double>(szraw));
data.put("xdata", new ArrayList<Double>(xraw));
data.put("ydata", new ArrayList<Double>(yraw));
data.put("zdata", new ArrayList<Double>(zraw));
wiredata.add((HashMap)data);
}
@SuppressWarnings ("unchecked") //Had to suppress because wiredata holds multiple types.
private void writeData(){
//This is just a routine to write out the current data set.
Iterator<Object> itr = wiredata.iterator();
while(itr.hasNext()){
HashMap<String, ArrayList<Double>> map = (HashMap<String, ArrayList<Double>>)itr.next();
ArrayList<Double> fitlist = map.get("fitparams");
ArrayList<Double> slist = map.get("sdata");
ArrayList<Double> ylist = map.get("ydata");
ArrayList<Double> zlist = map.get("zdata");
ArrayList<Double> xlist = map.get("xdata");
int ssize = slist.size();
int xsize = xlist.size();
int ysize = ylist.size();
int zsize = zlist.size();
System.out.println("This is " + map.get("name"));
System.out.println("With fit params " + fitlist.get(0) + " " + fitlist.get (1) + " " +fitlist.get(2));
if((ssize == xsize ) && (xsize == ysize) && (ysize == zsize)){
for(int i = 0; i<ssize; i++){
System.out.println(slist.get(i) + " " + ylist.get(i) + " " + zlist.get(i) + " " + xlist.get(i));
}
}
else{
System.out.println("Oops, a problem with array sizing.");
System.out.println(ssize + " " + xsize + " " + ysize + " " + zsize);
}
}
}
}
|
Remove commented code that doesn’t belong.
|
apps/wireanalysis/src/xal/app/wireanalysis/ParseWireFile.java
|
Remove commented code that doesn’t belong.
|
<ide><path>pps/wireanalysis/src/xal/app/wireanalysis/ParseWireFile.java
<ide> ArrayList<Double> szraw = new ArrayList<Double>();
<ide>
<ide> //Open the file.
<del> //URL url = getClass().getResource(filename);
<ide>
<ide> URL url = newfile.toURI().toURL();
<ide>
|
|
JavaScript
|
mit
|
66b4d70fb0d35175f7130b2bfb4e4a7fd8e2903f
| 0 |
TristanVALCKE/three.js,WestLangley/three.js,stanford-gfx/three.js,Liuer/three.js,Liuer/three.js,kaisalmen/three.js,Samsy/three.js,TristanVALCKE/three.js,jpweeks/three.js,donmccurdy/three.js,Samsy/three.js,fraguada/three.js,Itee/three.js,aardgoose/three.js,looeee/three.js,WestLangley/three.js,zhoushijie163/three.js,06wj/three.js,kaisalmen/three.js,greggman/three.js,TristanVALCKE/three.js,TristanVALCKE/three.js,TristanVALCKE/three.js,fraguada/three.js,Itee/three.js,stanford-gfx/three.js,looeee/three.js,06wj/three.js,gero3/three.js,Samsy/three.js,donmccurdy/three.js,greggman/three.js,TristanVALCKE/three.js,Samsy/three.js,fraguada/three.js,zhoushijie163/three.js,aardgoose/three.js,Samsy/three.js,gero3/three.js,fyoudine/three.js,fraguada/three.js,Samsy/three.js,fraguada/three.js,mrdoob/three.js,fraguada/three.js,fyoudine/three.js,jpweeks/three.js,mrdoob/three.js,makc/three.js.fork,makc/three.js.fork
|
import { Color } from '../math/Color.js';
import { Vector2 } from '../math/Vector2.js';
import { Vector3 } from '../math/Vector3.js';
import { Vector4 } from '../math/Vector4.js';
import { Matrix3 } from '../math/Matrix3.js';
import { Matrix4 } from '../math/Matrix4.js';
import { FileLoader } from './FileLoader.js';
import { Loader } from './Loader.js';
import * as Materials from '../materials/Materials.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function MaterialLoader( manager ) {
Loader.call( this, manager );
this.textures = {};
}
MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: MaterialLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( JSON.parse( text ) ) );
}, onProgress, onError );
},
parse: function ( json ) {
var textures = this.textures;
function getTexture( name ) {
if ( textures[ name ] === undefined ) {
console.warn( 'THREE.MaterialLoader: Undefined texture', name );
}
return textures[ name ];
}
var material = new Materials[ json.type ]();
if ( json.uuid !== undefined ) material.uuid = json.uuid;
if ( json.name !== undefined ) material.name = json.name;
if ( json.color !== undefined ) material.color.setHex( json.color );
if ( json.roughness !== undefined ) material.roughness = json.roughness;
if ( json.metalness !== undefined ) material.metalness = json.metalness;
if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
if ( json.specular !== undefined ) material.specular.setHex( json.specular );
if ( json.shininess !== undefined ) material.shininess = json.shininess;
if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
if ( json.fog !== undefined ) material.fog = json.fog;
if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
if ( json.blending !== undefined ) material.blending = json.blending;
if ( json.combine !== undefined ) material.combine = json.combine;
if ( json.side !== undefined ) material.side = json.side;
if ( json.opacity !== undefined ) material.opacity = json.opacity;
if ( json.transparent !== undefined ) material.transparent = json.transparent;
if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
if ( json.rotation !== undefined ) material.rotation = json.rotation;
if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
if ( json.scale !== undefined ) material.scale = json.scale;
if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
if ( json.skinning !== undefined ) material.skinning = json.skinning;
if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
if ( json.dithering !== undefined ) material.dithering = json.dithering;
if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
if ( json.visible !== undefined ) material.visible = json.visible;
if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
if ( json.userData !== undefined ) material.userData = json.userData;
if ( json.vertexColors !== undefined ) {
if ( typeof json.vertexColors === 'number' ) {
material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
} else {
material.vertexColors = json.vertexColors;
}
}
// Shader Material
if ( json.uniforms !== undefined ) {
for ( var name in json.uniforms ) {
var uniform = json.uniforms[ name ];
material.uniforms[ name ] = {};
switch ( uniform.type ) {
case 't':
material.uniforms[ name ].value = getTexture( uniform.value );
break;
case 'c':
material.uniforms[ name ].value = new Color().setHex( uniform.value );
break;
case 'v2':
material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
break;
case 'v3':
material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
break;
case 'v4':
material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
break;
case 'm3':
material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
case 'm4':
material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
break;
default:
material.uniforms[ name ].value = uniform.value;
}
}
}
if ( json.defines !== undefined ) material.defines = json.defines;
if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
if ( json.extensions !== undefined ) {
for ( var key in json.extensions ) {
material.extensions[ key ] = json.extensions[ key ];
}
}
// Deprecated
if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
// for PointsMaterial
if ( json.size !== undefined ) material.size = json.size;
if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
// maps
if ( json.map !== undefined ) material.map = getTexture( json.map );
if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
if ( json.normalScale !== undefined ) {
var normalScale = json.normalScale;
if ( Array.isArray( normalScale ) === false ) {
// Blender exporter used to export a scalar. See #7459
normalScale = [ normalScale, normalScale ];
}
material.normalScale = new Vector2().fromArray( normalScale );
}
if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
return material;
},
setTextures: function ( value ) {
this.textures = value;
return this;
}
} );
export { MaterialLoader };
|
src/loaders/MaterialLoader.js
|
import { Color } from '../math/Color.js';
import { Vector2 } from '../math/Vector2.js';
import { Vector3 } from '../math/Vector3.js';
import { Vector4 } from '../math/Vector4.js';
import { Matrix3 } from '../math/Matrix3.js';
import { Matrix4 } from '../math/Matrix4.js';
import { FileLoader } from './FileLoader.js';
import { Loader } from './Loader.js';
import * as Materials from '../materials/Materials.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function MaterialLoader( manager ) {
Loader.call( this, manager );
this.textures = {};
}
MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: MaterialLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.load( url, function ( text ) {
onLoad( scope.parse( JSON.parse( text ) ) );
}, onProgress, onError );
},
parse: function ( json ) {
var textures = this.textures;
function getTexture( name ) {
if ( textures[ name ] === undefined ) {
console.warn( 'THREE.MaterialLoader: Undefined texture', name );
}
return textures[ name ];
}
var material = new Materials[ json.type ]();
if ( json.uuid !== undefined ) material.uuid = json.uuid;
if ( json.name !== undefined ) material.name = json.name;
if ( json.color !== undefined ) material.color.setHex( json.color );
if ( json.roughness !== undefined ) material.roughness = json.roughness;
if ( json.metalness !== undefined ) material.metalness = json.metalness;
if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
if ( json.specular !== undefined ) material.specular.setHex( json.specular );
if ( json.shininess !== undefined ) material.shininess = json.shininess;
if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
if ( json.fog !== undefined ) material.fog = json.fog;
if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
if ( json.blending !== undefined ) material.blending = json.blending;
if ( json.combine !== undefined ) material.combine = json.combine;
if ( json.side !== undefined ) material.side = json.side;
if ( json.opacity !== undefined ) material.opacity = json.opacity;
if ( json.transparent !== undefined ) material.transparent = json.transparent;
if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
if ( json.rotation !== undefined ) material.rotation = json.rotation;
if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
if ( json.scale !== undefined ) material.scale = json.scale;
if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
if ( json.skinning !== undefined ) material.skinning = json.skinning;
if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
if ( json.dithering !== undefined ) material.dithering = json.dithering;
if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
if ( json.visible !== undefined ) material.visible = json.visible;
if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
if ( json.userData !== undefined ) material.userData = json.userData;
if ( json.vertexColors !== undefined ) {
if ( typeof json.vertexColors === 'number' ) {
material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
} else {
material.vertexColors = json.vertexColors;
}
}
// Shader Material
if ( json.uniforms !== undefined ) {
for ( var name in json.uniforms ) {
var uniform = json.uniforms[ name ];
material.uniforms[ name ] = {};
switch ( uniform.type ) {
case 't':
material.uniforms[ name ].value = getTexture( uniform.value );
break;
case 'c':
material.uniforms[ name ].value = new Color().setHex( uniform.value );
break;
case 'v2':
material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
break;
case 'v3':
material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
break;
case 'v4':
material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
break;
case 'm3':
material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
case 'm4':
material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
break;
default:
material.uniforms[ name ].value = uniform.value;
}
}
}
if ( json.defines !== undefined ) material.defines = json.defines;
if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
if ( json.extensions !== undefined ) {
for ( var key in json.extensions ) {
material.extensions[ key ] = json.extensions[ key ];
}
}
// Deprecated
if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
// for PointsMaterial
if ( json.size !== undefined ) material.size = json.size;
if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
// maps
if ( json.map !== undefined ) material.map = getTexture( json.map );
if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
if ( json.alphaMap !== undefined ) {
material.alphaMap = getTexture( json.alphaMap );
material.transparent = true;
}
if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
if ( json.normalScale !== undefined ) {
var normalScale = json.normalScale;
if ( Array.isArray( normalScale ) === false ) {
// Blender exporter used to export a scalar. See #7459
normalScale = [ normalScale, normalScale ];
}
material.normalScale = new Vector2().fromArray( normalScale );
}
if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
return material;
},
setTextures: function ( value ) {
this.textures = value;
return this;
}
} );
export { MaterialLoader };
|
remove transparent based on alphaMap #18705
|
src/loaders/MaterialLoader.js
|
remove transparent based on alphaMap #18705
|
<ide><path>rc/loaders/MaterialLoader.js
<ide> if ( json.map !== undefined ) material.map = getTexture( json.map );
<ide> if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
<ide>
<del> if ( json.alphaMap !== undefined ) {
<del>
<del> material.alphaMap = getTexture( json.alphaMap );
<del> material.transparent = true;
<del>
<del> }
<add> if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
<ide>
<ide> if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
<ide> if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
|
|
Java
|
agpl-3.0
|
e839e3f60d2eb36366ceb2ebc0bf0dee50907abb
| 0 |
DJmaxZPL4Y/Photon-Server
|
package org.mcphoton.impl.server;
import com.electronwill.utils.SimpleBag;
import java.net.InetSocketAddress;
import java.security.KeyPair;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.mcphoton.Photon;
import org.mcphoton.entity.living.player.Player;
import org.mcphoton.impl.command.StopCommand;
import org.mcphoton.impl.network.NetworkInputThread;
import org.mcphoton.impl.network.NetworkOutputThread;
import org.mcphoton.impl.network.PhotonPacketsManager;
import org.mcphoton.server.BansManager;
import org.mcphoton.server.Server;
import org.mcphoton.server.WhitelistManager;
import org.mcphoton.world.Location;
import org.mcphoton.world.World;
import org.slf4j.impl.LoggingService;
import org.slf4j.impl.PhotonLogger;
/**
* The game server.
*
* @author TheElectronWill
*
*/
public final class PhotonServer implements Server {
public final PhotonLogger logger;
public final KeyPair keyPair;
public final InetSocketAddress address;
public final NetworkInputThread networkInputThread;
public final NetworkOutputThread networkOutputThread;
public final ConsoleThread consoleThread = new ConsoleThread();
public final PhotonPacketsManager packetsManager = new PhotonPacketsManager(this);
public final PhotonBansManager bansManager = new PhotonBansManager();
public final PhotonWhitelistManager whitelistManager = new PhotonWhitelistManager();
public volatile String motd;
public final Collection<Player> onlinePlayers = new SimpleBag<>();
public volatile int maxPlayers;
public final Map<String, World> worlds = new ConcurrentHashMap<>();
public volatile Location spawn;
public PhotonServer(PhotonLogger logger, KeyPair keyPair, InetSocketAddress address, NetworkInputThread networkInputThread, NetworkOutputThread networkOutputThread, String motd, int maxPlayers, Location spawn) {
this.logger = logger;
this.keyPair = keyPair;
this.address = address;
this.networkInputThread = networkInputThread;
this.networkOutputThread = networkOutputThread;
this.motd = motd;
this.maxPlayers = maxPlayers;
this.spawn = spawn;
}
void startThreads() {
logger.info("Starting threads");
consoleThread.start();
networkInputThread.start();
networkOutputThread.start();
}
void setShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
logger.info("Stopping threads");
consoleThread.stopNicely();
networkInputThread.stopNicely();
networkOutputThread.stopNicely();
try {
networkInputThread.join(1000);
networkOutputThread.join(1000);
} catch (InterruptedException ex) {
logger.error("Unable to stop the network threads in an acceptable time", ex);
logger.warn("The network threads will be forcibly stopped!");
networkInputThread.stop();
networkOutputThread.stop();
} finally {
LoggingService.close();
}
}));
}
void registerCommands() {
logger.info("Registering photon commands");
Photon.getCommandsRegistry().register(new StopCommand(), null);
}
void registerPackets() {
logger.info("Registering game packets");
packetsManager.registerGamePackets();
}
@Override
public Collection<Player> getOnlinePlayers() {
return Collections.unmodifiableCollection(onlinePlayers);
}
@Override
public int getMaxPlayers() {
return maxPlayers;
}
@Override
public Player getPlayer(UUID id) {
for (Player p : onlinePlayers) {
if (p.getAccountId().equals(id)) {
return p;
}
}
return null;
}
@Override
public Player getPlayer(String name) {
for (Player p : onlinePlayers) {
if (p.getName().equals(name)) {
return p;
}
}
return null;
}
@Override
public BansManager getBansManager() {
return bansManager;
}
@Override
public WhitelistManager getWhitelistManager() {
return whitelistManager;
}
@Override
public InetSocketAddress getBoundAddress() {
return address;
}
@Override
public boolean isOnlineMode() {
return true;
}
@Override
public Collection<World> getWorlds() {
return Collections.unmodifiableCollection(worlds.values());
}
@Override
public World getWorld(String name) {
return worlds.get(name);
}
@Override
public void registerWorld(World w) {
worlds.put(w.getName(), w);
}
@Override
public void unregisterWorld(World w) {
worlds.remove(w.getName());
}
@Override
public Location getSpawn() {
return spawn;
}
@Override
public void setSpawn(Location spawn) {
this.spawn = spawn;
}
}
|
src/main/java/org/mcphoton/impl/server/PhotonServer.java
|
package org.mcphoton.impl.server;
import com.electronwill.utils.SimpleBag;
import java.net.InetSocketAddress;
import java.security.KeyPair;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.mcphoton.Photon;
import org.mcphoton.entity.living.player.Player;
import org.mcphoton.impl.command.StopCommand;
import org.mcphoton.impl.network.NetworkInputThread;
import org.mcphoton.impl.network.NetworkOutputThread;
import org.mcphoton.impl.network.PhotonPacketsManager;
import org.mcphoton.server.BansManager;
import org.mcphoton.server.Server;
import org.mcphoton.server.WhitelistManager;
import org.mcphoton.world.Location;
import org.mcphoton.world.World;
import org.slf4j.impl.LoggingService;
import org.slf4j.impl.PhotonLogger;
/**
* The game server.
*
* @author TheElectronWill
*
*/
public final class PhotonServer implements Server {
public final PhotonLogger logger;
public final KeyPair keyPair;
public final InetSocketAddress address;
public final NetworkInputThread networkInputThread;
public final NetworkOutputThread networkOutputThread;
public final ConsoleThread consoleThread = new ConsoleThread();
public final PhotonPacketsManager packetsManager = new PhotonPacketsManager(this);
public volatile String motd;
public final Collection<Player> onlinePlayers = new SimpleBag<>();
public volatile int maxPlayers;
public final Map<String, World> worlds = new ConcurrentHashMap<>();
public volatile Location spawn;
public PhotonServer(PhotonLogger logger, KeyPair keyPair, InetSocketAddress address, NetworkInputThread networkInputThread, NetworkOutputThread networkOutputThread, String motd, int maxPlayers, Location spawn) {
this.logger = logger;
this.keyPair = keyPair;
this.address = address;
this.networkInputThread = networkInputThread;
this.networkOutputThread = networkOutputThread;
this.motd = motd;
this.maxPlayers = maxPlayers;
this.spawn = spawn;
}
void startThreads() {
logger.info("Starting threads");
consoleThread.start();
networkInputThread.start();
networkOutputThread.start();
}
void setShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
logger.info("Stopping threads");
consoleThread.stopNicely();
networkInputThread.stopNicely();
networkOutputThread.stopNicely();
try {
networkInputThread.join(1000);
networkOutputThread.join(1000);
} catch (InterruptedException ex) {
logger.error("Unable to stop the network threads in an acceptable time", ex);
logger.warn("The network threads will be forcibly stopped!");
networkInputThread.stop();
networkOutputThread.stop();
} finally {
LoggingService.close();
}
}));
}
void registerCommands() {
logger.info("Registering photon commands");
Photon.getCommandsRegistry().register(new StopCommand(), null);
}
void registerPackets() {
logger.info("Registering game packets");
packetsManager.registerGamePackets();
}
@Override
public Collection<Player> getOnlinePlayers() {
return Collections.unmodifiableCollection(onlinePlayers);
}
@Override
public int getMaxPlayers() {
return maxPlayers;
}
@Override
public Player getPlayer(UUID id) {
for (Player p : onlinePlayers) {
if (p.getAccountId().equals(id)) {
return p;
}
}
return null;
}
@Override
public Player getPlayer(String name) {
for (Player p : onlinePlayers) {
if (p.getName().equals(name)) {
return p;
}
}
return null;
}
@Override
public BansManager getBansManager() {
return null;//TODO
}
@Override
public WhitelistManager getWhitelistManager() {
return null; //TODO
}
@Override
public InetSocketAddress getBoundAddress() {
return address;
}
@Override
public boolean isOnlineMode() {
return true;
}
@Override
public Collection<World> getWorlds() {
return Collections.unmodifiableCollection(worlds.values());
}
@Override
public World getWorld(String name) {
return worlds.get(name);
}
@Override
public void registerWorld(World w) {
worlds.put(w.getName(), w);
}
@Override
public void unregisterWorld(World w) {
worlds.remove(w.getName());
}
@Override
public Location getSpawn() {
return spawn;
}
@Override
public void setSpawn(Location spawn) {
this.spawn = spawn;
}
}
|
Create bans and whitelist manager instances + implement getters
|
src/main/java/org/mcphoton/impl/server/PhotonServer.java
|
Create bans and whitelist manager instances + implement getters
|
<ide><path>rc/main/java/org/mcphoton/impl/server/PhotonServer.java
<ide> public final NetworkOutputThread networkOutputThread;
<ide> public final ConsoleThread consoleThread = new ConsoleThread();
<ide> public final PhotonPacketsManager packetsManager = new PhotonPacketsManager(this);
<add> public final PhotonBansManager bansManager = new PhotonBansManager();
<add> public final PhotonWhitelistManager whitelistManager = new PhotonWhitelistManager();
<ide>
<ide> public volatile String motd;
<ide>
<ide>
<ide> @Override
<ide> public BansManager getBansManager() {
<del> return null;//TODO
<add> return bansManager;
<ide> }
<ide>
<ide> @Override
<ide> public WhitelistManager getWhitelistManager() {
<del> return null; //TODO
<add> return whitelistManager;
<ide> }
<ide>
<ide> @Override
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.