diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/android/src/com/google/zxing/client/android/ViewfinderView.java b/android/src/com/google/zxing/client/android/ViewfinderView.java
index 8a52ba9c..fe70351e 100755
--- a/android/src/com/google/zxing/client/android/ViewfinderView.java
+++ b/android/src/com/google/zxing/client/android/ViewfinderView.java
@@ -1,188 +1,192 @@
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.camera.CameraManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial
* transparency outside it, as well as the laser scanner animation and result points.
*
* @author [email protected] (Daniel Switkin)
*/
public final class ViewfinderView extends View {
private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64};
private static final long ANIMATION_DELAY = 80L;
private static final int CURRENT_POINT_OPACITY = 0xA0;
private static final int MAX_RESULT_POINTS = 20;
private static final int POINT_SIZE = 6;
private final Paint paint;
private Bitmap resultBitmap;
private final int maskColor;
private final int resultColor;
private final int frameColor;
private final int laserColor;
private final int resultPointColor;
private int scannerAlpha;
private List<ResultPoint> possibleResultPoints;
private List<ResultPoint> lastPossibleResultPoints;
// This constructor is used when the class is built from an XML resource.
public ViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
// Initialize these once for performance rather than calling them every time in onDraw().
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Resources resources = getResources();
maskColor = resources.getColor(R.color.viewfinder_mask);
resultColor = resources.getColor(R.color.result_view);
frameColor = resources.getColor(R.color.viewfinder_frame);
laserColor = resources.getColor(R.color.viewfinder_laser);
resultPointColor = resources.getColor(R.color.possible_result_points);
scannerAlpha = 0;
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = null;
}
@Override
public void onDraw(Canvas canvas) {
- Rect frame = CameraManager.get().getFramingRect();
+ CameraManager cameraManager = CameraManager.get();
+ if (cameraManager == null) {
+ return;
+ }
+ Rect frame = cameraManager.getFramingRect();
if (frame == null) {
return;
}
int width = canvas.getWidth();
int height = canvas.getHeight();
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(CURRENT_POINT_OPACITY);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
// Draw a two pixel solid black border inside the framing rect
paint.setColor(frameColor);
canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);
// Draw a red "laser scanner" line through the middle to show decoding is active
paint.setColor(laserColor);
paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
int middle = frame.height() / 2 + frame.top;
canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint);
- Rect previewFrame = CameraManager.get().getFramingRectInPreview();
+ Rect previewFrame = cameraManager.getFramingRectInPreview();
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
List<ResultPoint> currentPossible = possibleResultPoints;
List<ResultPoint> currentLast = lastPossibleResultPoints;
int frameLeft = frame.left;
int frameTop = frame.top;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(CURRENT_POINT_OPACITY);
paint.setColor(resultPointColor);
synchronized (currentPossible) {
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE, paint);
}
}
}
if (currentLast != null) {
paint.setAlpha(CURRENT_POINT_OPACITY / 2);
paint.setColor(resultPointColor);
synchronized (currentLast) {
for (ResultPoint point : currentLast) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE / 2, paint);
}
}
}
// Request another update at the animation interval, but only repaint the laser line,
// not the entire viewfinder mask.
postInvalidateDelayed(ANIMATION_DELAY,
frame.left - POINT_SIZE,
frame.top - POINT_SIZE,
frame.right + POINT_SIZE,
frame.bottom + POINT_SIZE);
}
}
public void drawViewfinder() {
Bitmap resultBitmap = this.resultBitmap;
this.resultBitmap = null;
if (resultBitmap != null) {
resultBitmap.recycle();
}
invalidate();
}
/**
* Draw a bitmap with the result points highlighted instead of the live scanning display.
*
* @param barcode An image of the decoded barcode.
*/
public void drawResultBitmap(Bitmap barcode) {
resultBitmap = barcode;
invalidate();
}
public void addPossibleResultPoint(ResultPoint point) {
List<ResultPoint> points = possibleResultPoints;
synchronized (point) {
points.add(point);
int size = points.size();
if (size > MAX_RESULT_POINTS) {
// trim it
points.subList(0, size - MAX_RESULT_POINTS / 2).clear();
}
}
}
}
| false | true | public void onDraw(Canvas canvas) {
Rect frame = CameraManager.get().getFramingRect();
if (frame == null) {
return;
}
int width = canvas.getWidth();
int height = canvas.getHeight();
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(CURRENT_POINT_OPACITY);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
// Draw a two pixel solid black border inside the framing rect
paint.setColor(frameColor);
canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);
// Draw a red "laser scanner" line through the middle to show decoding is active
paint.setColor(laserColor);
paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
int middle = frame.height() / 2 + frame.top;
canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint);
Rect previewFrame = CameraManager.get().getFramingRectInPreview();
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
List<ResultPoint> currentPossible = possibleResultPoints;
List<ResultPoint> currentLast = lastPossibleResultPoints;
int frameLeft = frame.left;
int frameTop = frame.top;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(CURRENT_POINT_OPACITY);
paint.setColor(resultPointColor);
synchronized (currentPossible) {
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE, paint);
}
}
}
if (currentLast != null) {
paint.setAlpha(CURRENT_POINT_OPACITY / 2);
paint.setColor(resultPointColor);
synchronized (currentLast) {
for (ResultPoint point : currentLast) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE / 2, paint);
}
}
}
// Request another update at the animation interval, but only repaint the laser line,
// not the entire viewfinder mask.
postInvalidateDelayed(ANIMATION_DELAY,
frame.left - POINT_SIZE,
frame.top - POINT_SIZE,
frame.right + POINT_SIZE,
frame.bottom + POINT_SIZE);
}
}
| public void onDraw(Canvas canvas) {
CameraManager cameraManager = CameraManager.get();
if (cameraManager == null) {
return;
}
Rect frame = cameraManager.getFramingRect();
if (frame == null) {
return;
}
int width = canvas.getWidth();
int height = canvas.getHeight();
// Draw the exterior (i.e. outside the framing rect) darkened
paint.setColor(resultBitmap != null ? resultColor : maskColor);
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(CURRENT_POINT_OPACITY);
canvas.drawBitmap(resultBitmap, null, frame, paint);
} else {
// Draw a two pixel solid black border inside the framing rect
paint.setColor(frameColor);
canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);
// Draw a red "laser scanner" line through the middle to show decoding is active
paint.setColor(laserColor);
paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);
scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length;
int middle = frame.height() / 2 + frame.top;
canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint);
Rect previewFrame = cameraManager.getFramingRectInPreview();
float scaleX = frame.width() / (float) previewFrame.width();
float scaleY = frame.height() / (float) previewFrame.height();
List<ResultPoint> currentPossible = possibleResultPoints;
List<ResultPoint> currentLast = lastPossibleResultPoints;
int frameLeft = frame.left;
int frameTop = frame.top;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new ArrayList<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(CURRENT_POINT_OPACITY);
paint.setColor(resultPointColor);
synchronized (currentPossible) {
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE, paint);
}
}
}
if (currentLast != null) {
paint.setAlpha(CURRENT_POINT_OPACITY / 2);
paint.setColor(resultPointColor);
synchronized (currentLast) {
for (ResultPoint point : currentLast) {
canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
frameTop + (int) (point.getY() * scaleY),
POINT_SIZE / 2, paint);
}
}
}
// Request another update at the animation interval, but only repaint the laser line,
// not the entire viewfinder mask.
postInvalidateDelayed(ANIMATION_DELAY,
frame.left - POINT_SIZE,
frame.top - POINT_SIZE,
frame.right + POINT_SIZE,
frame.bottom + POINT_SIZE);
}
}
|
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java
index d9a04eeae..4512c15ca 100644
--- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java
+++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java
@@ -1,198 +1,197 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia and others.
* 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
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.bugs.java;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Comment;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.TextElement;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.java.ui.editor.AbstractMylarHyperlinkDetector;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* @author Shawn Minto
*
*/
public class BugzillaHyperLinkDetector extends AbstractMylarHyperlinkDetector {
public BugzillaHyperLinkDetector() {
super();
}
@SuppressWarnings("unchecked")
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor = getEditor();
if (region == null || textEditor == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor))
return null;
IEditorSite site= textEditor.getEditorSite();
if (site == null)
return null;
IJavaElement javaElement= getInputJavaElement(textEditor);
if (javaElement == null)
return null;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null);
if (ast == null)
return null;
ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
if (node == null || !(node instanceof TextElement || node instanceof Block))
return null;
String comment = null;
int commentStart = -1;
if(node instanceof TextElement){
TextElement element = (TextElement)node;
comment = element.getText();
commentStart = element.getStartPosition();
} else if(node instanceof Block){
Comment c = findComment(ast.getCommentList(), region.getOffset(), 1);
if(c != null){
try{
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
String commentString = document.get(c.getStartPosition(), c.getLength());
comment = getStringFromComment(c, region.getOffset(), commentString);
commentStart = getLocationFromComment(c, comment, commentString) + c.getStartPosition();
} catch (BadLocationException e){
MylarPlugin.log(e, "Failed to get text for comment");
}
}
}
if(comment == null)
return null;
int startOffset= region.getOffset();
int endOffset= startOffset + region.getLength();
Pattern p = Pattern.compile("^.*bug\\s+\\d+.*");
Matcher m = p.matcher(comment.toLowerCase().trim());
boolean b = m.matches();
p = Pattern.compile("^.*bug#\\s+\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b2 = m.matches();
p = Pattern.compile("^.*bug\\s#\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b3 = m.matches();
p = Pattern.compile("^.*bug#\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b4 = m.matches();
// XXX walk forward from where we are
if(b || b2 || b3 || b4){
int start = comment.toLowerCase().indexOf("bug");
int ahead = 4;
if(b2 || b3 || b4){
int pound = comment.toLowerCase().indexOf("#", start);
ahead = pound - start + 1;
- System.out.println(ahead);
}
String endComment = comment.substring(start+ahead, comment.length());
endComment = endComment.trim();
int endCommentStart = comment.indexOf(endComment);
int end = comment.indexOf(" ", endCommentStart);
if(end == -1)
end = comment.length();
try{
int bugId = Integer.parseInt(comment.substring(endCommentStart, end).trim());
start += commentStart;
end += commentStart;
if(startOffset >= start && endOffset <= end){
IRegion sregion= new Region(start, end-start);
return new IHyperlink[] {new BugzillaHyperLink(sregion, bugId)};
}
} catch (NumberFormatException e){
return null;
}
}
return null;
}
private int getLocationFromComment(Comment c, String commentLine, String commentString) {
if(commentLine == null){
return -1;
} else {
return commentString.indexOf(commentLine);
}
}
private String getStringFromComment(Comment comment, int desiredOffset, String commentString) {
String [] parts = commentString.split("\n");
if(parts.length > 1){
int offset = comment.getStartPosition();
for(String part: parts){
int newOffset = offset + part.length() + 1;
if(desiredOffset >= offset && desiredOffset <= newOffset){
return part;
}
}
} else {
return commentString;
}
return null;
}
private Comment findComment(List<Comment> commentList, int offset, int i) {
for(Comment comment: commentList){
if(comment.getStartPosition() <= offset && (comment.getStartPosition() + comment.getLength() >= offset + i)){
return comment;
}
}
return null;
}
private IJavaElement getInputJavaElement(ITextEditor editor) {
IEditorInput editorInput= editor.getEditorInput();
if (editorInput instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)editorInput).getClassFile();
if (editor instanceof CompilationUnitEditor)
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput);
return null;
}
}
| true | true | public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor = getEditor();
if (region == null || textEditor == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor))
return null;
IEditorSite site= textEditor.getEditorSite();
if (site == null)
return null;
IJavaElement javaElement= getInputJavaElement(textEditor);
if (javaElement == null)
return null;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null);
if (ast == null)
return null;
ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
if (node == null || !(node instanceof TextElement || node instanceof Block))
return null;
String comment = null;
int commentStart = -1;
if(node instanceof TextElement){
TextElement element = (TextElement)node;
comment = element.getText();
commentStart = element.getStartPosition();
} else if(node instanceof Block){
Comment c = findComment(ast.getCommentList(), region.getOffset(), 1);
if(c != null){
try{
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
String commentString = document.get(c.getStartPosition(), c.getLength());
comment = getStringFromComment(c, region.getOffset(), commentString);
commentStart = getLocationFromComment(c, comment, commentString) + c.getStartPosition();
} catch (BadLocationException e){
MylarPlugin.log(e, "Failed to get text for comment");
}
}
}
if(comment == null)
return null;
int startOffset= region.getOffset();
int endOffset= startOffset + region.getLength();
Pattern p = Pattern.compile("^.*bug\\s+\\d+.*");
Matcher m = p.matcher(comment.toLowerCase().trim());
boolean b = m.matches();
p = Pattern.compile("^.*bug#\\s+\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b2 = m.matches();
p = Pattern.compile("^.*bug\\s#\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b3 = m.matches();
p = Pattern.compile("^.*bug#\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b4 = m.matches();
// XXX walk forward from where we are
if(b || b2 || b3 || b4){
int start = comment.toLowerCase().indexOf("bug");
int ahead = 4;
if(b2 || b3 || b4){
int pound = comment.toLowerCase().indexOf("#", start);
ahead = pound - start + 1;
System.out.println(ahead);
}
String endComment = comment.substring(start+ahead, comment.length());
endComment = endComment.trim();
int endCommentStart = comment.indexOf(endComment);
int end = comment.indexOf(" ", endCommentStart);
if(end == -1)
end = comment.length();
try{
int bugId = Integer.parseInt(comment.substring(endCommentStart, end).trim());
start += commentStart;
end += commentStart;
if(startOffset >= start && endOffset <= end){
IRegion sregion= new Region(start, end-start);
return new IHyperlink[] {new BugzillaHyperLink(sregion, bugId)};
}
} catch (NumberFormatException e){
return null;
}
}
return null;
}
| public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
ITextEditor textEditor = getEditor();
if (region == null || textEditor == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor))
return null;
IEditorSite site= textEditor.getEditorSite();
if (site == null)
return null;
IJavaElement javaElement= getInputJavaElement(textEditor);
if (javaElement == null)
return null;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null);
if (ast == null)
return null;
ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
if (node == null || !(node instanceof TextElement || node instanceof Block))
return null;
String comment = null;
int commentStart = -1;
if(node instanceof TextElement){
TextElement element = (TextElement)node;
comment = element.getText();
commentStart = element.getStartPosition();
} else if(node instanceof Block){
Comment c = findComment(ast.getCommentList(), region.getOffset(), 1);
if(c != null){
try{
IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
String commentString = document.get(c.getStartPosition(), c.getLength());
comment = getStringFromComment(c, region.getOffset(), commentString);
commentStart = getLocationFromComment(c, comment, commentString) + c.getStartPosition();
} catch (BadLocationException e){
MylarPlugin.log(e, "Failed to get text for comment");
}
}
}
if(comment == null)
return null;
int startOffset= region.getOffset();
int endOffset= startOffset + region.getLength();
Pattern p = Pattern.compile("^.*bug\\s+\\d+.*");
Matcher m = p.matcher(comment.toLowerCase().trim());
boolean b = m.matches();
p = Pattern.compile("^.*bug#\\s+\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b2 = m.matches();
p = Pattern.compile("^.*bug\\s#\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b3 = m.matches();
p = Pattern.compile("^.*bug#\\d+.*");
m = p.matcher(comment.toLowerCase().trim());
boolean b4 = m.matches();
// XXX walk forward from where we are
if(b || b2 || b3 || b4){
int start = comment.toLowerCase().indexOf("bug");
int ahead = 4;
if(b2 || b3 || b4){
int pound = comment.toLowerCase().indexOf("#", start);
ahead = pound - start + 1;
}
String endComment = comment.substring(start+ahead, comment.length());
endComment = endComment.trim();
int endCommentStart = comment.indexOf(endComment);
int end = comment.indexOf(" ", endCommentStart);
if(end == -1)
end = comment.length();
try{
int bugId = Integer.parseInt(comment.substring(endCommentStart, end).trim());
start += commentStart;
end += commentStart;
if(startOffset >= start && endOffset <= end){
IRegion sregion= new Region(start, end-start);
return new IHyperlink[] {new BugzillaHyperLink(sregion, bugId)};
}
} catch (NumberFormatException e){
return null;
}
}
return null;
}
|
diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java
index d3ce1c874..cc5c19fbe 100644
--- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java
+++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java
@@ -1,214 +1,218 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.tests.ccvs.core;
import java.io.*;
import junit.extensions.TestSetup;
import junit.framework.Test;
import org.eclipse.core.runtime.*;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.internal.ccvs.core.connection.CVSCommunicationException;
import org.eclipse.team.internal.ccvs.core.connection.CVSRepositoryLocation;
import org.eclipse.team.internal.ccvs.core.util.KnownRepositories;
public class CVSTestSetup extends TestSetup {
public static final String REPOSITORY_LOCATION;
public static final boolean INITIALIZE_REPO;
public static final boolean DEBUG;
public static final boolean LOCAL_REPO;
public static final String RSH;
public static final int WAIT_FACTOR;
public static final int COMPRESSION_LEVEL;
public static final boolean FAIL_IF_EXCEPTION_LOGGED;
public static final boolean RECORD_PROTOCOL_TRAFFIC;
public static final boolean ENSURE_SEQUENTIAL_ACCESS;
public static CVSRepositoryLocation repository;
public static CVSTestLogListener logListener;
// Static initializer for constants
static {
loadProperties();
REPOSITORY_LOCATION = System.getProperty("eclipse.cvs.repository");
INITIALIZE_REPO = Boolean.valueOf(System.getProperty("eclipse.cvs.initrepo", "false")).booleanValue();
DEBUG = Boolean.valueOf(System.getProperty("eclipse.cvs.debug", "false")).booleanValue();
RSH = System.getProperty("eclipse.cvs.rsh", "rsh");
LOCAL_REPO = Boolean.valueOf(System.getProperty("eclipse.cvs.localRepo", "false")).booleanValue();
WAIT_FACTOR = Integer.parseInt(System.getProperty("eclipse.cvs.waitFactor", "1"));
COMPRESSION_LEVEL = Integer.parseInt(System.getProperty("eclipse.cvs.compressionLevel", "0"));
FAIL_IF_EXCEPTION_LOGGED = Boolean.valueOf(System.getProperty("eclipse.cvs.failLog", "true")).booleanValue();
RECORD_PROTOCOL_TRAFFIC = Boolean.valueOf(System.getProperty("eclipse.cvs.recordProtocolTraffic", "false")).booleanValue();
ENSURE_SEQUENTIAL_ACCESS = Boolean.valueOf(System.getProperty("eclipse.cvs.sequentialAccess", "false")).booleanValue();
}
public static void loadProperties() {
String propertiesFile = System.getProperty("eclipse.cvs.properties");
if (propertiesFile == null) return;
File file = new File(propertiesFile);
if (file.isDirectory()) file = new File(file, "repository.properties");
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
for (String line; (line = reader.readLine()) != null; ) {
if (line.startsWith("#")) continue;
int sep = line.indexOf("=");
String property = line.substring(0, sep).trim();
String value = line.substring(sep + 1).trim();
System.setProperty("eclipse.cvs." + property, value);
}
} finally {
reader.close();
}
} catch (Exception e) {
System.err.println("Could not read repository properties file: " + file.getAbsolutePath());
}
}
/**
* Constructor for CVSTestSetup.
*/
public CVSTestSetup(Test test) {
super(test);
}
public static void executeRemoteCommand(ICVSRepositoryLocation repository, String commandLine) {
if (! LOCAL_REPO) {
commandLine = RSH + " " + repository.getHost() + " -l " + repository.getUsername() + " " + commandLine;
}
int returnCode = executeCommand(commandLine, null, null);
if (returnCode != -1 && returnCode != 0) {
System.err.println("Remote command returned " + returnCode + ": " + commandLine);
}
}
/**
* Executes a command.
* Returns the command's return code, or -1 on failure.
*
* @param commandLine the local command line to run
* @param environment the new environment variables, or null to inherit from parent process
* @param workingDirectory the new workingDirectory, or null to inherit from parent process
*/
public static int executeCommand(String commandLine, String[] environment, File workingDirectory) {
PrintStream debugStream = CVSTestSetup.DEBUG ? System.out : null;
try {
if (debugStream != null) {
// while debugging, dump CVS command line client results to stdout
// prefix distinguishes between message source stream
debugStream.println();
printPrefixedLine(debugStream, "CMD> ", commandLine);
if (workingDirectory != null) printPrefixedLine(debugStream, "DIR> ", workingDirectory.toString());
}
Process cvsProcess = Runtime.getRuntime().exec(commandLine, environment, workingDirectory);
// stream output must be dumped to avoid blocking the process or causing a deadlock
startBackgroundPipeThread(cvsProcess.getErrorStream(), debugStream, "ERR> ");
startBackgroundPipeThread(cvsProcess.getInputStream(), debugStream, "MSG> ");
int returnCode = cvsProcess.waitFor();
if (debugStream != null) debugStream.println("RESULT> " + returnCode);
return returnCode;
} catch (IOException e) {
printPrefixedLine(System.err, "Unable to execute command: ", commandLine);
e.printStackTrace(System.err);
} catch (InterruptedException e) {
printPrefixedLine(System.err, "Unable to execute command: ", commandLine);
e.printStackTrace(System.err);
}
return -1;
}
private static void startBackgroundPipeThread(final InputStream is, final PrintStream os,
final String prefix) {
new Thread() {
public void run() {
BufferedReader reader = null;
try {
try {
reader = new BufferedReader(new InputStreamReader(is));
for (;;) {
String line = reader.readLine();
if (line == null) break;
if (os != null) printPrefixedLine(os, prefix, line);
}
} finally {
if (reader != null) reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private static void printPrefixedLine(PrintStream os, String prefix, String line) {
os.print(prefix);
os.println(line.substring(0, Math.min(line.length(), 256))); // trim long lines
}
/*
* Use rsh to delete any contents of the repository and initialize it again
*/
private static void initializeRepository(CVSRepositoryLocation repository) {
String repoRoot = repository.getRootDirectory();
executeRemoteCommand(repository, "rm -rf " + repoRoot);
executeRemoteCommand(repository, "cvs -d " + repoRoot + " init");
}
public void setUp() throws CoreException {
if (repository == null) {
repository = setupRepository(REPOSITORY_LOCATION);
}
CVSProviderPlugin.getPlugin().setCompressionLevel(COMPRESSION_LEVEL);
// Add a log listener so we can ensure that nothing is logged during a test
if (logListener == null) {
logListener = new CVSTestLogListener();
Platform.addLogListener(logListener);
}
}
protected CVSRepositoryLocation setupRepository(String location) throws CVSException {
// Validate that we can connect, also creates and caches the repository location. This
// is important for the UI tests.
CVSRepositoryLocation repository = (CVSRepositoryLocation)KnownRepositories.getInstance().getRepository(location);
KnownRepositories.getInstance().addRepository(repository, false);
repository.setUserAuthenticator(new TestsUserAuthenticator());
// Give some info about which repository the tests are running with
System.out.println("Connecting to: " + repository.getHost() + ":" + repository.getMethod().getName());
try {
try {
repository.validateConnection(new NullProgressMonitor());
} catch (CVSCommunicationException e) {
// Try once more, just in case it is a transient server problem
repository.validateConnection(new NullProgressMonitor());
+ } catch (OperationCanceledException e) {
+ // This can occur if authentication fails
+ throw new CVSException(new CVSStatus(IStatus.ERROR, "The connection was canceled, possibly due to an authentication failure."));
}
} catch (CVSException e) {
System.out.println("Unable to connect to remote repository: " + repository.toString());
+ System.out.println(e.getMessage());
throw e;
}
// Initialize the repo if requested (requires rsh access)
if( INITIALIZE_REPO ) {
initializeRepository(repository);
}
return repository;
}
public void tearDown() throws CVSException {
// Nothing to do here
}
}
| false | true | protected CVSRepositoryLocation setupRepository(String location) throws CVSException {
// Validate that we can connect, also creates and caches the repository location. This
// is important for the UI tests.
CVSRepositoryLocation repository = (CVSRepositoryLocation)KnownRepositories.getInstance().getRepository(location);
KnownRepositories.getInstance().addRepository(repository, false);
repository.setUserAuthenticator(new TestsUserAuthenticator());
// Give some info about which repository the tests are running with
System.out.println("Connecting to: " + repository.getHost() + ":" + repository.getMethod().getName());
try {
try {
repository.validateConnection(new NullProgressMonitor());
} catch (CVSCommunicationException e) {
// Try once more, just in case it is a transient server problem
repository.validateConnection(new NullProgressMonitor());
}
} catch (CVSException e) {
System.out.println("Unable to connect to remote repository: " + repository.toString());
throw e;
}
// Initialize the repo if requested (requires rsh access)
if( INITIALIZE_REPO ) {
initializeRepository(repository);
}
return repository;
}
| protected CVSRepositoryLocation setupRepository(String location) throws CVSException {
// Validate that we can connect, also creates and caches the repository location. This
// is important for the UI tests.
CVSRepositoryLocation repository = (CVSRepositoryLocation)KnownRepositories.getInstance().getRepository(location);
KnownRepositories.getInstance().addRepository(repository, false);
repository.setUserAuthenticator(new TestsUserAuthenticator());
// Give some info about which repository the tests are running with
System.out.println("Connecting to: " + repository.getHost() + ":" + repository.getMethod().getName());
try {
try {
repository.validateConnection(new NullProgressMonitor());
} catch (CVSCommunicationException e) {
// Try once more, just in case it is a transient server problem
repository.validateConnection(new NullProgressMonitor());
} catch (OperationCanceledException e) {
// This can occur if authentication fails
throw new CVSException(new CVSStatus(IStatus.ERROR, "The connection was canceled, possibly due to an authentication failure."));
}
} catch (CVSException e) {
System.out.println("Unable to connect to remote repository: " + repository.toString());
System.out.println(e.getMessage());
throw e;
}
// Initialize the repo if requested (requires rsh access)
if( INITIALIZE_REPO ) {
initializeRepository(repository);
}
return repository;
}
|
diff --git a/CCProbe/source/CCProbe.java b/CCProbe/source/CCProbe.java
index 0ca4294..666a0ea 100644
--- a/CCProbe/source/CCProbe.java
+++ b/CCProbe/source/CCProbe.java
@@ -1,308 +1,312 @@
import waba.ui.*;
import waba.util.*;
import waba.fx.*;
import org.concord.waba.extra.ui.*;
import org.concord.waba.extra.event.*;
import org.concord.LabBook.*;
import org.concord.CCProbe.*;
public class CCProbe extends MainView
implements DialogListener
{
LabBookSession mainSession;
Menu edit;
Title title;
int yOffset = 0;
int newIndex = 0;
String aboutTitle = "About CCProbe";
String [] creationTypes = {"Folder", "Notes", "Data Collector",
"Drawing","UnitConvertor","Image"};
String [] palmFileStrings = {"Beam LabBook", aboutTitle};
String [] javaFileStrings = {aboutTitle, "Serial Port Setup..", "-",
"Exit"};
String [] ceFileStrings = {aboutTitle, "-", "Exit"};
int []creationID = {0x00010100};
public void onStart()
{
super.onStart();
LObjDictionary loDict = null;
LabBook.registerFactory(new DataObjFactory());
// Dialog.showImages = false;
// ImagePane.showImages = false;
graph.Bin.START_DATA_SIZE = 25000;
graph.LargeFloatArray.MaxNumChunks = 25;
int dictHeight = myHeight;
LabBookDB lbDB;
String plat = waba.sys.Vm.getPlatform();
if(plat.equals("PalmOS")){
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
GraphSettings.MAX_COLLECTIONS = 1;
graph.GraphViewLine.scrollStepSize = 0.45f;
lbDB = new LabBookCatalog("LabBook");
CCTextArea.INTER_LINE_SPACING = 0;
+ Dialog.showImages = false;
} else if(plat.equals("Java")){
/*
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
*/
// GraphSettings.MAX_COLLECTIONS = 1;
- lbDB = new LabBookCatalog("LabBook");
- // lbDB = new LabBookFile("LabBook");
+ // lbDB = new LabBookCatalog("LabBook");
+ // Dialog.showImages = false;
+ lbDB = new LabBookFile("LabBook");
} else {
lbDB = new LabBookFile("LabBook");
GraphSettings.MAX_COLLECTIONS = 4;
}
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
if(lbDB.getError()){
// Error;
exit(0);
}
if(plat.equals("PalmOS")){
addFileMenuItems(palmFileStrings, null);
} else if(plat.equals("Java")){
addFileMenuItems(javaFileStrings, null);
} else {
addFileMenuItems(ceFileStrings, null);
}
Debug.println("Openning");
labBook.open(lbDB);
LabObjectPtr rootPtr = labBook.getRoot();
mainSession = rootPtr.getSession();
loDict = (LObjDictionary)mainSession.getObj(rootPtr);
if(loDict == null){
loDict = DefaultFactory.createDictionary();
loDict.setName("Home");
mainSession.storeNew(loDict);
labBook.store(loDict);
}
LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession);
view.setRect(x,yOffset,width,dictHeight);
view.setShowMenus(true);
me.add(view);
lObjView = view;
newIndex = loDict.getChildCount();
- ((LObjDictionaryView)view).checkForBeam();
+ if(plat.equals("PalmOS")){
+ ((LObjDictionaryView)view).checkForBeam();
+ }
}
public String [] getCreateNames()
{
String []createNames = creationTypes;
if(creationID != null){
for(int i = 0; i < creationID.length; i++){
int factoryType = (creationID[i] & 0xFFFF0000);
factoryType >>>= 16;
int objID = creationID[i] & 0xFFFF;
LabObjectFactory factory = null;
for(int f = 0; f < LabBook.objFactories.length; f++){
if(LabBook.objFactories[f] == null) continue;
if(LabBook.objFactories[f].getFactoryType() == factoryType){
factory = LabBook.objFactories[f];
break;
}
}
if(factory != null){
LabObjDescriptor []desc = factory.getLabBookObjDesc();
if(desc != null){
for(int d = 0; d < desc.length; d++){
if(desc[d] == null) continue;
if(desc[d].objType == objID){
String name = desc[d].name;
if(name != null){
String []newNames = new String[createNames.length+1];
waba.sys.Vm.copyArray(createNames,0,newNames,0,createNames.length);
newNames[createNames.length] = name;
createNames = newNames;
}
}
}
}
}
}
}
return createNames;
}
public void createObj(String objType, LObjDictionaryView dView)
{
LabObject newObj = null;
// boolean autoEdit = false;
boolean autoEdit = true;
boolean autoProp = true;
for(int f = 0; f < LabBook.objFactories.length; f++){
if(LabBook.objFactories[f] == null) continue;
LabObjDescriptor []desc = LabBook.objFactories[f].getLabBookObjDesc();
if(desc == null) continue;
boolean doExit = false;
for(int d = 0; d < desc.length; d++){
if(desc[d] == null) continue;
if(objType.equals(desc[d].name)){
newObj = LabBook.objFactories[f].makeNewObj(desc[d].objType);
if(objType.equals("Folder")){
autoEdit = false;
} else if(objType.equals("Data Collector")){
autoEdit = false;
}
doExit = true;
break;
}
}
if(doExit) break;
}
if(newObj != null){
dView.getSession().storeNew(newObj);
if(newIndex == 0){
newObj.setName(objType);
} else {
newObj.setName(objType + " " + newIndex);
}
newIndex++;
dView.insertAtSelected(newObj);
// The order seems to matter here.
// insert and selected for some reason nulls the pointer.
// perhaps by doing a commit?
// newObj.store();
if(autoEdit){
dView.openSelected(true);
} else if(autoProp){
dView.showProperties(newObj);
}
}
}
Dialog beamLBDialog = null;
public void dialogClosed(DialogEvent e)
{
String command = e.getActionCommand();
if(e.getSource() == beamLBDialog){
if(command.equals("Beam")){
waba.sys.Vm.exec("CCBeam", "LabBook,,," +
"LabBook for CCProbe", 0, true);
}
}
}
public void reload(LabObjectView source)
{
if(source != lObjView) Debug.println("Error source being removed");
LabObject obj = source.getLabObject();
LabBookSession oldSession = source.getSession();
source.close();
me.remove(source);
if(title != null){
me.remove(title);
}
LabObjectView replacement = obj.getView(this, true, oldSession);
// This automatically does the layout call for us
waba.fx.Rect myRect = content.getRect();
myHeight = myRect.height;
int dictHeight = myHeight;
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
replacement.setRect(x,yOffset,width,dictHeight);
replacement.setShowMenus(true);
me.add(replacement);
lObjView = replacement;
}
public void actionPerformed(ActionEvent e)
{
String command;
Debug.println("Got action: " + e.getActionCommand());
if(e.getSource() == file){
command = e.getActionCommand();
if(command.equals("Exit")){
handleQuit();
}else if(command.equals(aboutTitle)){
handleAbout();
} else if(command.equals("Beam LabBook")){
String [] buttons = {"Beam", "Cancel"};
beamLBDialog = Dialog.showConfirmDialog(this, "Confirm",
"Close CCProbe on the receiving| " +
"Palm before beaming.",
buttons,
Dialog.INFO_DIALOG);
} else if(command.equals("Serial Port Setup..")){
DataExport.showSerialDialog();
} else {
super.actionPerformed(e);
}
}
}
public void onExit()
{
Debug.println("closing");
if(labBook != null){
if(curFullView != null){
curFullView.close();
} else {
lObjView.close();
}
labBook.commit();
labBook.close();
}
}
public void handleQuit(){
Debug.println("commiting");
if(curFullView != null){
curFullView.close();
curFullView = null;
} else if(lObjView != null) {
lObjView.close();
}
if(labBook != null){
labBook.commit();
labBook.close();
labBook = null;
exit(0);
}
}
public void handleAbout(){
Dialog.showAboutDialog(aboutTitle,AboutMessages.getMessage());
}
}
| false | true | public void onStart()
{
super.onStart();
LObjDictionary loDict = null;
LabBook.registerFactory(new DataObjFactory());
// Dialog.showImages = false;
// ImagePane.showImages = false;
graph.Bin.START_DATA_SIZE = 25000;
graph.LargeFloatArray.MaxNumChunks = 25;
int dictHeight = myHeight;
LabBookDB lbDB;
String plat = waba.sys.Vm.getPlatform();
if(plat.equals("PalmOS")){
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
GraphSettings.MAX_COLLECTIONS = 1;
graph.GraphViewLine.scrollStepSize = 0.45f;
lbDB = new LabBookCatalog("LabBook");
CCTextArea.INTER_LINE_SPACING = 0;
} else if(plat.equals("Java")){
/*
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
*/
// GraphSettings.MAX_COLLECTIONS = 1;
lbDB = new LabBookCatalog("LabBook");
// lbDB = new LabBookFile("LabBook");
} else {
lbDB = new LabBookFile("LabBook");
GraphSettings.MAX_COLLECTIONS = 4;
}
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
if(lbDB.getError()){
// Error;
exit(0);
}
if(plat.equals("PalmOS")){
addFileMenuItems(palmFileStrings, null);
} else if(plat.equals("Java")){
addFileMenuItems(javaFileStrings, null);
} else {
addFileMenuItems(ceFileStrings, null);
}
Debug.println("Openning");
labBook.open(lbDB);
LabObjectPtr rootPtr = labBook.getRoot();
mainSession = rootPtr.getSession();
loDict = (LObjDictionary)mainSession.getObj(rootPtr);
if(loDict == null){
loDict = DefaultFactory.createDictionary();
loDict.setName("Home");
mainSession.storeNew(loDict);
labBook.store(loDict);
}
LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession);
view.setRect(x,yOffset,width,dictHeight);
view.setShowMenus(true);
me.add(view);
lObjView = view;
newIndex = loDict.getChildCount();
((LObjDictionaryView)view).checkForBeam();
}
| public void onStart()
{
super.onStart();
LObjDictionary loDict = null;
LabBook.registerFactory(new DataObjFactory());
// Dialog.showImages = false;
// ImagePane.showImages = false;
graph.Bin.START_DATA_SIZE = 25000;
graph.LargeFloatArray.MaxNumChunks = 25;
int dictHeight = myHeight;
LabBookDB lbDB;
String plat = waba.sys.Vm.getPlatform();
if(plat.equals("PalmOS")){
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
GraphSettings.MAX_COLLECTIONS = 1;
graph.GraphViewLine.scrollStepSize = 0.45f;
lbDB = new LabBookCatalog("LabBook");
CCTextArea.INTER_LINE_SPACING = 0;
Dialog.showImages = false;
} else if(plat.equals("Java")){
/*
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
*/
// GraphSettings.MAX_COLLECTIONS = 1;
// lbDB = new LabBookCatalog("LabBook");
// Dialog.showImages = false;
lbDB = new LabBookFile("LabBook");
} else {
lbDB = new LabBookFile("LabBook");
GraphSettings.MAX_COLLECTIONS = 4;
}
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
if(lbDB.getError()){
// Error;
exit(0);
}
if(plat.equals("PalmOS")){
addFileMenuItems(palmFileStrings, null);
} else if(plat.equals("Java")){
addFileMenuItems(javaFileStrings, null);
} else {
addFileMenuItems(ceFileStrings, null);
}
Debug.println("Openning");
labBook.open(lbDB);
LabObjectPtr rootPtr = labBook.getRoot();
mainSession = rootPtr.getSession();
loDict = (LObjDictionary)mainSession.getObj(rootPtr);
if(loDict == null){
loDict = DefaultFactory.createDictionary();
loDict.setName("Home");
mainSession.storeNew(loDict);
labBook.store(loDict);
}
LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession);
view.setRect(x,yOffset,width,dictHeight);
view.setShowMenus(true);
me.add(view);
lObjView = view;
newIndex = loDict.getChildCount();
if(plat.equals("PalmOS")){
((LObjDictionaryView)view).checkForBeam();
}
}
|
diff --git a/flixel/src/org/flixel/FlxButton.java b/flixel/src/org/flixel/FlxButton.java
index 6cb970d..0b44ce6 100644
--- a/flixel/src/org/flixel/FlxButton.java
+++ b/flixel/src/org/flixel/FlxButton.java
@@ -1,512 +1,513 @@
package org.flixel;
import org.flixel.event.AFlxButton;
import org.flixel.event.IMouseObserver;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
/**
* A simple button class that calls a function when clicked by the mouse.
*
* @author Ka Wing Chin
*/
public class FlxButton extends FlxSprite implements IMouseObserver
{
protected String ImgDefaultButton = "org/flixel/data/pack:button";
/**
* Used with public variable <code>status</code>, means not highlighted or pressed.
*/
static public final int NORMAL = 0;
/**
* Used with public variable <code>status</code>, means highlighted (usually from mouse over).
*/
static public final int HIGHLIGHT = 1;
/**
* Used with public variable <code>status</code>, means pressed (usually from mouse click).
*/
static public final int PRESSED = 2;
/**
* The text that appears on the button.
*/
public FlxText label;
/**
* Controls the offset (from top left) of the text from the button.
*/
public FlxPoint labelOffset;
/**
* This event is called when the button is released or pressed.
* We recommend assigning your main button behavior to this function
* via the <code>FlxButton</code> constructor.
*/
public AFlxButton callback;
/**
* Shows the current state of the button.
*/
public int status;
/**
* Set this to play a sound when the mouse goes over the button.
* We recommend using the helper function setSounds()!
*/
public FlxSound soundOver;
/**
* Set this to play a sound when the mouse leaves the button.
* We recommend using the helper function setSounds()!
*/
public FlxSound soundOut;
/**
* Set this to play a sound when the button is pressed down.
* We recommend using the helper function setSounds()!
*/
public FlxSound soundDown;
/**
* Set this to play a sound when the button is released.
* We recommend using the helper function setSounds()!
*/
public FlxSound soundUp;
/**
* Used for checkbox-style behavior.
*/
protected boolean _onToggle;
/**
* Tracks whether or not the button is currently pressed.
*/
protected boolean _pressed;
/**
* Whether or not the button has initialized itself yet.
*/
private boolean _initialized;
/**
* Creates a new <code>FlxButton</code> object with a gray background
* and a callback function on the UI thread.
*
* @param X The X position of the button.
* @param Y The Y position of the button.
* @param Label The text that you want to appear on the button.
* @param OnClick The function to call whenever the button is clicked.
*/
public FlxButton(float X, float Y, String Label, AFlxButton Callback)
{
super(X,Y);
if(Label != null)
{
label = new FlxText(0,0,80,Label);
label.setFormat(null,8,0x333333,"center");
labelOffset = new FlxPoint(-1,4);
}
loadGraphic(ImgDefaultButton,true,false,80,20);
callback = Callback;
soundOver = null;
soundOut = null;
soundDown = null;
soundUp = null;
status = NORMAL;
_onToggle = false;
_pressed = false;
_initialized = false;
}
/**
* Creates a new <code>FlxButton</code> object with a gray background
* and a callback function on the UI thread.
*
* @param X The X position of the button.
* @param Y The Y position of the button.
* @param Label The text that you want to appear on the button.
*/
public FlxButton(float X, float Y, String Label)
{
this(X, Y, Label, null);
}
/**
* Creates a new <code>FlxButton</code> object with a gray background
* and a callback function on the UI thread.
*
* @param X The X position of the button.
* @param Y The Y position of the button.
*/
public FlxButton(float X, float Y)
{
this(X, Y, null, null);
}
/**
* Creates a new <code>FlxButton</code> object with a gray background
* and a callback function on the UI thread.
*
* @param X The X position of the button.
*/
public FlxButton(float X)
{
this(X, 0, null, null);
}
/**
* Creates a new <code>FlxButton</code> object with a gray background
* and a callback function on the UI thread.
*/
public FlxButton()
{
this(0, 0, null, null);
}
@Override
public void destroy()
{
if(FlxG._game != null)
FlxG._game.removeObserver(this);
if(label != null)
{
label.destroy();
label = null;
}
callback = null;
if(soundOver != null)
soundOver.destroy();
if(soundOut != null)
soundOut.destroy();
if(soundDown != null)
soundDown.destroy();
if(soundUp != null)
soundUp.destroy();
super.destroy();
}
@Override
public void preUpdate()
{
super.preUpdate();
if(!_initialized)
{
if(FlxG._game != null)
{
FlxG._game.addObserver(this);
_initialized = true;
}
}
}
@Override
public void update()
{
updateButton(); //Basic button logic
//Default button appearance is to simply update
// the label appearance based on animation frame.
if(label == null)
return;
switch(getFrame())
{
case HIGHLIGHT: //Extra behavior to accommodate checkbox logic.
label.setAlpha(1.0f);
break;
case PRESSED:
label.setAlpha(0.5f);
label.y++;
break;
case NORMAL:
default:
label.setAlpha(0.8f);
break;
}
}
/**
* Basic button update logic
*/
protected void updateButton()
{
- status = NORMAL;
+ if (status == PRESSED)
+ status = NORMAL;
//Figure out if the button is highlighted or pressed or what
// (ignore checkbox behavior for now).
if(cameras == null)
cameras = FlxG.cameras;
FlxCamera camera;
int i = 0;
int l = cameras.size;
int pointerId = 0;
int totalPointers = FlxG.mouse.activePointers + 1;
boolean offAll = true;
while(i < l)
{
camera = cameras.get(i++);
while(pointerId < totalPointers)
{
FlxG.mouse.getWorldPosition(pointerId, camera, _point);
if(overlapsPoint(_point, true, camera))
{
offAll = false;
if(FlxG.mouse.pressed(pointerId))
{
status = PRESSED;
if(FlxG.mouse.justPressed(pointerId))
{
if(callback != null)
{
callback.onDown();
}
if(soundDown != null)
soundDown.play(true);
}
}
if(status == NORMAL)
{
status = HIGHLIGHT;
if(callback != null)
callback.onOver();
if(soundOver != null)
soundOver.play(true);
}
}
++pointerId;
}
}
if(offAll)
{
if(status != NORMAL)
{
if(callback != null)
callback.onOut();
if(soundOut != null)
soundOut.play(true);
}
status = NORMAL;
}
//Then if the label and/or the label offset exist,
// position them to match the button.
if(label != null)
{
label.x = x;
label.y = y;
}
if(labelOffset != null)
{
label.x += labelOffset.x;
label.y += labelOffset.y;
}
//Then pick the appropriate frame of animation
if((status == HIGHLIGHT) && (_onToggle || Gdx.app.getType() != ApplicationType.Desktop))
setFrame(NORMAL);
else
setFrame(status);
}
/**
* Just draws the button graphic and text label to the screen.
*/
@Override
public void draw(FlxCamera Camera)
{
super.draw(Camera);
if(label != null)
{
label.scrollFactor = scrollFactor;
label.cameras = cameras;
label.draw(Camera);
}
}
/**
* Updates the size of the text field to match the button.
*/
@Override
protected void resetHelpers()
{
super.resetHelpers();
if(label != null)
label.width = width;
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
* @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound.
* @param SoundOutVolume How load the that sound should be.
* @param SoundDown What embedded sound effect to play when the mouse presses the button down. Default is null, or no sound.
* @param SoundDownVolume How load the that sound should be.
* @param SoundUp What embedded sound effect to play when the mouse releases the button. Default is null, or no sound.
* @param SoundUpVolume How load the that sound should be.
*/
public void setSounds(String SoundOver, float SoundOverVolume, String SoundOut, float SoundOutVolume, String SoundDown, float SoundDownVolume, String SoundUp, float SoundUpVolume)
{
if(SoundOver != null)
soundOver = FlxG.loadSound(SoundOver, SoundOverVolume);
if(SoundOut != null)
soundOut = FlxG.loadSound(SoundOut, SoundOutVolume);
if(SoundDown != null)
soundDown = FlxG.loadSound(SoundDown, SoundDownVolume);
if(SoundUp != null)
soundUp = FlxG.loadSound(SoundUp, SoundUpVolume);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
* @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound.
* @param SoundOutVolume How load the that sound should be.
* @param SoundDown What embedded sound effect to play when the mouse presses the button down. Default is null, or no sound.
* @param SoundDownVolume How load the that sound should be.
* @param SoundUp What embedded sound effect to play when the mouse releases the button. Default is null, or no sound.
*/
public void setSounds(String SoundOver, float SoundOverVolume, String SoundOut, float SoundOutVolume, String SoundDown, float SoundDownVolume, String SoundUp)
{
setSounds(SoundOver, SoundOverVolume, SoundOut, SoundOutVolume, SoundDown, SoundDownVolume, SoundUp, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
* @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound.
* @param SoundOutVolume How load the that sound should be.
* @param SoundDown What embedded sound effect to play when the mouse presses the button down. Default is null, or no sound.
* @param SoundDownVolume How load the that sound should be.
*/
public void setSounds(String SoundOver, float SoundOverVolume, String SoundOut, float SoundOutVolume, String SoundDown, float SoundDownVolume)
{
setSounds(SoundOver, SoundOverVolume, SoundOut, SoundOutVolume, SoundDown, SoundDownVolume, null, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
* @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound.
* @param SoundOutVolume How load the that sound should be.
* @param SoundDown What embedded sound effect to play when the mouse presses the button down. Default is null, or no sound.
*/
public void setSounds(String SoundOver, float SoundOverVolume, String SoundOut, float SoundOutVolume, String SoundDown)
{
setSounds(SoundOver, SoundOverVolume, SoundOut, SoundOutVolume, SoundDown, 1.0f, null, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
* @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound.
* @param SoundOutVolume How load the that sound should be.
*/
public void setSounds(String SoundOver, float SoundOverVolume, String SoundOut, float SoundOutVolume)
{
setSounds(SoundOver, SoundOverVolume, SoundOut, SoundOutVolume, null, 1.0f, null, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
* @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound.
*/
public void setSounds(String SoundOver, float SoundOverVolume, String SoundOut)
{
setSounds(SoundOver, SoundOverVolume, SoundOut, 1.0f, null, 1.0f, null, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
* @param SoundOverVolume How load the that sound should be.
*/
public void setSounds(String SoundOver, float SoundOverVolume)
{
setSounds(SoundOver, SoundOverVolume, null, 1.0f, null, 1.0f, null, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*
* @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound.
*/
public void setSounds(String SoundOver)
{
setSounds(SoundOver, 1.0f, null, 1.0f, null, 1.0f, null, 1.0f);
}
/**
* Set sounds to play during mouse-button interactions.
* These operations can be done manually as well, and the public
* sound variables can be used after this for more fine-tuning,
* such as positional audio, etc.
*/
public void setSounds()
{
setSounds(null, 1.0f, null, 1.0f, null, 1.0f, null, 1.0f);
}
/**
* Use this to toggle checkbox-style behavior.
*/
public boolean getOn()
{
return _onToggle;
}
/**
* @private
*/
public void setOn(boolean On)
{
_onToggle = On;
}
@Override
public void updateListener()
{
if(!exists || !visible || !active || (status != PRESSED))
return;
if(callback != null)
callback.onUp();
if(soundUp != null)
soundUp.play(true);
}
}
| true | true | protected void updateButton()
{
status = NORMAL;
//Figure out if the button is highlighted or pressed or what
// (ignore checkbox behavior for now).
if(cameras == null)
cameras = FlxG.cameras;
FlxCamera camera;
int i = 0;
int l = cameras.size;
int pointerId = 0;
int totalPointers = FlxG.mouse.activePointers + 1;
boolean offAll = true;
while(i < l)
{
camera = cameras.get(i++);
while(pointerId < totalPointers)
{
FlxG.mouse.getWorldPosition(pointerId, camera, _point);
if(overlapsPoint(_point, true, camera))
{
offAll = false;
if(FlxG.mouse.pressed(pointerId))
{
status = PRESSED;
if(FlxG.mouse.justPressed(pointerId))
{
if(callback != null)
{
callback.onDown();
}
if(soundDown != null)
soundDown.play(true);
}
}
if(status == NORMAL)
{
status = HIGHLIGHT;
if(callback != null)
callback.onOver();
if(soundOver != null)
soundOver.play(true);
}
}
++pointerId;
}
}
if(offAll)
{
if(status != NORMAL)
{
if(callback != null)
callback.onOut();
if(soundOut != null)
soundOut.play(true);
}
status = NORMAL;
}
//Then if the label and/or the label offset exist,
// position them to match the button.
if(label != null)
{
label.x = x;
label.y = y;
}
if(labelOffset != null)
{
label.x += labelOffset.x;
label.y += labelOffset.y;
}
//Then pick the appropriate frame of animation
if((status == HIGHLIGHT) && (_onToggle || Gdx.app.getType() != ApplicationType.Desktop))
setFrame(NORMAL);
else
setFrame(status);
}
| protected void updateButton()
{
if (status == PRESSED)
status = NORMAL;
//Figure out if the button is highlighted or pressed or what
// (ignore checkbox behavior for now).
if(cameras == null)
cameras = FlxG.cameras;
FlxCamera camera;
int i = 0;
int l = cameras.size;
int pointerId = 0;
int totalPointers = FlxG.mouse.activePointers + 1;
boolean offAll = true;
while(i < l)
{
camera = cameras.get(i++);
while(pointerId < totalPointers)
{
FlxG.mouse.getWorldPosition(pointerId, camera, _point);
if(overlapsPoint(_point, true, camera))
{
offAll = false;
if(FlxG.mouse.pressed(pointerId))
{
status = PRESSED;
if(FlxG.mouse.justPressed(pointerId))
{
if(callback != null)
{
callback.onDown();
}
if(soundDown != null)
soundDown.play(true);
}
}
if(status == NORMAL)
{
status = HIGHLIGHT;
if(callback != null)
callback.onOver();
if(soundOver != null)
soundOver.play(true);
}
}
++pointerId;
}
}
if(offAll)
{
if(status != NORMAL)
{
if(callback != null)
callback.onOut();
if(soundOut != null)
soundOut.play(true);
}
status = NORMAL;
}
//Then if the label and/or the label offset exist,
// position them to match the button.
if(label != null)
{
label.x = x;
label.y = y;
}
if(labelOffset != null)
{
label.x += labelOffset.x;
label.y += labelOffset.y;
}
//Then pick the appropriate frame of animation
if((status == HIGHLIGHT) && (_onToggle || Gdx.app.getType() != ApplicationType.Desktop))
setFrame(NORMAL);
else
setFrame(status);
}
|
diff --git a/src/test/java/nl/surfnet/bod/web/NsiTopologyControllerTest.java b/src/test/java/nl/surfnet/bod/web/NsiTopologyControllerTest.java
index 4f4a980cd..6f5e0abbf 100644
--- a/src/test/java/nl/surfnet/bod/web/NsiTopologyControllerTest.java
+++ b/src/test/java/nl/surfnet/bod/web/NsiTopologyControllerTest.java
@@ -1,96 +1,97 @@
/**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.web;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import com.google.common.collect.ImmutableList;
import nl.surfnet.bod.domain.EnniPort;
import nl.surfnet.bod.domain.UniPort;
import nl.surfnet.bod.domain.VirtualPort;
import nl.surfnet.bod.nsi.NsiHelper;
import nl.surfnet.bod.service.PhysicalPortService;
import nl.surfnet.bod.service.VirtualPortService;
import nl.surfnet.bod.util.Environment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(MockitoJUnitRunner.class)
public class NsiTopologyControllerTest {
@InjectMocks
private NsiTopologyController subject;
@Mock private Environment environment;
@Mock private VirtualPortService virtualPortService;
@Mock private PhysicalPortService physicalPortService;
@Mock private NsiHelper nsiHelper;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = standaloneSetup(subject).build();
}
@Test
public void should_display_virtualports_and_enniports() throws Exception {
EnniPort enniPort = new EnniPort();
VirtualPort virtualPort = new VirtualPort();
virtualPort.setVlanId(1);
virtualPort.setPhysicalPort(new UniPort());
when(physicalPortService.findAllAllocatedEnniEntries()).thenReturn(ImmutableList.of(enniPort));
when(virtualPortService.findAll()).thenReturn(ImmutableList.of(virtualPort));
when(environment.getNsiTopologyAdminContactContentFileUri()).thenReturn("/topologyAdminContactContent.xml");
+ when(environment.getNsiNetworkName()).thenReturn("nsiNetworkName");
when(nsiHelper.getProviderNsaV2()).thenReturn("providerNSA");
when(nsiHelper.getNetworkIdV2()).thenReturn("networkId");
mockMvc.perform(get("/nsi-topology"))
.andExpect(status().isOk())
.andExpect(model().attribute("entries", hasSize(2)))
.andExpect(model().attribute("providerNsa", is("providerNSA")))
- .andExpect(model().attribute("networkName", is("networkId")))
+ .andExpect(model().attribute("networkName", is("nsiNetworkName")))
.andExpect(model().attribute("version", notNullValue()))
.andExpect(model().attribute("adminContactContent", notNullValue()))
.andExpect(view().name("topology"));
verify(physicalPortService).findAllAllocatedEnniEntries();
verify(virtualPortService).findAll();
}
}
| false | true | public void should_display_virtualports_and_enniports() throws Exception {
EnniPort enniPort = new EnniPort();
VirtualPort virtualPort = new VirtualPort();
virtualPort.setVlanId(1);
virtualPort.setPhysicalPort(new UniPort());
when(physicalPortService.findAllAllocatedEnniEntries()).thenReturn(ImmutableList.of(enniPort));
when(virtualPortService.findAll()).thenReturn(ImmutableList.of(virtualPort));
when(environment.getNsiTopologyAdminContactContentFileUri()).thenReturn("/topologyAdminContactContent.xml");
when(nsiHelper.getProviderNsaV2()).thenReturn("providerNSA");
when(nsiHelper.getNetworkIdV2()).thenReturn("networkId");
mockMvc.perform(get("/nsi-topology"))
.andExpect(status().isOk())
.andExpect(model().attribute("entries", hasSize(2)))
.andExpect(model().attribute("providerNsa", is("providerNSA")))
.andExpect(model().attribute("networkName", is("networkId")))
.andExpect(model().attribute("version", notNullValue()))
.andExpect(model().attribute("adminContactContent", notNullValue()))
.andExpect(view().name("topology"));
verify(physicalPortService).findAllAllocatedEnniEntries();
verify(virtualPortService).findAll();
}
| public void should_display_virtualports_and_enniports() throws Exception {
EnniPort enniPort = new EnniPort();
VirtualPort virtualPort = new VirtualPort();
virtualPort.setVlanId(1);
virtualPort.setPhysicalPort(new UniPort());
when(physicalPortService.findAllAllocatedEnniEntries()).thenReturn(ImmutableList.of(enniPort));
when(virtualPortService.findAll()).thenReturn(ImmutableList.of(virtualPort));
when(environment.getNsiTopologyAdminContactContentFileUri()).thenReturn("/topologyAdminContactContent.xml");
when(environment.getNsiNetworkName()).thenReturn("nsiNetworkName");
when(nsiHelper.getProviderNsaV2()).thenReturn("providerNSA");
when(nsiHelper.getNetworkIdV2()).thenReturn("networkId");
mockMvc.perform(get("/nsi-topology"))
.andExpect(status().isOk())
.andExpect(model().attribute("entries", hasSize(2)))
.andExpect(model().attribute("providerNsa", is("providerNSA")))
.andExpect(model().attribute("networkName", is("nsiNetworkName")))
.andExpect(model().attribute("version", notNullValue()))
.andExpect(model().attribute("adminContactContent", notNullValue()))
.andExpect(view().name("topology"));
verify(physicalPortService).findAllAllocatedEnniEntries();
verify(virtualPortService).findAll();
}
|
diff --git a/src/main/java/org/werti/server/WERTiServiceImpl.java b/src/main/java/org/werti/server/WERTiServiceImpl.java
index 97a6042..9d4bc82 100644
--- a/src/main/java/org/werti/server/WERTiServiceImpl.java
+++ b/src/main/java/org/werti/server/WERTiServiceImpl.java
@@ -1,260 +1,261 @@
package org.werti.server;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.apache.log4j.Logger;
import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceSpecifier;
import org.apache.uima.util.InvalidXMLException;
import org.apache.uima.util.XMLInputSource;
import org.werti.WERTiContext;
import org.werti.client.InitializationException;
import org.werti.client.ProcessingException;
import org.werti.client.URLException;
import org.werti.client.WERTiService;
import org.werti.client.run.RunConfiguration;
import org.werti.client.util.Tuple;
import org.werti.uima.types.Enhancement;
import org.werti.util.Fetcher;
/**
* The server side implementation of the WERTi service.
*
* This is were the work is coordinated. The rough outline of the procedure is as follows:
*
* <li>We take a request via the <tt>process</tt> method</li>
* <li>We Construct the analysis engines (post and preprocessing) according to the request</li>
* <li>In the meantime lib.html.Fetcher is invoked to fetch the requested site off the Internet</li>
* <li>Then everything is pre-processed in UIMA, invoking the right pre processor for the task at hand</li>
* <li>We take the resulting CAS and post-process it, invoking the right post processor for the task at hand</li>
* <li>We add some neccessary headers to the page (<tt><base></tt> tag and JS sources).</li>
* <li>Afterwards we take the CAS and insert enhancement annotations
* (<tt>WERTi</tt>-<tt><span></tt>s) according to the target annotations by the post-processing.</li>
* <li>Finally, a temporary file is written to, which holds the results</li>
*
* Currently, there is no real API for binding into this procedure. This should ultimately change.
* In order to incorporate new features, modifications to this file will have to be made... :-(
*
* @author Aleksandar Dimitrov
* @version 0.2
*/
public class WERTiServiceImpl extends RemoteServiceServlet implements WERTiService {
private static final Logger log =
Logger.getLogger(WERTiServiceImpl.class);
// maximum amount of of ms to wait for a web-page to load
private static final int MAX_WAIT = 1000 * 10; // 10 seconds
public static WERTiContext context;
public static final long serialVersionUID = 10;
private static void configEngine(AnalysisEngine ae, List<Tuple> config) {
if (config == null) {
log.warn("No configuration found for " + ae.getClass().getName());
return;
}
log.debug("Configuring " + ae.getClass().getName());
for (Tuple e:config) {
log.debug("Configuring: " + e.fst() + " with " + e.snd());
ae.setConfigParameterValue(e.fst(), e.snd());
}
}
/**
* The implementation of the process method according to the interface specifications.
*
* @param config The <code>RunConfiguration</code> for this request.
* @param url The URL of the page the user has requested.
*/
public String process(RunConfiguration config, String url)
throws URLException, InitializationException, ProcessingException {
context = new WERTiContext(getServletContext());
if (log.isDebugEnabled()) { // dump configuration to log
final StringBuilder sb = new StringBuilder();
sb.append("\nURL: "+ url);
sb.append("\nConfiguration: " + config.getClass().getName());
sb.append("\nPre-processor: " + config.preprocessor());
sb.append("\n\tlocation: : " + context.getProperty(config.preprocessor()));
sb.append("\nPost-processor: " + config.postprocessor());
sb.append("\n\tlocation: : " + context.getProperty(config.postprocessor()));
log.debug(sb.toString());
}
log.debug("Fetching site " + url);
final Fetcher fetcher;
try {
fetcher = new Fetcher(url);
} catch (MalformedURLException murle) {
throw new URLException(murle);
}
fetcher.start();
final JCas cas;
final AnalysisEngine preprocessor, postprocessor;
final String descPath = context.getProperty("descriptorPath");
log.trace("Loading from descriptor path: " + descPath);
final URL preDesc, postDesc;
try { // to load the descriptors
preDesc = getServletContext().getResource
(descPath + context.getProperty(config.preprocessor()));
postDesc = getServletContext().getResource
(descPath + context.getProperty(config.postprocessor()));
} catch (MalformedURLException murle) {
log.fatal("Unrecoverable: Invalid descriptor file!");
throw new InitializationException("Could not instantiate operator.", murle);
}
try { // to initialize UIMA components
final XMLInputSource pre_xmlin = new XMLInputSource(preDesc);
final ResourceSpecifier pre_spec =
UIMAFramework.getXMLParser().parseResourceSpecifier(pre_xmlin);
preprocessor = UIMAFramework.produceAnalysisEngine(pre_spec);
cas = preprocessor.newJCas();
final XMLInputSource post_xmlin = new XMLInputSource(postDesc);
final ResourceSpecifier post_spec =
UIMAFramework.getXMLParser().parseResourceSpecifier(post_xmlin);
postprocessor = UIMAFramework.produceAnalysisEngine(post_spec);
} catch (InvalidXMLException ixmle) {
log.fatal("Error initializing XML code. Invalid?", ixmle);
throw new InitializationException("Error initializing XML code. Invalid?", ixmle);
} catch (ResourceInitializationException rie) {
log.fatal("Error initializing resource", rie);
throw new InitializationException("Error initializing resource", rie);
} catch (IOException ioe) {
log.fatal("Error accessing descriptor file", ioe);
throw new InitializationException("Error accessing descriptor file", ioe);
} catch (NullPointerException npe) {
log.fatal("Error accessing descriptor files or creating analysis objects", npe);
throw new InitializationException
("Error accessing descriptor files or creating analysis objects", npe);
}
log.info("Initialized UIMA components.");
log.info("Configuring UIMA components...");
configEngine(preprocessor, config.preconfig());
configEngine(postprocessor, config.postconfig());
try { // to wait for document text to be available
fetcher.join(MAX_WAIT);
} catch (InterruptedException itre) {
log.error("Fetcher recieved interrupt. This shouldn't happen, should it?", itre);
}
if (fetcher.getText() == null) { // we don't have text, that's bad
log.error("Webpage retrieval failed! " + fetcher.getBase_url());
throw new InitializationException("Webpage retrieval failed.");
}
cas.setDocumentText(fetcher.getText());
try { // to process
preprocessor.process(cas);
postprocessor.process(cas);
} catch (AnalysisEngineProcessException aepe) {
log.fatal("Analysis Engine encountered errors!", aepe);
throw new ProcessingException("Text analysis failed.", aepe);
}
final String base_url = "http://" + fetcher.getBase_url() + ":" + fetcher.getPort();
final String enhanced = enhance(config.enhancer(), cas, base_url);
final String tempDir = getServletContext().getRealPath("/tmp");
final File temp;
try { // to create a temporary file
temp = File.createTempFile("WERTi", ".tmp.html", new File(tempDir));
} catch (IOException ioe) {
log.error("Failed to create temporary file");
throw new ProcessingException("Failed to create temporary file!", ioe);
}
try { // to write to the temporary file
if (log.isDebugEnabled()) {
log.debug("Writing to file: " + temp.getAbsoluteFile());
}
final FileWriter out = new FileWriter(temp);
out.write(enhanced);
+ out.close();
} catch (IOException ioe) {
log.error("Failed to write to temporary file");
throw new ProcessingException("Failed write to temporary file!", ioe);
}
return "/tmp/" + temp.getName();
}
/**
* Input-Enhances the CAS given with Enhancement annotations.
*
* This is an easy to understand version of enhance, using StringBuilders insert() rather
* than appending to it and minding skews.
*
* @param cas The cas to enhance.
*/
@SuppressWarnings("unchecked")
private String enhance(final String method, final JCas cas, final String baseurl) {
final String docText = cas.getDocumentText();
final StringBuilder rtext = new StringBuilder(docText);
int skew = docText.indexOf("<head");
skew = docText.indexOf('>',skew)+1;
final String basetag = "<base href=\"" + baseurl + "\" />"
// GWT main JS module
+ "<script type=\"text/javascript\" language=\"javascript\" src=\""
+ context.getProperty("this-server") + "/WERTi/org.werti.enhancements."
+ method
+ "/org.werti.enhancements."
+ method
+ ".nocache.js\"></script>";
rtext.insert(skew, basetag);
skew = basetag.length();
final FSIndex tagIndex = cas.getAnnotationIndex(Enhancement.type);
final Iterator<Enhancement> eit = tagIndex.iterator();
while (eit.hasNext()) {
final Enhancement e = eit.next();
if (log.isTraceEnabled()){
log.trace("Enhancement starts at " + e.getBegin()
+ " and ends at " + e.getEnd()
+ "; Current skew is: " + skew);
}
final String start_tag = e.getEnhanceStart();
rtext.insert(e.getBegin() + skew, start_tag);
skew += start_tag.length();
final String end_tag = e.getEnhanceEnd();
rtext.insert(e.getEnd() + skew, end_tag);
skew += end_tag.length();
}
return rtext.toString();
}
}
| true | true | public String process(RunConfiguration config, String url)
throws URLException, InitializationException, ProcessingException {
context = new WERTiContext(getServletContext());
if (log.isDebugEnabled()) { // dump configuration to log
final StringBuilder sb = new StringBuilder();
sb.append("\nURL: "+ url);
sb.append("\nConfiguration: " + config.getClass().getName());
sb.append("\nPre-processor: " + config.preprocessor());
sb.append("\n\tlocation: : " + context.getProperty(config.preprocessor()));
sb.append("\nPost-processor: " + config.postprocessor());
sb.append("\n\tlocation: : " + context.getProperty(config.postprocessor()));
log.debug(sb.toString());
}
log.debug("Fetching site " + url);
final Fetcher fetcher;
try {
fetcher = new Fetcher(url);
} catch (MalformedURLException murle) {
throw new URLException(murle);
}
fetcher.start();
final JCas cas;
final AnalysisEngine preprocessor, postprocessor;
final String descPath = context.getProperty("descriptorPath");
log.trace("Loading from descriptor path: " + descPath);
final URL preDesc, postDesc;
try { // to load the descriptors
preDesc = getServletContext().getResource
(descPath + context.getProperty(config.preprocessor()));
postDesc = getServletContext().getResource
(descPath + context.getProperty(config.postprocessor()));
} catch (MalformedURLException murle) {
log.fatal("Unrecoverable: Invalid descriptor file!");
throw new InitializationException("Could not instantiate operator.", murle);
}
try { // to initialize UIMA components
final XMLInputSource pre_xmlin = new XMLInputSource(preDesc);
final ResourceSpecifier pre_spec =
UIMAFramework.getXMLParser().parseResourceSpecifier(pre_xmlin);
preprocessor = UIMAFramework.produceAnalysisEngine(pre_spec);
cas = preprocessor.newJCas();
final XMLInputSource post_xmlin = new XMLInputSource(postDesc);
final ResourceSpecifier post_spec =
UIMAFramework.getXMLParser().parseResourceSpecifier(post_xmlin);
postprocessor = UIMAFramework.produceAnalysisEngine(post_spec);
} catch (InvalidXMLException ixmle) {
log.fatal("Error initializing XML code. Invalid?", ixmle);
throw new InitializationException("Error initializing XML code. Invalid?", ixmle);
} catch (ResourceInitializationException rie) {
log.fatal("Error initializing resource", rie);
throw new InitializationException("Error initializing resource", rie);
} catch (IOException ioe) {
log.fatal("Error accessing descriptor file", ioe);
throw new InitializationException("Error accessing descriptor file", ioe);
} catch (NullPointerException npe) {
log.fatal("Error accessing descriptor files or creating analysis objects", npe);
throw new InitializationException
("Error accessing descriptor files or creating analysis objects", npe);
}
log.info("Initialized UIMA components.");
log.info("Configuring UIMA components...");
configEngine(preprocessor, config.preconfig());
configEngine(postprocessor, config.postconfig());
try { // to wait for document text to be available
fetcher.join(MAX_WAIT);
} catch (InterruptedException itre) {
log.error("Fetcher recieved interrupt. This shouldn't happen, should it?", itre);
}
if (fetcher.getText() == null) { // we don't have text, that's bad
log.error("Webpage retrieval failed! " + fetcher.getBase_url());
throw new InitializationException("Webpage retrieval failed.");
}
cas.setDocumentText(fetcher.getText());
try { // to process
preprocessor.process(cas);
postprocessor.process(cas);
} catch (AnalysisEngineProcessException aepe) {
log.fatal("Analysis Engine encountered errors!", aepe);
throw new ProcessingException("Text analysis failed.", aepe);
}
final String base_url = "http://" + fetcher.getBase_url() + ":" + fetcher.getPort();
final String enhanced = enhance(config.enhancer(), cas, base_url);
final String tempDir = getServletContext().getRealPath("/tmp");
final File temp;
try { // to create a temporary file
temp = File.createTempFile("WERTi", ".tmp.html", new File(tempDir));
} catch (IOException ioe) {
log.error("Failed to create temporary file");
throw new ProcessingException("Failed to create temporary file!", ioe);
}
try { // to write to the temporary file
if (log.isDebugEnabled()) {
log.debug("Writing to file: " + temp.getAbsoluteFile());
}
final FileWriter out = new FileWriter(temp);
out.write(enhanced);
} catch (IOException ioe) {
log.error("Failed to write to temporary file");
throw new ProcessingException("Failed write to temporary file!", ioe);
}
return "/tmp/" + temp.getName();
}
| public String process(RunConfiguration config, String url)
throws URLException, InitializationException, ProcessingException {
context = new WERTiContext(getServletContext());
if (log.isDebugEnabled()) { // dump configuration to log
final StringBuilder sb = new StringBuilder();
sb.append("\nURL: "+ url);
sb.append("\nConfiguration: " + config.getClass().getName());
sb.append("\nPre-processor: " + config.preprocessor());
sb.append("\n\tlocation: : " + context.getProperty(config.preprocessor()));
sb.append("\nPost-processor: " + config.postprocessor());
sb.append("\n\tlocation: : " + context.getProperty(config.postprocessor()));
log.debug(sb.toString());
}
log.debug("Fetching site " + url);
final Fetcher fetcher;
try {
fetcher = new Fetcher(url);
} catch (MalformedURLException murle) {
throw new URLException(murle);
}
fetcher.start();
final JCas cas;
final AnalysisEngine preprocessor, postprocessor;
final String descPath = context.getProperty("descriptorPath");
log.trace("Loading from descriptor path: " + descPath);
final URL preDesc, postDesc;
try { // to load the descriptors
preDesc = getServletContext().getResource
(descPath + context.getProperty(config.preprocessor()));
postDesc = getServletContext().getResource
(descPath + context.getProperty(config.postprocessor()));
} catch (MalformedURLException murle) {
log.fatal("Unrecoverable: Invalid descriptor file!");
throw new InitializationException("Could not instantiate operator.", murle);
}
try { // to initialize UIMA components
final XMLInputSource pre_xmlin = new XMLInputSource(preDesc);
final ResourceSpecifier pre_spec =
UIMAFramework.getXMLParser().parseResourceSpecifier(pre_xmlin);
preprocessor = UIMAFramework.produceAnalysisEngine(pre_spec);
cas = preprocessor.newJCas();
final XMLInputSource post_xmlin = new XMLInputSource(postDesc);
final ResourceSpecifier post_spec =
UIMAFramework.getXMLParser().parseResourceSpecifier(post_xmlin);
postprocessor = UIMAFramework.produceAnalysisEngine(post_spec);
} catch (InvalidXMLException ixmle) {
log.fatal("Error initializing XML code. Invalid?", ixmle);
throw new InitializationException("Error initializing XML code. Invalid?", ixmle);
} catch (ResourceInitializationException rie) {
log.fatal("Error initializing resource", rie);
throw new InitializationException("Error initializing resource", rie);
} catch (IOException ioe) {
log.fatal("Error accessing descriptor file", ioe);
throw new InitializationException("Error accessing descriptor file", ioe);
} catch (NullPointerException npe) {
log.fatal("Error accessing descriptor files or creating analysis objects", npe);
throw new InitializationException
("Error accessing descriptor files or creating analysis objects", npe);
}
log.info("Initialized UIMA components.");
log.info("Configuring UIMA components...");
configEngine(preprocessor, config.preconfig());
configEngine(postprocessor, config.postconfig());
try { // to wait for document text to be available
fetcher.join(MAX_WAIT);
} catch (InterruptedException itre) {
log.error("Fetcher recieved interrupt. This shouldn't happen, should it?", itre);
}
if (fetcher.getText() == null) { // we don't have text, that's bad
log.error("Webpage retrieval failed! " + fetcher.getBase_url());
throw new InitializationException("Webpage retrieval failed.");
}
cas.setDocumentText(fetcher.getText());
try { // to process
preprocessor.process(cas);
postprocessor.process(cas);
} catch (AnalysisEngineProcessException aepe) {
log.fatal("Analysis Engine encountered errors!", aepe);
throw new ProcessingException("Text analysis failed.", aepe);
}
final String base_url = "http://" + fetcher.getBase_url() + ":" + fetcher.getPort();
final String enhanced = enhance(config.enhancer(), cas, base_url);
final String tempDir = getServletContext().getRealPath("/tmp");
final File temp;
try { // to create a temporary file
temp = File.createTempFile("WERTi", ".tmp.html", new File(tempDir));
} catch (IOException ioe) {
log.error("Failed to create temporary file");
throw new ProcessingException("Failed to create temporary file!", ioe);
}
try { // to write to the temporary file
if (log.isDebugEnabled()) {
log.debug("Writing to file: " + temp.getAbsoluteFile());
}
final FileWriter out = new FileWriter(temp);
out.write(enhanced);
out.close();
} catch (IOException ioe) {
log.error("Failed to write to temporary file");
throw new ProcessingException("Failed write to temporary file!", ioe);
}
return "/tmp/" + temp.getName();
}
|
diff --git a/ActiveObjects/src/net/java/ao/EntityProxy.java b/ActiveObjects/src/net/java/ao/EntityProxy.java
index df7e736..bec117f 100644
--- a/ActiveObjects/src/net/java/ao/EntityProxy.java
+++ b/ActiveObjects/src/net/java/ao/EntityProxy.java
@@ -1,671 +1,671 @@
/*
* Copyright 2007 Daniel Spiewak
*
* 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.java.ao;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.java.ao.schema.OnUpdate;
import net.java.ao.types.DatabaseType;
import net.java.ao.types.TypeManager;
/**
* @author Daniel Spiewak
*/
class EntityProxy<T extends Entity> implements InvocationHandler {
private static final Pattern WHERE_PATTERN = Pattern.compile("([\\d\\w]+)\\s*(=|>|<|LIKE|IS)");
private int id;
private Class<T> type;
private EntityManager manager;
private ImplementationWrapper<T> implementation;
private final Map<String, Object> cache;
private final Set<String> nullSet;
private final ReadWriteLock cacheLock = new ReentrantReadWriteLock();
private final Set<String> dirtyFields;
private final ReadWriteLock dirtyFieldsLock = new ReentrantReadWriteLock();
private final Set<Class<? extends Entity>> toFlushRelations = new HashSet<Class<? extends Entity>>();
private final ReadWriteLock toFlushLock = new ReentrantReadWriteLock();
private List<PropertyChangeListener> listeners;
public EntityProxy(EntityManager manager, Class<T> type, int id) {
this.id = id;
this.type = type;
this.manager = manager;
cache = new HashMap<String, Object>();
nullSet = new HashSet<String>();
dirtyFields = new LinkedHashSet<String>();
listeners = new LinkedList<PropertyChangeListener>();
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getEntityType")) {
return type;
}
if (implementation == null) {
implementation = new ImplementationWrapper<T>((T) proxy);
}
MethodImplWrapper methodImpl = implementation.getMethod(method.getName(), method.getParameterTypes());
if (methodImpl != null) {
if (!Common.getCallingClass(1).equals(methodImpl.getMethod().getDeclaringClass()) && !methodImpl.getMethod().getDeclaringClass().equals(Object.class)) {
return methodImpl.getMethod().invoke(methodImpl.getInstance(), args);
}
}
if (method.getName().equals("getID")) {
return getID();
} else if (method.getName().equals("save")) {
save((Entity) proxy);
return Void.TYPE;
} else if (method.getName().equals("getTableName")) {
return getTableName();
} else if (method.getName().equals("getEntityManager")) {
return getManager();
} else if (method.getName().equals("addPropertyChangeListener")) {
addPropertyChangeListener((PropertyChangeListener) args[0]);
} else if (method.getName().equals("removePropertyChangeListener")) {
removePropertyChangeListener((PropertyChangeListener) args[0]);
} else if (method.getName().equals("hashCode")) {
return hashCodeImpl();
} else if (method.getName().equals("equals")) {
return equalsImpl((Entity) proxy, args[0]);
} else if (method.getName().equals("toString")) {
return toStringImpl();
}
String tableName = getManager().getNameConverter().getName(type);
Mutator mutatorAnnotation = method.getAnnotation(Mutator.class);
Accessor accessorAnnotation = method.getAnnotation(Accessor.class);
OneToMany oneToManyAnnotation = method.getAnnotation(OneToMany.class);
ManyToMany manyToManyAnnotation = method.getAnnotation(ManyToMany.class);
OnUpdate onUpdateAnnotation = method.getAnnotation(OnUpdate.class);
if (mutatorAnnotation != null) {
invokeSetter((T) proxy, mutatorAnnotation.value(), args[0], onUpdateAnnotation != null);
return Void.TYPE;
} else if (accessorAnnotation != null) {
return invokeGetter(getID(), tableName, accessorAnnotation.value(), method.getReturnType(), onUpdateAnnotation != null);
} else if (oneToManyAnnotation != null && method.getReturnType().isArray()
&& Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) {
Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType();
return retrieveRelations((Entity) proxy, new String[0], new String[] { "id" }, (Class<? extends Entity>) type, oneToManyAnnotation.where());
} else if (manyToManyAnnotation != null && method.getReturnType().isArray()
&& Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) {
Class<? extends Entity> throughType = manyToManyAnnotation.value();
Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType();
return retrieveRelations((Entity) proxy, null, Common.getMappingFields(throughType, type), throughType, type, manyToManyAnnotation.where());
} else if (method.getName().startsWith("get")) {
String name = Common.convertDowncaseName(method.getName().substring(3));
if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) {
name += "ID";
}
return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation == null);
} else if (method.getName().startsWith("is")) {
String name = Common.convertDowncaseName(method.getName().substring(2));
if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) {
name += "ID";
}
return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation == null);
} else if (method.getName().startsWith("set")) {
String name = Common.convertDowncaseName(method.getName().substring(3));
if (Common.interfaceInheritsFrom(method.getParameterTypes()[0], Entity.class)) {
name += "ID";
}
invokeSetter((T) proxy, name, args[0], onUpdateAnnotation == null);
return Void.TYPE;
}
return null;
}
public int getID() {
return id;
}
public String getTableName() {
return getManager().getNameConverter().getName(type);
}
@SuppressWarnings("unchecked")
public void save(Entity entity) throws SQLException {
dirtyFieldsLock.writeLock().lock();
try {
if (dirtyFields.isEmpty()) {
return;
}
String table = getTableName();
TypeManager manager = TypeManager.getInstance();
Connection conn = getConnectionImpl();
cacheLock.readLock().lock();
try {
StringBuilder sql = new StringBuilder("UPDATE " + table + " SET ");
for (String field : dirtyFields) {
sql.append(field);
if (cache.containsKey(field)) {
sql.append(" = ?,");
} else {
sql.append(" = NULL,");
}
}
if (dirtyFields.size() > 0) {
sql.setLength(sql.length() - 1);
}
sql.append(" WHERE id = ?");
Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
int index = 1;
for (String field : dirtyFields) {
if (cache.containsKey(field)) {
Object obj = cache.get(field);
Class javaType = obj.getClass();
if (obj instanceof Entity) {
javaType = ((Entity) obj).getEntityType();
}
manager.getType(javaType).putToDatabase(index++, stmt, obj);
} else if (nullSet.contains(field)) {
stmt.setString(index++, null);
}
}
stmt.setInt(index++, id);
toFlushLock.writeLock().lock();
try {
getManager().getRelationsCache().remove(toFlushRelations.toArray(new Class[toFlushRelations.size()]));
toFlushRelations.clear();
} finally {
toFlushLock.writeLock().unlock();
}
getManager().getRelationsCache().remove(entity, type, dirtyFields.toArray(new String[dirtyFields.size()]));
stmt.executeUpdate();
dirtyFields.removeAll(dirtyFields);
stmt.close();
} finally {
cacheLock.readLock().unlock();
closeConnectionImpl(conn);
}
} finally {
dirtyFieldsLock.writeLock().unlock();
}
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.add(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
listeners.remove(listener);
}
public int hashCodeImpl() {
return (int) (new Random(getID()).nextFloat() * getID()) + getID() % (2 << 15);
}
public boolean equalsImpl(Entity proxy, Object obj) {
if (proxy == obj) {
return true;
}
if (obj instanceof Entity) {
Entity entity = (Entity) obj;
return entity.getID() == proxy.getID() && entity.getTableName().equals(proxy.getTableName());
}
return false;
}
public String toStringImpl() {
return getManager().getNameConverter().getName(type) + " {id = " + getID() + "}";
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof EntityProxy) {
EntityProxy<?> proxy = (EntityProxy<?>) obj;
if (proxy.type.equals(type) && proxy.id == id) {
return true;
}
}
return false;
}
public int hashCode() {
return type.hashCode();
}
void addToCache(String key, Object value) {
if (key.trim().equalsIgnoreCase("id")) {
return;
}
cacheLock.writeLock().lock();
try {
if (value == null) {
nullSet.add(key);
} else if (!cache.containsKey(key)) {
cache.put(key, value);
}
} finally {
cacheLock.writeLock().unlock();
}
}
Class<T> getType() {
return type;
}
// any dirty fields are kept in the cache, since they have yet to be saved
void flushCache() {
cacheLock.writeLock().lock();
dirtyFieldsLock.readLock().lock();
try {
for (String fieldName : cache.keySet()) {
if (!dirtyFields.contains(fieldName)) {
cache.remove(fieldName);
nullSet.remove(fieldName);
}
}
} finally {
dirtyFieldsLock.readLock().unlock();
cacheLock.writeLock().unlock();
}
}
private EntityManager getManager() {
return manager;
}
private Connection getConnectionImpl() throws SQLException {
return getManager().getProvider().getConnection();
}
private void closeConnectionImpl(Connection conn) throws SQLException {
conn.close();
}
private <V> V invokeGetter(int id, String table, String name, Class<V> type, boolean shouldCache) throws Throwable {
V back = null;
if (shouldCache) {
cacheLock.writeLock().lock();
}
try {
if (shouldCache && nullSet.contains(name)) {
return null;
} else if (shouldCache && cache.containsKey(name)) {
Object value = cache.get(name);
if (instanceOf(value, type)) {
return (V) value;
} else if (Common.interfaceInheritsFrom(type, Entity.class) && value instanceof Integer) {
value = getManager().get((Class<? extends Entity>) type, (Integer) value);
cache.put(name, value);
return (V) value;
} else {
cache.remove(name); // invalid cached value
}
}
Connection conn = getConnectionImpl();
try {
String sql = "SELECT " + name + " FROM " + table + " WHERE id = ?";
Logger.getLogger("net.java.ao").log(Level.INFO, sql);
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
ResultSet res = stmt.executeQuery();
if (res.next()) {
back = convertValue(res, name, type);
}
res.close();
stmt.close();
} finally {
closeConnectionImpl(conn);
}
if (shouldCache) {
cache.put(name, back);
if (back == null) {
nullSet.add(name);
}
}
} finally {
if (shouldCache) {
cacheLock.writeLock().unlock();
}
}
return back;
}
private void invokeSetter(T entity, String name, Object value, boolean shouldCache) throws Throwable {
Object oldValue = null;
cacheLock.readLock().lock();
try {
if (cache.containsKey(name)) {
oldValue = cache.get(name);
}
} finally {
cacheLock.readLock().unlock();
}
if (value instanceof Entity) {
toFlushLock.writeLock().lock();
try {
toFlushRelations.add(((Entity) value).getEntityType());
} finally {
toFlushLock.writeLock().unlock();
}
}
invokeSetterImpl(name, value);
PropertyChangeEvent evt = new PropertyChangeEvent(entity, name, oldValue, value);
for (PropertyChangeListener l : listeners) {
l.propertyChange(evt);
}
dirtyFieldsLock.writeLock().lock();
try {
dirtyFields.add(name);
} finally {
dirtyFieldsLock.writeLock().unlock();
}
}
private void invokeSetterImpl(String name, Object value) throws Throwable {
cacheLock.writeLock().lock();
try {
cache.put(name, value);
if (value != null) {
nullSet.remove(name);
} else {
nullSet.add(name);
}
} finally {
cacheLock.writeLock().unlock();
}
}
private <V extends Entity> V[] retrieveRelations(Entity entity, String[] inMapFields, String[] outMapFields, Class<V> type, String where) throws SQLException {
return retrieveRelations(entity, inMapFields, outMapFields, type, type, where);
}
private <V extends Entity> V[] retrieveRelations(Entity entity, String[] inMapFields, String[] outMapFields, Class<? extends Entity> type,
Class<V> finalType, String where) throws SQLException {
String[] fields = getFields(outMapFields, where);
V[] cached = getManager().getRelationsCache().get(entity, finalType, fields);
if (cached != null) {
return cached;
}
List<V> back = new ArrayList<V>();
String table = getManager().getNameConverter().getName(type);
boolean oneToMany = inMapFields == null || inMapFields.length == 0;
Preload preloadAnnotation = finalType.getAnnotation(Preload.class);
Connection conn = getConnectionImpl();
if (oneToMany) {
inMapFields = Common.getMappingFields(type, this.type);
}
try {
StringBuilder sql = new StringBuilder();
String returnField;
int numParams = 0;
if (oneToMany && inMapFields.length == 1 && outMapFields.length == 1 && preloadAnnotation != null) {
sql.append("SELECT ");
- sql.append(inMapFields[0]).append(',');
+ sql.append(outMapFields[0]).append(',');
for (String field : preloadAnnotation.value()) {
sql.append(field).append(',');
}
sql.setLength(sql.length() - 1);
sql.append(" FROM ").append(table);
sql.append(" WHERE ").append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
- returnField = inMapFields[0];
+ returnField = outMapFields[0];
} else if (!oneToMany && inMapFields.length == 1 && outMapFields.length == 1 && preloadAnnotation != null) {
String finalTable = getManager().getNameConverter().getName(finalType);
sql.append("SELECT ");
sql.append(finalTable).append(".id,");
for (String field : preloadAnnotation.value()) {
sql.append(finalTable).append('.').append(field).append(',');
}
sql.setLength(sql.length() - 1);
sql.append(" FROM ").append(table).append(" INNER JOIN ");
sql.append(finalTable).append(" ON ");
sql.append(table).append('.').append(inMapFields[0]);
sql.append(" = ").append(finalTable).append(".id");
sql.append(" WHERE ").append(table).append('.').append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = "id";
} else if (inMapFields.length == 1 && outMapFields.length == 1) {
sql.append("SELECT ").append(outMapFields[0]).append(" FROM ").append(table);
sql.append(" WHERE ").append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = outMapFields[0];
} else {
sql.append("SELECT DISTINCT a.outMap AS outMap FROM (");
returnField = "outMap";
for (String outMap : outMapFields) {
for (String inMap : inMapFields) {
sql.append("SELECT ");
sql.append(outMap);
sql.append(" AS outMap,");
sql.append(inMap);
sql.append(" AS inMap FROM ");
sql.append(table);
sql.append(" WHERE ");
sql.append(inMap).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
sql.append(" UNION ");
numParams++;
}
}
sql.setLength(sql.length() - " UNION ".length());
sql.append(") a");
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
for (int i = 0; i < numParams; i++) {
stmt.setInt(i + 1, id);
}
ResultSet res = stmt.executeQuery();
while (res.next()) {
int returnValue = res.getInt(returnField);
if (finalType.equals(this.type) && returnValue == id) {
continue;
}
V returnValueEntity = getManager().get(finalType, returnValue);
ResultSetMetaData md = res.getMetaData();
for (int i = 0; i < md.getColumnCount(); i++) {
getManager().getProxyForEntity(returnValueEntity).addToCache(md.getColumnName(i + 1), res.getObject(i + 1));
}
back.add(returnValueEntity);
}
res.close();
stmt.close();
} finally {
closeConnectionImpl(conn);
}
cached = back.toArray((V[]) Array.newInstance(finalType, back.size()));
if (type.equals(finalType)) { // only cache one-to-many
getManager().getRelationsCache().put(entity, cached, fields);
}
return cached;
}
private String[] getFields(String[] mapFields, String where) {
List<String> back = new ArrayList<String>();
back.addAll(Arrays.asList(mapFields));
Matcher matcher = WHERE_PATTERN.matcher(where);
while (matcher.find()) {
back.add(matcher.group(1));
}
return back.toArray(new String[back.size()]);
}
private <V> V convertValue(ResultSet res, String field, Class<V> type) throws SQLException {
if (res.getString(field) == null) {
return null;
}
TypeManager manager = TypeManager.getInstance();
DatabaseType<V> databaseType = manager.getType(type);
if (databaseType == null) {
throw new RuntimeException("UnrecognizedType: " + type.toString());
}
return databaseType.convert(getManager(), res, type, field);
}
private boolean instanceOf(Object value, Class<?> type) {
if (type.isPrimitive()) {
if (type.equals(boolean.class)) {
return instanceOf(value, Boolean.class);
} else if (type.equals(char.class)) {
return instanceOf(value, Character.class);
} else if (type.equals(byte.class)) {
return instanceOf(value, Byte.class);
} else if (type.equals(short.class)) {
return instanceOf(value, Short.class);
} else if (type.equals(int.class)) {
return instanceOf(value, Integer.class);
} else if (type.equals(long.class)) {
return instanceOf(value, Long.class);
} else if (type.equals(float.class)) {
return instanceOf(value, Float.class);
} else if (type.equals(double.class)) {
return instanceOf(value, Double.class);
}
} else {
return type.isInstance(value);
}
return false;
}
}
| false | true | private <V extends Entity> V[] retrieveRelations(Entity entity, String[] inMapFields, String[] outMapFields, Class<? extends Entity> type,
Class<V> finalType, String where) throws SQLException {
String[] fields = getFields(outMapFields, where);
V[] cached = getManager().getRelationsCache().get(entity, finalType, fields);
if (cached != null) {
return cached;
}
List<V> back = new ArrayList<V>();
String table = getManager().getNameConverter().getName(type);
boolean oneToMany = inMapFields == null || inMapFields.length == 0;
Preload preloadAnnotation = finalType.getAnnotation(Preload.class);
Connection conn = getConnectionImpl();
if (oneToMany) {
inMapFields = Common.getMappingFields(type, this.type);
}
try {
StringBuilder sql = new StringBuilder();
String returnField;
int numParams = 0;
if (oneToMany && inMapFields.length == 1 && outMapFields.length == 1 && preloadAnnotation != null) {
sql.append("SELECT ");
sql.append(inMapFields[0]).append(',');
for (String field : preloadAnnotation.value()) {
sql.append(field).append(',');
}
sql.setLength(sql.length() - 1);
sql.append(" FROM ").append(table);
sql.append(" WHERE ").append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = inMapFields[0];
} else if (!oneToMany && inMapFields.length == 1 && outMapFields.length == 1 && preloadAnnotation != null) {
String finalTable = getManager().getNameConverter().getName(finalType);
sql.append("SELECT ");
sql.append(finalTable).append(".id,");
for (String field : preloadAnnotation.value()) {
sql.append(finalTable).append('.').append(field).append(',');
}
sql.setLength(sql.length() - 1);
sql.append(" FROM ").append(table).append(" INNER JOIN ");
sql.append(finalTable).append(" ON ");
sql.append(table).append('.').append(inMapFields[0]);
sql.append(" = ").append(finalTable).append(".id");
sql.append(" WHERE ").append(table).append('.').append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = "id";
} else if (inMapFields.length == 1 && outMapFields.length == 1) {
sql.append("SELECT ").append(outMapFields[0]).append(" FROM ").append(table);
sql.append(" WHERE ").append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = outMapFields[0];
} else {
sql.append("SELECT DISTINCT a.outMap AS outMap FROM (");
returnField = "outMap";
for (String outMap : outMapFields) {
for (String inMap : inMapFields) {
sql.append("SELECT ");
sql.append(outMap);
sql.append(" AS outMap,");
sql.append(inMap);
sql.append(" AS inMap FROM ");
sql.append(table);
sql.append(" WHERE ");
sql.append(inMap).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
sql.append(" UNION ");
numParams++;
}
}
sql.setLength(sql.length() - " UNION ".length());
sql.append(") a");
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
for (int i = 0; i < numParams; i++) {
stmt.setInt(i + 1, id);
}
ResultSet res = stmt.executeQuery();
while (res.next()) {
int returnValue = res.getInt(returnField);
if (finalType.equals(this.type) && returnValue == id) {
continue;
}
V returnValueEntity = getManager().get(finalType, returnValue);
ResultSetMetaData md = res.getMetaData();
for (int i = 0; i < md.getColumnCount(); i++) {
getManager().getProxyForEntity(returnValueEntity).addToCache(md.getColumnName(i + 1), res.getObject(i + 1));
}
back.add(returnValueEntity);
}
res.close();
stmt.close();
} finally {
closeConnectionImpl(conn);
}
cached = back.toArray((V[]) Array.newInstance(finalType, back.size()));
if (type.equals(finalType)) { // only cache one-to-many
getManager().getRelationsCache().put(entity, cached, fields);
}
return cached;
}
| private <V extends Entity> V[] retrieveRelations(Entity entity, String[] inMapFields, String[] outMapFields, Class<? extends Entity> type,
Class<V> finalType, String where) throws SQLException {
String[] fields = getFields(outMapFields, where);
V[] cached = getManager().getRelationsCache().get(entity, finalType, fields);
if (cached != null) {
return cached;
}
List<V> back = new ArrayList<V>();
String table = getManager().getNameConverter().getName(type);
boolean oneToMany = inMapFields == null || inMapFields.length == 0;
Preload preloadAnnotation = finalType.getAnnotation(Preload.class);
Connection conn = getConnectionImpl();
if (oneToMany) {
inMapFields = Common.getMappingFields(type, this.type);
}
try {
StringBuilder sql = new StringBuilder();
String returnField;
int numParams = 0;
if (oneToMany && inMapFields.length == 1 && outMapFields.length == 1 && preloadAnnotation != null) {
sql.append("SELECT ");
sql.append(outMapFields[0]).append(',');
for (String field : preloadAnnotation.value()) {
sql.append(field).append(',');
}
sql.setLength(sql.length() - 1);
sql.append(" FROM ").append(table);
sql.append(" WHERE ").append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = outMapFields[0];
} else if (!oneToMany && inMapFields.length == 1 && outMapFields.length == 1 && preloadAnnotation != null) {
String finalTable = getManager().getNameConverter().getName(finalType);
sql.append("SELECT ");
sql.append(finalTable).append(".id,");
for (String field : preloadAnnotation.value()) {
sql.append(finalTable).append('.').append(field).append(',');
}
sql.setLength(sql.length() - 1);
sql.append(" FROM ").append(table).append(" INNER JOIN ");
sql.append(finalTable).append(" ON ");
sql.append(table).append('.').append(inMapFields[0]);
sql.append(" = ").append(finalTable).append(".id");
sql.append(" WHERE ").append(table).append('.').append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = "id";
} else if (inMapFields.length == 1 && outMapFields.length == 1) {
sql.append("SELECT ").append(outMapFields[0]).append(" FROM ").append(table);
sql.append(" WHERE ").append(inMapFields[0]).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
numParams++;
returnField = outMapFields[0];
} else {
sql.append("SELECT DISTINCT a.outMap AS outMap FROM (");
returnField = "outMap";
for (String outMap : outMapFields) {
for (String inMap : inMapFields) {
sql.append("SELECT ");
sql.append(outMap);
sql.append(" AS outMap,");
sql.append(inMap);
sql.append(" AS inMap FROM ");
sql.append(table);
sql.append(" WHERE ");
sql.append(inMap).append(" = ?");
if (!where.trim().equals("")) {
sql.append(" AND (").append(where).append(")");
}
sql.append(" UNION ");
numParams++;
}
}
sql.setLength(sql.length() - " UNION ".length());
sql.append(") a");
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
for (int i = 0; i < numParams; i++) {
stmt.setInt(i + 1, id);
}
ResultSet res = stmt.executeQuery();
while (res.next()) {
int returnValue = res.getInt(returnField);
if (finalType.equals(this.type) && returnValue == id) {
continue;
}
V returnValueEntity = getManager().get(finalType, returnValue);
ResultSetMetaData md = res.getMetaData();
for (int i = 0; i < md.getColumnCount(); i++) {
getManager().getProxyForEntity(returnValueEntity).addToCache(md.getColumnName(i + 1), res.getObject(i + 1));
}
back.add(returnValueEntity);
}
res.close();
stmt.close();
} finally {
closeConnectionImpl(conn);
}
cached = back.toArray((V[]) Array.newInstance(finalType, back.size()));
if (type.equals(finalType)) { // only cache one-to-many
getManager().getRelationsCache().put(entity, cached, fields);
}
return cached;
}
|
diff --git a/src/com/softeoz/bookmarktree/domain/UrlDocument.java b/src/com/softeoz/bookmarktree/domain/UrlDocument.java
index fbb8311..c820c43 100644
--- a/src/com/softeoz/bookmarktree/domain/UrlDocument.java
+++ b/src/com/softeoz/bookmarktree/domain/UrlDocument.java
@@ -1,110 +1,112 @@
package com.softeoz.bookmarktree.domain;
import org.primefaces.model.TreeNode;
public class UrlDocument {
private String name;
private String url;
private String fullPath;
private String parentPath;
private TreeNode parentNode;
public UrlDocument() {
}
public UrlDocument(String name, String url, TreeNode parent) {
setName(name);
setUrl(url);
setParentNode(parent);
pathUpdate();
}
public void pathUpdate() {
Path fullPathProxy = new Path();
- // Path parentPath = new Path();
+ Path parentPathProxy = new Path();
if (isTop()) {
// setParentPath(null);
// setFullPath(null);
- // parentPath.setValue(null);
+ parentPathProxy.setValue(null);
fullPathProxy.setValue(null);
} else {
if (isRoot()) {
// setParentPath("");
// setFullPath(name);
- // parentPath.setValue("");
+ parentPathProxy.setValue("");
fullPathProxy.setValue(name);
} else {
// setParentPath(((UrlDocument) getParentNode().getData())
// .getFullPath());
// setFullPath(parentPath + "/" + name);
- // parentPath.setValue(((UrlDocument) getParentNode().getData())
- // .getFullPath());
+ parentPathProxy.setValue(((UrlDocument) getParentNode()
+ .getData()).getFullPath());
+ fullPathProxy.setValue(parentPathProxy.getValue());
fullPathProxy.add(name);
}
}
fullPath = fullPathProxy.getValue();
+ parentPath = parentPathProxy.getValue();
}
public String getFullPath() {
return fullPath;
}
public void setFullPath(String path) {
this.fullPath = path;
}
public boolean isRoot() {
return getParentNode().getParent() == null;
}
public boolean isTop() {
return getParentNode() == null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
pathUpdate();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public TreeNode getParentNode() {
return parentNode;
}
public void setParentNode(TreeNode node) {
this.parentNode = node;
}
public String getParentPath() {
return parentPath;
}
public void setParentPath(String parentPath) {
this.parentPath = parentPath;
}
@Override
public String toString() {
return fullPath;
}
}
| false | true | public void pathUpdate() {
Path fullPathProxy = new Path();
// Path parentPath = new Path();
if (isTop()) {
// setParentPath(null);
// setFullPath(null);
// parentPath.setValue(null);
fullPathProxy.setValue(null);
} else {
if (isRoot()) {
// setParentPath("");
// setFullPath(name);
// parentPath.setValue("");
fullPathProxy.setValue(name);
} else {
// setParentPath(((UrlDocument) getParentNode().getData())
// .getFullPath());
// setFullPath(parentPath + "/" + name);
// parentPath.setValue(((UrlDocument) getParentNode().getData())
// .getFullPath());
fullPathProxy.add(name);
}
}
fullPath = fullPathProxy.getValue();
}
| public void pathUpdate() {
Path fullPathProxy = new Path();
Path parentPathProxy = new Path();
if (isTop()) {
// setParentPath(null);
// setFullPath(null);
parentPathProxy.setValue(null);
fullPathProxy.setValue(null);
} else {
if (isRoot()) {
// setParentPath("");
// setFullPath(name);
parentPathProxy.setValue("");
fullPathProxy.setValue(name);
} else {
// setParentPath(((UrlDocument) getParentNode().getData())
// .getFullPath());
// setFullPath(parentPath + "/" + name);
parentPathProxy.setValue(((UrlDocument) getParentNode()
.getData()).getFullPath());
fullPathProxy.setValue(parentPathProxy.getValue());
fullPathProxy.add(name);
}
}
fullPath = fullPathProxy.getValue();
parentPath = parentPathProxy.getValue();
}
|
diff --git a/plugins/GexPlugin/src/org/pathvisio/plugins/gex/GexTxtImporter.java b/plugins/GexPlugin/src/org/pathvisio/plugins/gex/GexTxtImporter.java
index d7cbbbae..e0e0cf27 100644
--- a/plugins/GexPlugin/src/org/pathvisio/plugins/gex/GexTxtImporter.java
+++ b/plugins/GexPlugin/src/org/pathvisio/plugins/gex/GexTxtImporter.java
@@ -1,316 +1,319 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2009 BiGCaT Bioinformatics
//
// 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.pathvisio.plugins.gex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.Types;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.bridgedb.IDMapper;
import org.bridgedb.IDMapperException;
import org.bridgedb.DataSource;
import org.bridgedb.Xref;
import org.bridgedb.rdb.IDMapperRdb;
import org.pathvisio.debug.Logger;
import org.pathvisio.debug.StopWatch;
import org.pathvisio.gex.GexManager;
import org.pathvisio.gex.SimpleGex;
import org.pathvisio.plugins.gex.ImportInformation.ColumnType;
import org.pathvisio.util.FileUtils;
import org.pathvisio.util.ProgressKeeper;
/**
* Functions to create a new Gex database
* based on a text file.
*/
public class GexTxtImporter
{
/**
* Imports expression data from a text file and saves it to an hsqldb expression database
* @param info {@link GexImportWizard.ImportInformation} object that contains the
* information needed to import the data
* @param p {@link ProgressKeeper} that reports the progress of the process and enables
* the user to cancel. May be null for headless mode operation.
*/
public static void importFromTxt(ImportInformation info, ProgressKeeper p, IDMapper currentGdb, GexManager gexManager)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getGexName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getGexName(), true, gexManager.getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
List<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
ColumnType type = info.getColumnType(i);
//skip the id and systemcode column if there is one
if(type == ColumnType.COL_NUMBER || type == ColumnType.COL_STRING)
{
String header = headers[i];
if (header.length() >= 50)
{
header = header.substring(0, 49);
}
try {
result.addSample(
sampleId++,
header,
type == ColumnType.COL_STRING ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 0; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow();
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
NumberFormat nf = NumberFormat.getInstance(
info.digitIsDot() ? Locale.US : Locale.FRANCE);
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.isSyscodeFixed())
{
ds = info.getDataSource();
}
else
{
ds = DataSource.getBySystemCode(data[info.getSyscodeColumn()].trim());
}
Xref ref = new Xref (id, ds);
//check if the ref exists
boolean refExists = currentGdb.xrefExists(ref);
if(!refExists)
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
- "\tCould not look up this identifier in the synonym database", errors);
- }
+ "\tError: Could not look up this identifier in the synonym database", errors);
+ } else {
+ errors = reportError(info, error, "Line " + n + ":\t" + ref +
+ "\t", errors - 1); // decrement counter to count only the errors
+ }
// add row anyway
{
boolean success = true;
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
double dNumber = nf.parse(value.toUpperCase()).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (ParseException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
result.addExpr(
ref,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
in.close();
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " rows of data were imported succesfully");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null)
{
p.setTaskName("Finalizing database (this may take some time)");
p.report ("Finalizing database");
}
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
gexManager.setCurrentGex(result.getDbName(), false);
if (p != null)
{
p.setTaskName ("Done.");
p.report ("Done.");
p.finished();
}
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (IDMapperException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
private static int reportError(ImportInformation info, PrintStream log, String message, int nrError)
{
info.addError(message);
log.println(message);
nrError++;
return nrError;
}
}
| true | true | public static void importFromTxt(ImportInformation info, ProgressKeeper p, IDMapper currentGdb, GexManager gexManager)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getGexName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getGexName(), true, gexManager.getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
List<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
ColumnType type = info.getColumnType(i);
//skip the id and systemcode column if there is one
if(type == ColumnType.COL_NUMBER || type == ColumnType.COL_STRING)
{
String header = headers[i];
if (header.length() >= 50)
{
header = header.substring(0, 49);
}
try {
result.addSample(
sampleId++,
header,
type == ColumnType.COL_STRING ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 0; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow();
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
NumberFormat nf = NumberFormat.getInstance(
info.digitIsDot() ? Locale.US : Locale.FRANCE);
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.isSyscodeFixed())
{
ds = info.getDataSource();
}
else
{
ds = DataSource.getBySystemCode(data[info.getSyscodeColumn()].trim());
}
Xref ref = new Xref (id, ds);
//check if the ref exists
boolean refExists = currentGdb.xrefExists(ref);
if(!refExists)
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tCould not look up this identifier in the synonym database", errors);
}
// add row anyway
{
boolean success = true;
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
double dNumber = nf.parse(value.toUpperCase()).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (ParseException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
result.addExpr(
ref,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
in.close();
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " rows of data were imported succesfully");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null)
{
p.setTaskName("Finalizing database (this may take some time)");
p.report ("Finalizing database");
}
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
gexManager.setCurrentGex(result.getDbName(), false);
if (p != null)
{
p.setTaskName ("Done.");
p.report ("Done.");
p.finished();
}
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (IDMapperException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
| public static void importFromTxt(ImportInformation info, ProgressKeeper p, IDMapper currentGdb, GexManager gexManager)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getGexName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getGexName(), true, gexManager.getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
List<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
ColumnType type = info.getColumnType(i);
//skip the id and systemcode column if there is one
if(type == ColumnType.COL_NUMBER || type == ColumnType.COL_STRING)
{
String header = headers[i];
if (header.length() >= 50)
{
header = header.substring(0, 49);
}
try {
result.addSample(
sampleId++,
header,
type == ColumnType.COL_STRING ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 0; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow();
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
NumberFormat nf = NumberFormat.getInstance(
info.digitIsDot() ? Locale.US : Locale.FRANCE);
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.isSyscodeFixed())
{
ds = info.getDataSource();
}
else
{
ds = DataSource.getBySystemCode(data[info.getSyscodeColumn()].trim());
}
Xref ref = new Xref (id, ds);
//check if the ref exists
boolean refExists = currentGdb.xrefExists(ref);
if(!refExists)
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tError: Could not look up this identifier in the synonym database", errors);
} else {
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\t", errors - 1); // decrement counter to count only the errors
}
// add row anyway
{
boolean success = true;
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
double dNumber = nf.parse(value.toUpperCase()).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (ParseException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
result.addExpr(
ref,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
in.close();
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " rows of data were imported succesfully");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null)
{
p.setTaskName("Finalizing database (this may take some time)");
p.report ("Finalizing database");
}
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
gexManager.setCurrentGex(result.getDbName(), false);
if (p != null)
{
p.setTaskName ("Done.");
p.report ("Done.");
p.finished();
}
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (IDMapperException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
|
diff --git a/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMergeCommand.java b/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMergeCommand.java
index 56feb57b2..feb69b0a2 100644
--- a/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMergeCommand.java
+++ b/svnkit-cli/src/main/java/org/tmatesoft/svn/cli/svn/SVNMergeCommand.java
@@ -1,266 +1,266 @@
/*
* ====================================================================
* Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.cli.svn;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNFileType;
import org.tmatesoft.svn.core.internal.wc.SVNPath;
import org.tmatesoft.svn.core.wc.SVNDiffClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNRevisionRange;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.3
* @author TMate Software Ltd.
*/
public class SVNMergeCommand extends SVNCommand {
public SVNMergeCommand() {
super("merge", null);
}
protected Collection createSupportedOptions() {
Collection options = new LinkedList();
options.add(SVNOption.REVISION);
options.add(SVNOption.CHANGE);
options.add(SVNOption.NON_RECURSIVE);
options.add(SVNOption.DEPTH);
options.add(SVNOption.QUIET);
options.add(SVNOption.FORCE);
options.add(SVNOption.DRY_RUN);
options.add(SVNOption.DIFF3_CMD);
options.add(SVNOption.RECORD_ONLY);
options.add(SVNOption.EXTENSIONS);
options.add(SVNOption.IGNORE_ANCESTRY);
options.add(SVNOption.ACCEPT);
options.add(SVNOption.REINTEGRATE);
options.add(SVNOption.ALLOW_MIXED_REVISIONS);
return options;
}
public boolean acceptsRevisionRange() {
return true;
}
public void run() throws SVNException {
List targets = getSVNEnvironment().combineTargets(new ArrayList(), true);
SVNPath source1 = null;
SVNPath source2 = null;
SVNPath target = null;
SVNRevision pegRevision1 = null;
SVNRevision pegRevision2 = null;
if (targets.size() >= 1) {
source1 = new SVNPath((String) targets.get(0), true);
pegRevision1 = source1.getPegRevision();
if (targets.size() >= 2) {
source2 = new SVNPath((String) targets.get(1), true);
pegRevision2 = source2.getPegRevision();
}
}
boolean twoSourcesSpecified = true;
if (targets.size() <= 1) {
twoSourcesSpecified = false;
} else if (targets.size() == 2) {
if (source1.isURL() && !source2.isURL()) {
twoSourcesSpecified = false;
}
}
List rangesToMerge = getSVNEnvironment().getRevisionRanges();
SVNRevision firstRangeStart = SVNRevision.UNDEFINED;
SVNRevision firstRangeEnd = SVNRevision.UNDEFINED;
if (!rangesToMerge.isEmpty()) {
SVNRevisionRange range = (SVNRevisionRange) rangesToMerge.get(0);
firstRangeStart = range.getStartRevision();
firstRangeEnd = range.getEndRevision();
}
if (firstRangeStart != SVNRevision.UNDEFINED) {
if (firstRangeEnd == SVNRevision.UNDEFINED) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS,
"Second revision required");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
twoSourcesSpecified = false;
}
if (!twoSourcesSpecified) {
if (targets.size() > 2) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Too many arguments given"), SVNLogType.CLIENT);
}
if (targets.isEmpty()) {
pegRevision1 = SVNRevision.HEAD;
} else {
source2 = source1;
if (pegRevision1 == null || pegRevision1 == SVNRevision.UNDEFINED) {
pegRevision1 = source1.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING;
}
if (targets.size() == 2) {
target = new SVNPath((String) targets.get(1));
if (target.isURL()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Cannot specifify a revision range with two URLs");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
}
} else {
if (targets.size() < 2) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT);
} else if (targets.size() > 3) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Too many arguments given"), SVNLogType.CLIENT);
}
firstRangeStart = pegRevision1;
firstRangeEnd = pegRevision2;
if (((firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) && !source1.isURL()) ||
((pegRevision2 == null || pegRevision2 == SVNRevision.UNDEFINED) && !source2.isURL())) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION,
"A working copy merge source needs an explicit revision"), SVNLogType.CLIENT);
}
if (firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) {
firstRangeStart = SVNRevision.HEAD;
}
if (firstRangeEnd == null || firstRangeEnd == SVNRevision.UNDEFINED) {
firstRangeEnd = SVNRevision.HEAD;
}
if (targets.size() >= 3) {
target = new SVNPath((String) targets.get(2));
}
}
if (source1 != null && source2 != null && target == null) {
if (source1.isURL()) {
String name1 = SVNPathUtil.tail(source1.getTarget());
String name2 = SVNPathUtil.tail(source2.getTarget());
if (name1.equals(name2)) {
String decodedPath = SVNEncodingUtil.uriDecode(name1);
SVNPath decodedPathTarget = new SVNPath(decodedPath);
if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) {
target = decodedPathTarget;
}
}
} else if (source1.equals(source2)) {
String decodedPath = SVNEncodingUtil.uriDecode(source1.getTarget());
SVNPath decodedPathTarget = new SVNPath(decodedPath);
if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) {
target = decodedPathTarget;
}
}
}
if (target == null) {
target = new SVNPath("");
}
SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient();
if (!getSVNEnvironment().isQuiet()) {
client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment()));
}
- client.setAllowMixedRevisions(getSVNEnvironment().isAllowMixedRevisions());
+ client.setAllowMixedRevisionsWCForMerge(getSVNEnvironment().isAllowMixedRevisions());
try {
client.setMergeOptions(getSVNEnvironment().getDiffOptions());
if (!twoSourcesSpecified) {
if (firstRangeStart == SVNRevision.UNDEFINED && firstRangeEnd == SVNRevision.UNDEFINED) {
SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), pegRevision1);
rangesToMerge = new LinkedList();
rangesToMerge.add(range);
}
if (source1 == null) {
source1 = target;
}
if (getSVNEnvironment().isReIntegrate()) {
if (getSVNEnvironment().getDepth() != SVNDepth.UNKNOWN) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS,
"--depth cannot be used with --reintegrate");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (getSVNEnvironment().isForce()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS,
"--force cannot be used with --reintegrate");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (source1.isURL()) {
client.doMergeReIntegrate(source1.getURL(), pegRevision1, target.getFile(),
getSVNEnvironment().isDryRun());
} else {
client.doMergeReIntegrate(source1.getFile(), pegRevision1, target.getFile(),
getSVNEnvironment().isDryRun());
}
} else {
if (source1.isURL()) {
client.doMerge(source1.getURL(), pegRevision1, rangesToMerge, target.getFile(),
getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(),
getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(),
getSVNEnvironment().isRecordOnly());
} else {
client.doMerge(source1.getFile(), pegRevision1, rangesToMerge, target.getFile(),
getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(),
getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(),
getSVNEnvironment().isRecordOnly());
}
}
} else {
if (source1.isURL() && source2.isURL()) {
client.doMerge(source1.getURL(), firstRangeStart, source2.getURL(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else if (source1.isURL() && source2.isFile()) {
client.doMerge(source1.getURL(), firstRangeStart, source2.getFile(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else if (source1.isFile() && source2.isURL()) {
client.doMerge(source1.getFile(), firstRangeStart, source2.getURL(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else {
client.doMerge(source1.getFile(), firstRangeStart, source2.getFile(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
}
}
} catch (SVNException e) {
SVNErrorMessage err = e.getErrorMessage();
if (err != null && !getSVNEnvironment().isReIntegrate()) {
SVNErrorCode code = err.getErrorCode();
if (code == SVNErrorCode.UNVERSIONED_RESOURCE || code == SVNErrorCode.CLIENT_MODIFIED) {
err = err.wrap("Use --force to override this restriction");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
throw e;
}
}
}
| true | true | public void run() throws SVNException {
List targets = getSVNEnvironment().combineTargets(new ArrayList(), true);
SVNPath source1 = null;
SVNPath source2 = null;
SVNPath target = null;
SVNRevision pegRevision1 = null;
SVNRevision pegRevision2 = null;
if (targets.size() >= 1) {
source1 = new SVNPath((String) targets.get(0), true);
pegRevision1 = source1.getPegRevision();
if (targets.size() >= 2) {
source2 = new SVNPath((String) targets.get(1), true);
pegRevision2 = source2.getPegRevision();
}
}
boolean twoSourcesSpecified = true;
if (targets.size() <= 1) {
twoSourcesSpecified = false;
} else if (targets.size() == 2) {
if (source1.isURL() && !source2.isURL()) {
twoSourcesSpecified = false;
}
}
List rangesToMerge = getSVNEnvironment().getRevisionRanges();
SVNRevision firstRangeStart = SVNRevision.UNDEFINED;
SVNRevision firstRangeEnd = SVNRevision.UNDEFINED;
if (!rangesToMerge.isEmpty()) {
SVNRevisionRange range = (SVNRevisionRange) rangesToMerge.get(0);
firstRangeStart = range.getStartRevision();
firstRangeEnd = range.getEndRevision();
}
if (firstRangeStart != SVNRevision.UNDEFINED) {
if (firstRangeEnd == SVNRevision.UNDEFINED) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS,
"Second revision required");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
twoSourcesSpecified = false;
}
if (!twoSourcesSpecified) {
if (targets.size() > 2) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Too many arguments given"), SVNLogType.CLIENT);
}
if (targets.isEmpty()) {
pegRevision1 = SVNRevision.HEAD;
} else {
source2 = source1;
if (pegRevision1 == null || pegRevision1 == SVNRevision.UNDEFINED) {
pegRevision1 = source1.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING;
}
if (targets.size() == 2) {
target = new SVNPath((String) targets.get(1));
if (target.isURL()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Cannot specifify a revision range with two URLs");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
}
} else {
if (targets.size() < 2) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT);
} else if (targets.size() > 3) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Too many arguments given"), SVNLogType.CLIENT);
}
firstRangeStart = pegRevision1;
firstRangeEnd = pegRevision2;
if (((firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) && !source1.isURL()) ||
((pegRevision2 == null || pegRevision2 == SVNRevision.UNDEFINED) && !source2.isURL())) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION,
"A working copy merge source needs an explicit revision"), SVNLogType.CLIENT);
}
if (firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) {
firstRangeStart = SVNRevision.HEAD;
}
if (firstRangeEnd == null || firstRangeEnd == SVNRevision.UNDEFINED) {
firstRangeEnd = SVNRevision.HEAD;
}
if (targets.size() >= 3) {
target = new SVNPath((String) targets.get(2));
}
}
if (source1 != null && source2 != null && target == null) {
if (source1.isURL()) {
String name1 = SVNPathUtil.tail(source1.getTarget());
String name2 = SVNPathUtil.tail(source2.getTarget());
if (name1.equals(name2)) {
String decodedPath = SVNEncodingUtil.uriDecode(name1);
SVNPath decodedPathTarget = new SVNPath(decodedPath);
if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) {
target = decodedPathTarget;
}
}
} else if (source1.equals(source2)) {
String decodedPath = SVNEncodingUtil.uriDecode(source1.getTarget());
SVNPath decodedPathTarget = new SVNPath(decodedPath);
if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) {
target = decodedPathTarget;
}
}
}
if (target == null) {
target = new SVNPath("");
}
SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient();
if (!getSVNEnvironment().isQuiet()) {
client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment()));
}
client.setAllowMixedRevisions(getSVNEnvironment().isAllowMixedRevisions());
try {
client.setMergeOptions(getSVNEnvironment().getDiffOptions());
if (!twoSourcesSpecified) {
if (firstRangeStart == SVNRevision.UNDEFINED && firstRangeEnd == SVNRevision.UNDEFINED) {
SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), pegRevision1);
rangesToMerge = new LinkedList();
rangesToMerge.add(range);
}
if (source1 == null) {
source1 = target;
}
if (getSVNEnvironment().isReIntegrate()) {
if (getSVNEnvironment().getDepth() != SVNDepth.UNKNOWN) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS,
"--depth cannot be used with --reintegrate");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (getSVNEnvironment().isForce()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS,
"--force cannot be used with --reintegrate");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (source1.isURL()) {
client.doMergeReIntegrate(source1.getURL(), pegRevision1, target.getFile(),
getSVNEnvironment().isDryRun());
} else {
client.doMergeReIntegrate(source1.getFile(), pegRevision1, target.getFile(),
getSVNEnvironment().isDryRun());
}
} else {
if (source1.isURL()) {
client.doMerge(source1.getURL(), pegRevision1, rangesToMerge, target.getFile(),
getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(),
getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(),
getSVNEnvironment().isRecordOnly());
} else {
client.doMerge(source1.getFile(), pegRevision1, rangesToMerge, target.getFile(),
getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(),
getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(),
getSVNEnvironment().isRecordOnly());
}
}
} else {
if (source1.isURL() && source2.isURL()) {
client.doMerge(source1.getURL(), firstRangeStart, source2.getURL(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else if (source1.isURL() && source2.isFile()) {
client.doMerge(source1.getURL(), firstRangeStart, source2.getFile(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else if (source1.isFile() && source2.isURL()) {
client.doMerge(source1.getFile(), firstRangeStart, source2.getURL(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else {
client.doMerge(source1.getFile(), firstRangeStart, source2.getFile(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
}
}
} catch (SVNException e) {
SVNErrorMessage err = e.getErrorMessage();
if (err != null && !getSVNEnvironment().isReIntegrate()) {
SVNErrorCode code = err.getErrorCode();
if (code == SVNErrorCode.UNVERSIONED_RESOURCE || code == SVNErrorCode.CLIENT_MODIFIED) {
err = err.wrap("Use --force to override this restriction");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
throw e;
}
}
| public void run() throws SVNException {
List targets = getSVNEnvironment().combineTargets(new ArrayList(), true);
SVNPath source1 = null;
SVNPath source2 = null;
SVNPath target = null;
SVNRevision pegRevision1 = null;
SVNRevision pegRevision2 = null;
if (targets.size() >= 1) {
source1 = new SVNPath((String) targets.get(0), true);
pegRevision1 = source1.getPegRevision();
if (targets.size() >= 2) {
source2 = new SVNPath((String) targets.get(1), true);
pegRevision2 = source2.getPegRevision();
}
}
boolean twoSourcesSpecified = true;
if (targets.size() <= 1) {
twoSourcesSpecified = false;
} else if (targets.size() == 2) {
if (source1.isURL() && !source2.isURL()) {
twoSourcesSpecified = false;
}
}
List rangesToMerge = getSVNEnvironment().getRevisionRanges();
SVNRevision firstRangeStart = SVNRevision.UNDEFINED;
SVNRevision firstRangeEnd = SVNRevision.UNDEFINED;
if (!rangesToMerge.isEmpty()) {
SVNRevisionRange range = (SVNRevisionRange) rangesToMerge.get(0);
firstRangeStart = range.getStartRevision();
firstRangeEnd = range.getEndRevision();
}
if (firstRangeStart != SVNRevision.UNDEFINED) {
if (firstRangeEnd == SVNRevision.UNDEFINED) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS,
"Second revision required");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
twoSourcesSpecified = false;
}
if (!twoSourcesSpecified) {
if (targets.size() > 2) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Too many arguments given"), SVNLogType.CLIENT);
}
if (targets.isEmpty()) {
pegRevision1 = SVNRevision.HEAD;
} else {
source2 = source1;
if (pegRevision1 == null || pegRevision1 == SVNRevision.UNDEFINED) {
pegRevision1 = source1.isURL() ? SVNRevision.HEAD : SVNRevision.WORKING;
}
if (targets.size() == 2) {
target = new SVNPath((String) targets.get(1));
if (target.isURL()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Cannot specifify a revision range with two URLs");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
}
} else {
if (targets.size() < 2) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS), SVNLogType.CLIENT);
} else if (targets.size() > 3) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Too many arguments given"), SVNLogType.CLIENT);
}
firstRangeStart = pegRevision1;
firstRangeEnd = pegRevision2;
if (((firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) && !source1.isURL()) ||
((pegRevision2 == null || pegRevision2 == SVNRevision.UNDEFINED) && !source2.isURL())) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION,
"A working copy merge source needs an explicit revision"), SVNLogType.CLIENT);
}
if (firstRangeStart == null || firstRangeStart == SVNRevision.UNDEFINED) {
firstRangeStart = SVNRevision.HEAD;
}
if (firstRangeEnd == null || firstRangeEnd == SVNRevision.UNDEFINED) {
firstRangeEnd = SVNRevision.HEAD;
}
if (targets.size() >= 3) {
target = new SVNPath((String) targets.get(2));
}
}
if (source1 != null && source2 != null && target == null) {
if (source1.isURL()) {
String name1 = SVNPathUtil.tail(source1.getTarget());
String name2 = SVNPathUtil.tail(source2.getTarget());
if (name1.equals(name2)) {
String decodedPath = SVNEncodingUtil.uriDecode(name1);
SVNPath decodedPathTarget = new SVNPath(decodedPath);
if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) {
target = decodedPathTarget;
}
}
} else if (source1.equals(source2)) {
String decodedPath = SVNEncodingUtil.uriDecode(source1.getTarget());
SVNPath decodedPathTarget = new SVNPath(decodedPath);
if (SVNFileType.getType(decodedPathTarget.getFile()) == SVNFileType.FILE) {
target = decodedPathTarget;
}
}
}
if (target == null) {
target = new SVNPath("");
}
SVNDiffClient client = getSVNEnvironment().getClientManager().getDiffClient();
if (!getSVNEnvironment().isQuiet()) {
client.setEventHandler(new SVNNotifyPrinter(getSVNEnvironment()));
}
client.setAllowMixedRevisionsWCForMerge(getSVNEnvironment().isAllowMixedRevisions());
try {
client.setMergeOptions(getSVNEnvironment().getDiffOptions());
if (!twoSourcesSpecified) {
if (firstRangeStart == SVNRevision.UNDEFINED && firstRangeEnd == SVNRevision.UNDEFINED) {
SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), pegRevision1);
rangesToMerge = new LinkedList();
rangesToMerge.add(range);
}
if (source1 == null) {
source1 = target;
}
if (getSVNEnvironment().isReIntegrate()) {
if (getSVNEnvironment().getDepth() != SVNDepth.UNKNOWN) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS,
"--depth cannot be used with --reintegrate");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (getSVNEnvironment().isForce()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_MUTUALLY_EXCLUSIVE_ARGS,
"--force cannot be used with --reintegrate");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (source1.isURL()) {
client.doMergeReIntegrate(source1.getURL(), pegRevision1, target.getFile(),
getSVNEnvironment().isDryRun());
} else {
client.doMergeReIntegrate(source1.getFile(), pegRevision1, target.getFile(),
getSVNEnvironment().isDryRun());
}
} else {
if (source1.isURL()) {
client.doMerge(source1.getURL(), pegRevision1, rangesToMerge, target.getFile(),
getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(),
getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(),
getSVNEnvironment().isRecordOnly());
} else {
client.doMerge(source1.getFile(), pegRevision1, rangesToMerge, target.getFile(),
getSVNEnvironment().getDepth(), !getSVNEnvironment().isIgnoreAncestry(),
getSVNEnvironment().isForce(), getSVNEnvironment().isDryRun(),
getSVNEnvironment().isRecordOnly());
}
}
} else {
if (source1.isURL() && source2.isURL()) {
client.doMerge(source1.getURL(), firstRangeStart, source2.getURL(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else if (source1.isURL() && source2.isFile()) {
client.doMerge(source1.getURL(), firstRangeStart, source2.getFile(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else if (source1.isFile() && source2.isURL()) {
client.doMerge(source1.getFile(), firstRangeStart, source2.getURL(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
} else {
client.doMerge(source1.getFile(), firstRangeStart, source2.getFile(), firstRangeEnd,
target.getFile(), getSVNEnvironment().getDepth(),
!getSVNEnvironment().isIgnoreAncestry(), getSVNEnvironment().isForce(),
getSVNEnvironment().isDryRun(), getSVNEnvironment().isRecordOnly());
}
}
} catch (SVNException e) {
SVNErrorMessage err = e.getErrorMessage();
if (err != null && !getSVNEnvironment().isReIntegrate()) {
SVNErrorCode code = err.getErrorCode();
if (code == SVNErrorCode.UNVERSIONED_RESOURCE || code == SVNErrorCode.CLIENT_MODIFIED) {
err = err.wrap("Use --force to override this restriction");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
throw e;
}
}
|
diff --git a/sonar-batch-bootstrapper/src/main/java/org/sonar/batch/bootstrapper/BatchDownloader.java b/sonar-batch-bootstrapper/src/main/java/org/sonar/batch/bootstrapper/BatchDownloader.java
index 27b28df1cf..250559a075 100644
--- a/sonar-batch-bootstrapper/src/main/java/org/sonar/batch/bootstrapper/BatchDownloader.java
+++ b/sonar-batch-bootstrapper/src/main/java/org/sonar/batch/bootstrapper/BatchDownloader.java
@@ -1,138 +1,138 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar 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 3 of the License, or (at your option) any later version.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.batch.bootstrapper;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class BatchDownloader {
private static final String VERSION_PATH = "/api/server/version";
private static final String BATCH_PATH = "/batch/";
public static final int CONNECT_TIMEOUT_MILLISECONDS = 30000;
public static final int READ_TIMEOUT_MILLISECONDS = 60000;
private String serverUrl;
private String serverVersion;
public BatchDownloader(String serverUrl) {
if (serverUrl.endsWith("/")) {
this.serverUrl = serverUrl.substring(0, serverUrl.length() - 1);
} else {
this.serverUrl = serverUrl;
}
}
/**
* @return server url
*/
public String getServerUrl() {
return serverUrl;
}
/**
* @return server version
*/
public String getServerVersion() {
if (serverVersion == null) {
try {
serverVersion = remoteContent(VERSION_PATH);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return serverVersion;
}
/**
* To use this method version of Sonar should be at least 2.6.
*
* @return list of downloaded files
*/
public List<File> downloadBatchFiles(File toDir) {
try {
List<File> files = new ArrayList<File>();
String libs = remoteContent(BATCH_PATH);
for (String lib : libs.split("\n")) {
- if ("".equals(lib)) {
+ if (!"".equals(lib)) {
File file = new File(toDir, lib);
remoteContentToFile(BATCH_PATH + lib, file);
files.add(file);
}
}
return files;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void remoteContentToFile(String path, File toFile) {
InputStream input = null;
FileOutputStream output = null;
String fullUrl = serverUrl + path;
try {
HttpURLConnection connection = newHttpConnection(new URL(fullUrl));
output = new FileOutputStream(toFile, false);
input = connection.getInputStream();
BootstrapperIOUtils.copyLarge(input, output);
} catch (Exception e) {
BootstrapperIOUtils.closeQuietly(output);
BootstrapperIOUtils.deleteFileQuietly(toFile);
throw new RuntimeException("Fail to download the file: " + fullUrl, e);
} finally {
BootstrapperIOUtils.closeQuietly(input);
BootstrapperIOUtils.closeQuietly(output);
}
}
String remoteContent(String path) throws IOException {
String fullUrl = serverUrl + path;
HttpURLConnection conn = newHttpConnection(new URL(fullUrl));
Reader reader = new InputStreamReader((InputStream) conn.getContent());
try {
int statusCode = conn.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
throw new IOException("Status returned by url : '" + fullUrl + "' is invalid : " + statusCode);
}
return BootstrapperIOUtils.toString(reader);
} finally {
BootstrapperIOUtils.closeQuietly(reader);
conn.disconnect();
}
}
static HttpURLConnection newHttpConnection(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT_MILLISECONDS);
connection.setReadTimeout(READ_TIMEOUT_MILLISECONDS);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("GET");
// TODO connection.setRequestProperty("User-Agent", userAgent);
return connection;
}
}
| true | true | public List<File> downloadBatchFiles(File toDir) {
try {
List<File> files = new ArrayList<File>();
String libs = remoteContent(BATCH_PATH);
for (String lib : libs.split("\n")) {
if ("".equals(lib)) {
File file = new File(toDir, lib);
remoteContentToFile(BATCH_PATH + lib, file);
files.add(file);
}
}
return files;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
| public List<File> downloadBatchFiles(File toDir) {
try {
List<File> files = new ArrayList<File>();
String libs = remoteContent(BATCH_PATH);
for (String lib : libs.split("\n")) {
if (!"".equals(lib)) {
File file = new File(toDir, lib);
remoteContentToFile(BATCH_PATH + lib, file);
files.add(file);
}
}
return files;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
diff --git a/code/src/pt/isel/adeetc/meic/pdm/common/GenericEventArgs.java b/code/src/pt/isel/adeetc/meic/pdm/common/GenericEventArgs.java
index 9ad91de..6527519 100644
--- a/code/src/pt/isel/adeetc/meic/pdm/common/GenericEventArgs.java
+++ b/code/src/pt/isel/adeetc/meic/pdm/common/GenericEventArgs.java
@@ -1,33 +1,33 @@
package pt.isel.adeetc.meic.pdm.common;
public class GenericEventArgs<T> implements IEventHandlerArgs<T>
{
private final T _data;
private final Exception _error;
public GenericEventArgs(T result, Exception error)
{
this._data = result;
_error = error;
}
public Exception getError()
{
return _error;
}
public T getData() throws Exception
{
- if(_error == null)
+ if(_error != null)
throw _error;
return _data;
}
public boolean errorOccurred()
{
return _error != null;
}
}
| true | true | public T getData() throws Exception
{
if(_error == null)
throw _error;
return _data;
}
| public T getData() throws Exception
{
if(_error != null)
throw _error;
return _data;
}
|
diff --git a/src/org/rsbot/security/RestrictedSecurityManager.java b/src/org/rsbot/security/RestrictedSecurityManager.java
index 85d9161d..2389ce32 100644
--- a/src/org/rsbot/security/RestrictedSecurityManager.java
+++ b/src/org/rsbot/security/RestrictedSecurityManager.java
@@ -1,233 +1,233 @@
package org.rsbot.security;
import org.rsbot.Application;
import org.rsbot.gui.BotGUI;
import org.rsbot.script.Script;
import org.rsbot.service.ScriptDeliveryNetwork;
import java.io.FileDescriptor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Permission;
import java.util.ArrayList;
/**
* @author Paris
*/
public class RestrictedSecurityManager extends SecurityManager {
private String getCallingClass() {
final String prefix = Application.class.getPackage().getName() + ".";
for (StackTraceElement s : Thread.currentThread().getStackTrace()) {
final String name = s.getClassName();
if (name.startsWith(prefix) && !name.equals(RestrictedSecurityManager.class.getName())) {
return name;
}
}
return "";
}
private boolean isCallerScript() {
final String name = getCallingClass();
if (name.isEmpty()) {
return false;
}
return name.startsWith(Script.class.getName());
}
public void checkAccept(String host, int port) {
throw new SecurityException();
}
public void checkConnect(String host, int port) {
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: prefix with '.' boundary because .example.com won't match on hacked-example.com
- whitelist.add(".imageshack.us");
- whitelist.add(".tinypic.com");
- whitelist.add(".imgur.com");
- whitelist.add(".powerbot.org");
- whitelist.add(".runescape.com");
+ whitelist.add("imageshack.us");
+ whitelist.add("tinypic.com");
+ whitelist.add("imgur.com");
+ whitelist.add("powerbot.org");
+ whitelist.add("runescape.com");
- whitelist.add(".shadowscripting.org"); // iDungeon
- whitelist.add(".shadowscripting.wordpress.com"); // iDungeon
+ whitelist.add("shadowscripting.org"); // iDungeon
+ whitelist.add("shadowscripting.wordpress.com"); // iDungeon
if (isIpAddress(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostName();
} catch (UnknownHostException e) {
throw new SecurityException();
}
}
boolean allowed = false;
for (String check : whitelist) {
- if (host.endsWith(check)) {
+ if (host.equalsIgnoreCase(check)) {
allowed = true;
break;
}
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
private boolean isIpAddress(String check) {
final int l = check.length();
if (l < 7 || l > 15) {
return false;
}
String[] parts = check.split("\\.", 4);
if (parts.length != 4) {
return false;
}
for (int i = 0; i < 4; i++) {
int n = Integer.parseInt(parts[i]);
if (n < 0 || n > 255) {
return false;
}
}
return true;
}
public void checkConnect(String host, int port, Object context) {
checkConnect(host, port);
}
public void checkCreateClassLoader() {
super.checkCreateClassLoader();
}
public void checkDelete(String file) {
if (isCallerScript()) {
throw new SecurityException();
} else {
super.checkDelete(file);
}
}
public void checkExec(String cmd) {
final String calling = getCallingClass();
if (calling.equals(ScriptDeliveryNetwork.class.getName()) || calling.equals(BotGUI.class.getName())) {
super.checkExec(cmd);
} else {
throw new SecurityException();
}
}
public void checkExit(int status) {
final String calling = getCallingClass();
if (calling.equals(BotGUI.class.getName())) {
super.checkExit(status);
} else {
throw new SecurityException();
}
}
public void checkLink(String lib) {
super.checkLink(lib);
}
public void checkListen(int port) {
throw new SecurityException();
}
public void checkMemberAccess(Class<?> clazz, int which) {
super.checkMemberAccess(clazz, which);
}
public void checkMulticast(InetAddress maddr) {
throw new SecurityException();
}
public void checkMulticast(InetAddress maddr, byte ttl) {
throw new SecurityException();
}
public void checkPackageAccess(String pkg) {
super.checkPackageAccess(pkg);
}
public void checkPackageDefinition(String pkg) {
super.checkPackageDefinition(pkg);
}
public void checkPermission(Permission perm) {
//super.checkPermission(perm);
}
public void checkPermission(Permission perm, Object context) {
//super.checkPermission(perm, context);
}
public void checkPrintJobAccess() {
throw new SecurityException();
}
public void checkPropertiesAccess() {
super.checkPropertiesAccess();
}
public void checkPropertyAccess(String key) {
super.checkPropertyAccess(key);
}
public void checkRead(FileDescriptor fd) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkRead(fd);
}
public void checkRead(String file) {
super.checkRead(file);
}
public void checkRead(String file, Object context) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkRead(file, context);
}
public void checkSecurityAccess(String target) {
super.checkSecurityAccess(target);
}
public void checkSetFactory() {
super.checkSetFactory();
}
public void checkSystemClipboardAccess() {
throw new SecurityException();
}
public boolean checkTopLevelWindow(Object window) {
return super.checkTopLevelWindow(window);
}
public void checkWrite(FileDescriptor fd) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkWrite(fd);
}
public void checkWrite(String file) {
if (isCallerScript()) {
throw new SecurityException();
}
super.checkWrite(file);
}
}
| false | true | public void checkConnect(String host, int port) {
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: prefix with '.' boundary because .example.com won't match on hacked-example.com
whitelist.add(".imageshack.us");
whitelist.add(".tinypic.com");
whitelist.add(".imgur.com");
whitelist.add(".powerbot.org");
whitelist.add(".runescape.com");
whitelist.add(".shadowscripting.org"); // iDungeon
whitelist.add(".shadowscripting.wordpress.com"); // iDungeon
if (isIpAddress(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostName();
} catch (UnknownHostException e) {
throw new SecurityException();
}
}
boolean allowed = false;
for (String check : whitelist) {
if (host.endsWith(check)) {
allowed = true;
break;
}
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
| public void checkConnect(String host, int port) {
// ports other than HTTP (80), HTTPS (443) and unknown (-1) are automatically denied
if (!(port == -1 || port == 80 || port == 443)) {
throw new SecurityException();
}
if (isCallerScript()) {
ArrayList<String> whitelist = new ArrayList<String>();
// NOTE: prefix with '.' boundary because .example.com won't match on hacked-example.com
whitelist.add("imageshack.us");
whitelist.add("tinypic.com");
whitelist.add("imgur.com");
whitelist.add("powerbot.org");
whitelist.add("runescape.com");
whitelist.add("shadowscripting.org"); // iDungeon
whitelist.add("shadowscripting.wordpress.com"); // iDungeon
if (isIpAddress(host)) {
try {
InetAddress addr = InetAddress.getByName(host);
host = addr.getHostName();
} catch (UnknownHostException e) {
throw new SecurityException();
}
}
boolean allowed = false;
for (String check : whitelist) {
if (host.equalsIgnoreCase(check)) {
allowed = true;
break;
}
}
if (!allowed) {
throw new SecurityException();
}
}
super.checkConnect(host, port);
}
|
diff --git a/core/cc.warlock.core/src/main/cc/warlock/client/stormfront/internal/StormFrontClient.java b/core/cc.warlock.core/src/main/cc/warlock/client/stormfront/internal/StormFrontClient.java
index f4710a2e..ca6be1f8 100644
--- a/core/cc.warlock.core/src/main/cc/warlock/client/stormfront/internal/StormFrontClient.java
+++ b/core/cc.warlock.core/src/main/cc/warlock/client/stormfront/internal/StormFrontClient.java
@@ -1,280 +1,280 @@
/*
* Created on Mar 26, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package cc.warlock.client.stormfront.internal;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cc.warlock.client.ICompass;
import cc.warlock.client.IProperty;
import cc.warlock.client.IWarlockStyle;
import cc.warlock.client.WarlockClientRegistry;
import cc.warlock.client.internal.ClientProperty;
import cc.warlock.client.internal.Compass;
import cc.warlock.client.internal.WarlockClient;
import cc.warlock.client.internal.WarlockStyle;
import cc.warlock.client.stormfront.IStormFrontClient;
import cc.warlock.configuration.WarlockConfiguration;
import cc.warlock.configuration.server.ServerSettings;
import cc.warlock.network.StormFrontConnection;
import cc.warlock.script.IScript;
import cc.warlock.script.IScriptCommands;
import cc.warlock.script.IScriptListener;
import cc.warlock.script.internal.ScriptCommands;
import cc.warlock.script.internal.ScriptRunner;
import cc.warlock.stormfront.IStormFrontProtocolHandler;
import com.martiansoftware.jsap.CommandLineTokenizer;
/**
* @author Marshall
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class StormFrontClient extends WarlockClient implements IStormFrontClient, IScriptListener {
protected ICompass compass;
protected int lastPrompt;
protected ClientProperty<Integer> roundtime, health, mana, fatigue, spirit;
protected ClientProperty<String> leftHand, rightHand, currentSpell;
protected boolean isPrompting = false;
protected StringBuffer buffer = new StringBuffer();
protected IStormFrontProtocolHandler handler;
protected boolean isBold;
protected ClientProperty<String> playerId, characterName;
protected IWarlockStyle currentStyle = WarlockStyle.EMPTY_STYLE;
protected ServerSettings serverSettings;
protected RoundtimeRunnable rtRunnable;
protected ScriptCommands scriptCommands;
protected ArrayList<IScript> runningScripts;
protected ArrayList<IScriptListener> scriptListeners;
public StormFrontClient() {
compass = new Compass(this);
leftHand = new ClientProperty<String>(this, "leftHand", null);
rightHand = new ClientProperty<String>(this, "rightHand", null);
currentSpell = new ClientProperty<String>(this, "currentSpell", null);
roundtime = new ClientProperty<Integer>(this, "roundtime", 0);
health = new ClientProperty<Integer>(this, "health", 0);
mana = new ClientProperty<Integer>(this, "mana", 0);
fatigue = new ClientProperty<Integer>(this, "fatigue", 0);
spirit = new ClientProperty<Integer>(this, "spirit", 0);
playerId = new ClientProperty<String>(this, "playerId", null);
characterName = new ClientProperty<String>(this, "characterName", null);
serverSettings = new ServerSettings(this);
rtRunnable = new RoundtimeRunnable();
scriptCommands = new ScriptCommands(this);
runningScripts = new ArrayList<IScript>();
scriptListeners = new ArrayList<IScriptListener>();
WarlockClientRegistry.activateClient(this);
}
@Override
public void send(String command) {
if (command.startsWith(".")){
runScriptCommand(command);
} else {
super.send(command);
}
}
protected void runScriptCommand(String command) {
command = command.substring(1);
int firstSpace = command.indexOf(" ");
String scriptName = command.substring(0, (firstSpace < 0 ? command.length() : firstSpace));
String[] arguments = new String[0];
if (firstSpace > 0)
{
String args = command.substring(firstSpace+1);
arguments = CommandLineTokenizer.tokenize(args);
}
File scriptDirectory = WarlockConfiguration.getConfigurationDirectory("scripts", true);
IScript script = ScriptRunner.runScriptFromFile(scriptCommands, scriptDirectory, scriptName, arguments);
if (script != null)
{
script.addScriptListener(this);
for (IScriptListener listener : scriptListeners) listener.scriptStarted(script);
runningScripts.add(script);
}
- getCommandHistory().addCommand(command);
+ getCommandHistory().addCommand("." + command);
}
public void scriptPaused(IScript script) {
for (IScriptListener listener : scriptListeners) listener.scriptPaused(script);
}
public void scriptResumed(IScript script) {
for (IScriptListener listener : scriptListeners) listener.scriptResumed(script);
}
public void scriptStarted(IScript script) {
for (IScriptListener listener : scriptListeners) listener.scriptStarted(script);
}
public void scriptStopped(IScript script, boolean userStopped) {
runningScripts.remove(script);
for (IScriptListener listener : scriptListeners) listener.scriptStopped(script, userStopped);
}
public IProperty<Integer> getRoundtime() {
return roundtime;
}
private class RoundtimeRunnable implements Runnable
{
public int roundtime;
public synchronized void run ()
{
for (int i = 0; i < roundtime; i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateRoundtime(StormFrontClient.this.roundtime.get() - 1);
}
}
}
public void startRoundtime (int seconds)
{
roundtime.activate();
roundtime.set(seconds);
rtRunnable.roundtime = seconds;
new Thread(rtRunnable).start();
}
public void updateRoundtime (int currentRoundtime)
{
roundtime.set(currentRoundtime);
}
public IProperty<Integer> getHealth() {
return health;
}
public IProperty<Integer> getMana() {
return mana;
}
public IProperty<Integer> getFatigue() {
return fatigue;
}
public IProperty<Integer> getSpirit() {
return spirit;
}
public ICompass getCompass() {
return compass;
}
public void connect(String server, int port, String key) throws IOException {
try {
connection = new StormFrontConnection(this, key);
connection.connect(server, port);
WarlockClientRegistry.clientConnected(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void streamCleared() {
// TODO Auto-generated method stub
}
public void setPrompting() {
isPrompting = true;
}
public boolean isPrompting() {
return isPrompting;
}
public void setBold(boolean bold) {
isBold = bold;
}
public boolean isBold() {
return isBold;
}
public IWarlockStyle getCurrentStyle() {
return currentStyle;
}
public void setCurrentStyle(IWarlockStyle currentStyle) {
this.currentStyle = currentStyle;
}
public ClientProperty<String> getPlayerId() {
return playerId;
}
public ServerSettings getServerSettings() {
return serverSettings;
}
public IScriptCommands getScriptCommands() {
return scriptCommands;
}
public IProperty<String> getCharacterName() {
return characterName;
}
public IProperty<String> getLeftHand() {
return leftHand;
}
public IProperty<String> getRightHand() {
return rightHand;
}
public IProperty<String> getCurrentSpell() {
return currentSpell;
}
public List<IScript> getRunningScripts() {
return runningScripts;
}
public void addScriptListener(IScriptListener listener)
{
scriptListeners.add(listener);
}
public void removeScriptListener (IScriptListener listener)
{
if (scriptListeners.contains(listener))
scriptListeners.remove(listener);
}
@Override
protected void finalize() throws Throwable {
WarlockClientRegistry.removeClient(this);
super.finalize();
}
}
| true | true | protected void runScriptCommand(String command) {
command = command.substring(1);
int firstSpace = command.indexOf(" ");
String scriptName = command.substring(0, (firstSpace < 0 ? command.length() : firstSpace));
String[] arguments = new String[0];
if (firstSpace > 0)
{
String args = command.substring(firstSpace+1);
arguments = CommandLineTokenizer.tokenize(args);
}
File scriptDirectory = WarlockConfiguration.getConfigurationDirectory("scripts", true);
IScript script = ScriptRunner.runScriptFromFile(scriptCommands, scriptDirectory, scriptName, arguments);
if (script != null)
{
script.addScriptListener(this);
for (IScriptListener listener : scriptListeners) listener.scriptStarted(script);
runningScripts.add(script);
}
getCommandHistory().addCommand(command);
}
| protected void runScriptCommand(String command) {
command = command.substring(1);
int firstSpace = command.indexOf(" ");
String scriptName = command.substring(0, (firstSpace < 0 ? command.length() : firstSpace));
String[] arguments = new String[0];
if (firstSpace > 0)
{
String args = command.substring(firstSpace+1);
arguments = CommandLineTokenizer.tokenize(args);
}
File scriptDirectory = WarlockConfiguration.getConfigurationDirectory("scripts", true);
IScript script = ScriptRunner.runScriptFromFile(scriptCommands, scriptDirectory, scriptName, arguments);
if (script != null)
{
script.addScriptListener(this);
for (IScriptListener listener : scriptListeners) listener.scriptStarted(script);
runningScripts.add(script);
}
getCommandHistory().addCommand("." + command);
}
|
diff --git a/plugins/net.refractions.udig.catalog.worldimage/src/net/refractions/udig/catalog/internal/worldimage/WorldImageServiceExtension.java b/plugins/net.refractions.udig.catalog.worldimage/src/net/refractions/udig/catalog/internal/worldimage/WorldImageServiceExtension.java
index d673b3471..69074b524 100644
--- a/plugins/net.refractions.udig.catalog.worldimage/src/net/refractions/udig/catalog/internal/worldimage/WorldImageServiceExtension.java
+++ b/plugins/net.refractions.udig.catalog.worldimage/src/net/refractions/udig/catalog/internal/worldimage/WorldImageServiceExtension.java
@@ -1,162 +1,162 @@
/* uDig - User Friendly Desktop Internet GIS client
* http://udig.refractions.net
* (C) 2004-2012, Refractions Research Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Refractions BSD
* License v1.0 (http://udig.refractions.net/files/bsd3-v10.html).
*/
package net.refractions.udig.catalog.internal.worldimage;
import java.io.File;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import net.refractions.udig.catalog.IService;
import net.refractions.udig.catalog.ServiceExtension2;
import net.refractions.udig.catalog.URLUtils;
import net.refractions.udig.catalog.worldimage.internal.Messages;
import org.geotools.gce.image.WorldImageFormat;
import org.geotools.gce.image.WorldImageFormatFactory;
/**
* Provides the interface to the catalog service extension point.
* <p>
* This class is responsible for ensuring that only those services that the
* WorldImage plugin is capable of processing are created.
* </p>
* @author mleslie
* @since 0.6.0
*/
public class WorldImageServiceExtension implements ServiceExtension2 {
/** <code>URL_PARAM</code> field */
public final static String URL_PARAM = "URL"; //$NON-NLS-1$
public static final String TYPE = "world+image"; //$NON-NLS-1$
private static WorldImageFormatFactory factory;
/**
* Construct <code>WorldImageServiceExtension</code>.
*
*/
public WorldImageServiceExtension() {
super();
}
public IService createService(URL id, Map<String, Serializable> params ) {
URL id2 = getID(params);
if (!canProcess(id2)) {
return null;
}
WorldImageServiceImpl service =
new WorldImageServiceImpl(id2, getFactory());
return service;
}
private URL getID( Map<String, Serializable> params ) {
if (params.containsKey(URL_PARAM)) {
Object param = params.get(URL_PARAM);
if (param instanceof String) {
try {
return new URL((String) param);
} catch (MalformedURLException ex) {
return null;
}
} else if (param instanceof URL) {
return (URL) param;
} else {
return null;
}
} else {
return null;
}
}
/**
* Finds or creates a WorldImageFormatFactory.
*
* @return Default instance of WorldImageFormatFactory
*/
public static WorldImageFormatFactory getFactory() {
if(factory == null) {
factory = new WorldImageFormatFactory();
}
return factory;
}
private boolean canProcess( URL id ) {
return reasonForFailure(id)==null;
}
public Map<String, Serializable> createParams( URL url ) {
if( !canProcess(url))
return null;
if (url != null) {
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put(URL_PARAM, url);
return params;
}
return null;
}
public String reasonForFailure( Map<String, Serializable> params ) {
return reasonForFailure(getID(params));
}
public String reasonForFailure( URL id ) {
if(id == null) {
return Messages.WorldImageServiceExtension_noID;
}
File file = URLUtils.urlToFile(id);
if(file == null) {
return "Not a file";
}
String path = file.getAbsolutePath();
String fileExt = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
if( fileExt.compareToIgnoreCase("BMP") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("PNG") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("GIF") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("JPG") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("JPEG") != 0 && //&& //$NON-NLS-1$
fileExt.compareToIgnoreCase("TIF") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("TIFF") != 0) { //$NON-NLS-1$
return Messages.WorldImageServiceExtension_badFileExtension+fileExt;
}
Collection<String> endings = new HashSet<String>(WorldImageFormat.getWorldExtension(fileExt));
endings.add(".wld"); //$NON-NLS-1$
endings.add(fileExt+"w"); //$NON-NLS-1$
File[] found = URLUtils.findRelatedFiles(file, endings.toArray(new String[0]) );
if (found.length==0) {
return Messages.WorldImageServiceExtension_needsFile;
}
- if( !id.getProtocol().equals(Messages.WorldImageServiceExtension_file) ){
+ if( !id.getProtocol().equals("file") ){
return Messages.WorldImageServiceExtension_mustBeFIle;
}
try {
@SuppressWarnings("unused")
File fileTest = URLUtils.urlToFile(id);
} catch(IllegalArgumentException ex) {
return Messages.WorldImageServiceExtension_IllegalFilePart1+id.getFile()+Messages.WorldImageServiceExtension_IllegalFilePart2;
}
return null;
}
}
| true | true | public String reasonForFailure( URL id ) {
if(id == null) {
return Messages.WorldImageServiceExtension_noID;
}
File file = URLUtils.urlToFile(id);
if(file == null) {
return "Not a file";
}
String path = file.getAbsolutePath();
String fileExt = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
if( fileExt.compareToIgnoreCase("BMP") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("PNG") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("GIF") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("JPG") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("JPEG") != 0 && //&& //$NON-NLS-1$
fileExt.compareToIgnoreCase("TIF") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("TIFF") != 0) { //$NON-NLS-1$
return Messages.WorldImageServiceExtension_badFileExtension+fileExt;
}
Collection<String> endings = new HashSet<String>(WorldImageFormat.getWorldExtension(fileExt));
endings.add(".wld"); //$NON-NLS-1$
endings.add(fileExt+"w"); //$NON-NLS-1$
File[] found = URLUtils.findRelatedFiles(file, endings.toArray(new String[0]) );
if (found.length==0) {
return Messages.WorldImageServiceExtension_needsFile;
}
if( !id.getProtocol().equals(Messages.WorldImageServiceExtension_file) ){
return Messages.WorldImageServiceExtension_mustBeFIle;
}
try {
@SuppressWarnings("unused")
File fileTest = URLUtils.urlToFile(id);
} catch(IllegalArgumentException ex) {
return Messages.WorldImageServiceExtension_IllegalFilePart1+id.getFile()+Messages.WorldImageServiceExtension_IllegalFilePart2;
}
return null;
}
| public String reasonForFailure( URL id ) {
if(id == null) {
return Messages.WorldImageServiceExtension_noID;
}
File file = URLUtils.urlToFile(id);
if(file == null) {
return "Not a file";
}
String path = file.getAbsolutePath();
String fileExt = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
if( fileExt.compareToIgnoreCase("BMP") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("PNG") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("GIF") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("JPG") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("JPEG") != 0 && //&& //$NON-NLS-1$
fileExt.compareToIgnoreCase("TIF") != 0 && //$NON-NLS-1$
fileExt.compareToIgnoreCase("TIFF") != 0) { //$NON-NLS-1$
return Messages.WorldImageServiceExtension_badFileExtension+fileExt;
}
Collection<String> endings = new HashSet<String>(WorldImageFormat.getWorldExtension(fileExt));
endings.add(".wld"); //$NON-NLS-1$
endings.add(fileExt+"w"); //$NON-NLS-1$
File[] found = URLUtils.findRelatedFiles(file, endings.toArray(new String[0]) );
if (found.length==0) {
return Messages.WorldImageServiceExtension_needsFile;
}
if( !id.getProtocol().equals("file") ){
return Messages.WorldImageServiceExtension_mustBeFIle;
}
try {
@SuppressWarnings("unused")
File fileTest = URLUtils.urlToFile(id);
} catch(IllegalArgumentException ex) {
return Messages.WorldImageServiceExtension_IllegalFilePart1+id.getFile()+Messages.WorldImageServiceExtension_IllegalFilePart2;
}
return null;
}
|
diff --git a/src/rs/pedjaapps/KernelTuner/ui/SDScannerConfigActivity.java b/src/rs/pedjaapps/KernelTuner/ui/SDScannerConfigActivity.java
index 6dd27ce..5b4daa2 100644
--- a/src/rs/pedjaapps/KernelTuner/ui/SDScannerConfigActivity.java
+++ b/src/rs/pedjaapps/KernelTuner/ui/SDScannerConfigActivity.java
@@ -1,467 +1,467 @@
/*
* This file is part of the Kernel Tuner.
*
* Copyright Predrag Čokulov <[email protected]>
*
* Kernel Tuner 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 3 of the License, or
* (at your option) any later version.
*
* Kernel Tuner 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 Kernel Tuner. If not, see <http://www.gnu.org/licenses/>.
*/
package rs.pedjaapps.KernelTuner.ui;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.*;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import de.ankri.views.Switch;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import rs.pedjaapps.KernelTuner.R;
import rs.pedjaapps.KernelTuner.entry.SDSummaryEntry;
import rs.pedjaapps.KernelTuner.helpers.SDSummaryAdapter;
import rs.pedjaapps.KernelTuner.ui.SDScannerActivity;
import rs.pedjaapps.KernelTuner.ui.SDScannerConfigActivity;
public class SDScannerConfigActivity extends SherlockActivity
{
private Switch sw;
private static final int GET_CODE = 0;
String pt;
TextView path;
LinearLayout chart;
int labelColor;
SDSummaryAdapter summaryAdapter;
ProgressDialog pd;
List<SDSummaryEntry> entries;
String[] names = {"Applications(*.apk)", "Videos", "Music", "Images", "Documents", "Archives"};
int[] icons = {R.drawable.apk, R.drawable.movie, R.drawable.music, R.drawable.img, R.drawable.doc, R.drawable.arch};
private static final String CALCULATING = "calculating...";
ScanSDCard scanSDCard = new ScanSDCard();
@Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String theme = preferences.getString("theme", "light");
if(theme.equals("light")){
setTheme(R.style.SwitchCompatAndSherlockLight);
labelColor = Color.BLACK;
}
else if(theme.equals("dark")){
setTheme(R.style.SwitchCompatAndSherlock);
labelColor = Color.WHITE;
}
else if(theme.equals("light_dark_action_bar")){
setTheme(R.style.SwitchCompatAndSherlockLightDark);
labelColor = Color.BLACK;
}
super.onCreate(savedInstanceState);
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent==false){
finish();
Toast.makeText(this, "External Storage not mounted", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.sd_scanner_config);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
final SharedPreferences.Editor editor = preferences.edit();
boolean ads = preferences.getBoolean("ads", true);
if (ads == true)
{AdView adView = (AdView)findViewById(R.id.ad);
adView.loadAd(new AdRequest());}
sw = (Switch)findViewById(R.id.switch1);
sw.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
arg0.setText("Scann Folders+Files");
}
else if(arg0.isChecked()==false){
arg0.setText("Scann Folders");
}
}
});
final Switch displayType = (Switch)findViewById(R.id.display_in_switch);
displayType.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
arg0.setText("Dispay Result in List");
}
else if(arg0.isChecked()==false){
arg0.setText("Dispay Result in Chart");
}
}
});
path = (TextView)findViewById(R.id.path);
final EditText depth = (EditText)findViewById(R.id.editText2);
final EditText numberOfItems = (EditText)findViewById(R.id.editText3);
path.setText(preferences.getString("SDScanner_path", Environment.getExternalStorageDirectory().getPath()));
pt = preferences.getString("SDScanner_path", Environment.getExternalStorageDirectory().getPath());
depth.setText(preferences.getString("SDScanner_depth", "1"));
numberOfItems.setText(preferences.getString("SDScanner_items", "20"));
if(preferences.getBoolean("SDScanner_scann_type", false)){
sw.setChecked(true);
}
else{
sw.setChecked(false);
}
if(preferences.getBoolean("SDScanner_display_type", false)){
displayType.setChecked(true);
}
else{
displayType.setChecked(false);
}
Button scan = (Button)findViewById(R.id.button2);
scan.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String scannType = " ";
if(sw.isChecked()){
scannType = " -a ";
editor.putBoolean("SDScanner_scann_type", true);
}
else{
editor.putBoolean("SDScanner_scann_type", false);
}
Intent intent = new Intent();
intent.putExtra("path", pt);
intent.putExtra("depth", depth.getText().toString());
intent.putExtra("items", numberOfItems.getText().toString());
intent.putExtra("scannType", scannType);
if(displayType.isChecked()){
intent.setClass(SDScannerConfigActivity.this, SDScannerActivityList.class);
editor.putBoolean("SDScanner_display_type", true);
}
else{
intent.setClass(SDScannerConfigActivity.this, SDScannerActivity.class);
editor.putBoolean("SDScanner_display_type", false);
}
startActivity(intent);
editor.putString("SDScanner_path", path.getText().toString());
editor.putString("SDScanner_depth", depth.getText().toString());
editor.putString("SDScanner_items", numberOfItems.getText().toString());
editor.commit();
}
});
((Button)findViewById(R.id.browse)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
startActivityForResult(new Intent(SDScannerConfigActivity.this, FMActivity.class), GET_CODE);
}
});
ListView summaryListView = (ListView) findViewById(R.id.list);
summaryAdapter = new SDSummaryAdapter(this, R.layout.sd_conf_list_row);
summaryListView.setAdapter(summaryAdapter);
summaryAdapter.add(new SDSummaryEntry(names[0], CALCULATING, 0, 0, icons[0]));
summaryAdapter.add(new SDSummaryEntry(names[1], CALCULATING, 0, 0, icons[1]));
summaryAdapter.add(new SDSummaryEntry(names[2], CALCULATING, 0, 0, icons[2]));
summaryAdapter.add(new SDSummaryEntry(names[3], CALCULATING, 0, 0, icons[3]));
summaryAdapter.add(new SDSummaryEntry(names[4], CALCULATING, 0, 0, icons[4]));
summaryAdapter.add(new SDSummaryEntry(names[5], CALCULATING, 0, 0, icons[5]));
int apiLevel = Build.VERSION.SDK_INT;
- if(apiLevel <= android.os.Build.VERSION_CODES.GINGERBREAD_MR1){
+ if(apiLevel <= android.os.Build.VERSION_CODES.HONEYCOMB){
scanSDCard.execute();
}
else{
scanSDCard.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
@Override
protected void onResume() {
super.onResume();
((TextView)findViewById(R.id.mem_total)).setText("Total: "+size(getTotalSpaceInBytes()));
((TextView)findViewById(R.id.mem_used)).setText("Used: "+size(getUsedSpaceInBytes()));
((TextView)findViewById(R.id.mem_free)).setText("Free: "+size(getAvailableSpaceInBytes()));
}
public static long getAvailableSpaceInBytes() {
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace;
}
public static long getUsedSpaceInBytes() {
long usedSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
usedSpace = ((long) stat.getBlockCount() - stat.getAvailableBlocks()) * (long) stat.getBlockSize();
return usedSpace;
}
public static long getTotalSpaceInBytes() {
long totalSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
totalSpace = (long) stat.getBlockCount() * (long) stat.getBlockSize();
return totalSpace;
}
public String size(long size){
String hrSize = "";
long b = size;
double k = size/1024.0;
double m = size/1048576.0;
double g = size/1073741824.0;
double t = size/1099511627776.0;
DecimalFormat dec = new DecimalFormat("0.00");
if (t>1)
{
hrSize = dec.format(t).concat("TB");
}
else if (g>1)
{
hrSize = dec.format(g).concat("GB");
}
else if (m>1)
{
hrSize = dec.format(m).concat("MB");
}
else if (k>1)
{
hrSize = dec.format(k).concat("KB");
}
else if(b>1){
hrSize = dec.format(b).concat("B");
}
return hrSize;
}
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, KernelTuner.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_CODE){
if (resultCode == RESULT_OK) {
pt = data.getStringExtra("path");
path.setText(pt);
}
}
}
private class ScanSDCard extends AsyncTask<String, Integer, Void> {
long apk;
long video;
long music;
long images;
long doc;
long arch;
@Override
protected Void doInBackground(String... args) {
entries = new ArrayList<SDSummaryEntry>();
Iterator<File> apkIt = FileUtils.iterateFiles(Environment.getExternalStorageDirectory(), new String[] {"apk"}, true);
while(apkIt.hasNext()){
apk+=apkIt.next().length();
}
publishProgress(0);
Iterator<File> videoIt = FileUtils.iterateFiles(Environment.getExternalStorageDirectory(), new String[] {"avi", "mp4", "mkv", "m4v", "3gp"}, true);
while(videoIt.hasNext()){
video+=videoIt.next().length();
}
publishProgress(1);
Iterator<File> musicIt = FileUtils.iterateFiles(Environment.getExternalStorageDirectory(), new String[] {"mp3", "wma", "wav", "aac"}, true);
while(musicIt.hasNext()){
music+=musicIt.next().length();
}
publishProgress(2);
Iterator<File> imgIt = FileUtils.iterateFiles(Environment.getExternalStorageDirectory(), new String[] {"jpg", "jpeg", "png", "bmp", "jcs", "mpo"}, true);
while(imgIt.hasNext()){
images+=imgIt.next().length();
}
publishProgress(3);
Iterator<File> docIt = FileUtils.iterateFiles(Environment.getExternalStorageDirectory(), new String[] {"docx", "xls", "ppt", "docx", "pptx", "xlsx", "pdf", "epub"}, true);
while(docIt.hasNext()){
doc+=docIt.next().length();
}
publishProgress(4);
Iterator<File> archIt = FileUtils.iterateFiles(Environment.getExternalStorageDirectory(), new String[] {"zip", "jar", "rar", "7zip", "tar", "gz"}, true);
while(archIt.hasNext()){
arch+=archIt.next().length();
}
publishProgress(5);
return null;
}
@Override
protected void onProgressUpdate(Integer... values)
{
switch(values[0]){
case 0:
summaryAdapter.remove(summaryAdapter.getItem(0));
summaryAdapter.insert(new SDSummaryEntry(names[0], size(apk), apk, (int)(apk*100/getTotalSpaceInBytes()), icons[0]), 0);
entries.add(new SDSummaryEntry(names[0], size(apk), apk, (int)(apk*100/getTotalSpaceInBytes()), icons[0]));
break;
case 1:
summaryAdapter.remove(summaryAdapter.getItem(1));
summaryAdapter.insert(new SDSummaryEntry(names[1], size(video), video, (int)(video*100/getTotalSpaceInBytes()), icons[1]), 1);
entries.add(new SDSummaryEntry(names[1], size(video), video, (int)(video*100/getTotalSpaceInBytes()), icons[1]));
break;
case 2:
summaryAdapter.remove(summaryAdapter.getItem(2));
summaryAdapter.insert(new SDSummaryEntry(names[2], size(music), music, (int)(music*100/getTotalSpaceInBytes()), icons[2]), 2);
entries.add(new SDSummaryEntry(names[2], size(music), music, (int)(music*100/getTotalSpaceInBytes()), icons[2]));
break;
case 3:
summaryAdapter.remove(summaryAdapter.getItem(3));
summaryAdapter.insert(new SDSummaryEntry(names[3], size(images), images, (int)(images*100/getTotalSpaceInBytes()), icons[3]), 3);
entries.add(new SDSummaryEntry(names[3], size(images), images, (int)(images*100/getTotalSpaceInBytes()), icons[3]));
break;
case 4:
summaryAdapter.remove(summaryAdapter.getItem(4));
summaryAdapter.insert(new SDSummaryEntry(names[4], size(doc), doc, (int)(doc*100/getTotalSpaceInBytes()), icons[4]), 4);
entries.add(new SDSummaryEntry(names[4], size(doc), doc, (int)(doc*100/getTotalSpaceInBytes()), icons[4]));
break;
case 5:
summaryAdapter.remove(summaryAdapter.getItem(5));
summaryAdapter.insert(new SDSummaryEntry(names[5], size(arch), arch, (int)(arch*100/getTotalSpaceInBytes()), icons[5]), 5);
entries.add(new SDSummaryEntry(names[5], size(arch), arch, (int)(arch*100/getTotalSpaceInBytes()), icons[5]));
break;
}
super.onProgressUpdate();
}
@Override
protected void onPostExecute(Void res) {
summaryAdapter.clear();
Collections.sort(entries, new MyComparator());
for(SDSummaryEntry e : entries){
summaryAdapter.add(e);
}
summaryAdapter.notifyDataSetChanged();
}
@Override
protected void onPreExecute(){
}
}
class MyComparator implements Comparator<SDSummaryEntry>{
public int compare(SDSummaryEntry ob1, SDSummaryEntry ob2){
return ob2.getSize().compareTo(ob1.getSize()) ;
}
}
@Override
public void onDestroy(){
scanSDCard.cancel(true);
scanSDCard = null;
super.onDestroy();
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String theme = preferences.getString("theme", "light");
if(theme.equals("light")){
setTheme(R.style.SwitchCompatAndSherlockLight);
labelColor = Color.BLACK;
}
else if(theme.equals("dark")){
setTheme(R.style.SwitchCompatAndSherlock);
labelColor = Color.WHITE;
}
else if(theme.equals("light_dark_action_bar")){
setTheme(R.style.SwitchCompatAndSherlockLightDark);
labelColor = Color.BLACK;
}
super.onCreate(savedInstanceState);
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent==false){
finish();
Toast.makeText(this, "External Storage not mounted", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.sd_scanner_config);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
final SharedPreferences.Editor editor = preferences.edit();
boolean ads = preferences.getBoolean("ads", true);
if (ads == true)
{AdView adView = (AdView)findViewById(R.id.ad);
adView.loadAd(new AdRequest());}
sw = (Switch)findViewById(R.id.switch1);
sw.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
arg0.setText("Scann Folders+Files");
}
else if(arg0.isChecked()==false){
arg0.setText("Scann Folders");
}
}
});
final Switch displayType = (Switch)findViewById(R.id.display_in_switch);
displayType.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
arg0.setText("Dispay Result in List");
}
else if(arg0.isChecked()==false){
arg0.setText("Dispay Result in Chart");
}
}
});
path = (TextView)findViewById(R.id.path);
final EditText depth = (EditText)findViewById(R.id.editText2);
final EditText numberOfItems = (EditText)findViewById(R.id.editText3);
path.setText(preferences.getString("SDScanner_path", Environment.getExternalStorageDirectory().getPath()));
pt = preferences.getString("SDScanner_path", Environment.getExternalStorageDirectory().getPath());
depth.setText(preferences.getString("SDScanner_depth", "1"));
numberOfItems.setText(preferences.getString("SDScanner_items", "20"));
if(preferences.getBoolean("SDScanner_scann_type", false)){
sw.setChecked(true);
}
else{
sw.setChecked(false);
}
if(preferences.getBoolean("SDScanner_display_type", false)){
displayType.setChecked(true);
}
else{
displayType.setChecked(false);
}
Button scan = (Button)findViewById(R.id.button2);
scan.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String scannType = " ";
if(sw.isChecked()){
scannType = " -a ";
editor.putBoolean("SDScanner_scann_type", true);
}
else{
editor.putBoolean("SDScanner_scann_type", false);
}
Intent intent = new Intent();
intent.putExtra("path", pt);
intent.putExtra("depth", depth.getText().toString());
intent.putExtra("items", numberOfItems.getText().toString());
intent.putExtra("scannType", scannType);
if(displayType.isChecked()){
intent.setClass(SDScannerConfigActivity.this, SDScannerActivityList.class);
editor.putBoolean("SDScanner_display_type", true);
}
else{
intent.setClass(SDScannerConfigActivity.this, SDScannerActivity.class);
editor.putBoolean("SDScanner_display_type", false);
}
startActivity(intent);
editor.putString("SDScanner_path", path.getText().toString());
editor.putString("SDScanner_depth", depth.getText().toString());
editor.putString("SDScanner_items", numberOfItems.getText().toString());
editor.commit();
}
});
((Button)findViewById(R.id.browse)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
startActivityForResult(new Intent(SDScannerConfigActivity.this, FMActivity.class), GET_CODE);
}
});
ListView summaryListView = (ListView) findViewById(R.id.list);
summaryAdapter = new SDSummaryAdapter(this, R.layout.sd_conf_list_row);
summaryListView.setAdapter(summaryAdapter);
summaryAdapter.add(new SDSummaryEntry(names[0], CALCULATING, 0, 0, icons[0]));
summaryAdapter.add(new SDSummaryEntry(names[1], CALCULATING, 0, 0, icons[1]));
summaryAdapter.add(new SDSummaryEntry(names[2], CALCULATING, 0, 0, icons[2]));
summaryAdapter.add(new SDSummaryEntry(names[3], CALCULATING, 0, 0, icons[3]));
summaryAdapter.add(new SDSummaryEntry(names[4], CALCULATING, 0, 0, icons[4]));
summaryAdapter.add(new SDSummaryEntry(names[5], CALCULATING, 0, 0, icons[5]));
int apiLevel = Build.VERSION.SDK_INT;
if(apiLevel <= android.os.Build.VERSION_CODES.GINGERBREAD_MR1){
scanSDCard.execute();
}
else{
scanSDCard.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
| public void onCreate(Bundle savedInstanceState)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String theme = preferences.getString("theme", "light");
if(theme.equals("light")){
setTheme(R.style.SwitchCompatAndSherlockLight);
labelColor = Color.BLACK;
}
else if(theme.equals("dark")){
setTheme(R.style.SwitchCompatAndSherlock);
labelColor = Color.WHITE;
}
else if(theme.equals("light_dark_action_bar")){
setTheme(R.style.SwitchCompatAndSherlockLightDark);
labelColor = Color.BLACK;
}
super.onCreate(savedInstanceState);
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent==false){
finish();
Toast.makeText(this, "External Storage not mounted", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.sd_scanner_config);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
final SharedPreferences.Editor editor = preferences.edit();
boolean ads = preferences.getBoolean("ads", true);
if (ads == true)
{AdView adView = (AdView)findViewById(R.id.ad);
adView.loadAd(new AdRequest());}
sw = (Switch)findViewById(R.id.switch1);
sw.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
arg0.setText("Scann Folders+Files");
}
else if(arg0.isChecked()==false){
arg0.setText("Scann Folders");
}
}
});
final Switch displayType = (Switch)findViewById(R.id.display_in_switch);
displayType.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if(arg0.isChecked()){
arg0.setText("Dispay Result in List");
}
else if(arg0.isChecked()==false){
arg0.setText("Dispay Result in Chart");
}
}
});
path = (TextView)findViewById(R.id.path);
final EditText depth = (EditText)findViewById(R.id.editText2);
final EditText numberOfItems = (EditText)findViewById(R.id.editText3);
path.setText(preferences.getString("SDScanner_path", Environment.getExternalStorageDirectory().getPath()));
pt = preferences.getString("SDScanner_path", Environment.getExternalStorageDirectory().getPath());
depth.setText(preferences.getString("SDScanner_depth", "1"));
numberOfItems.setText(preferences.getString("SDScanner_items", "20"));
if(preferences.getBoolean("SDScanner_scann_type", false)){
sw.setChecked(true);
}
else{
sw.setChecked(false);
}
if(preferences.getBoolean("SDScanner_display_type", false)){
displayType.setChecked(true);
}
else{
displayType.setChecked(false);
}
Button scan = (Button)findViewById(R.id.button2);
scan.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String scannType = " ";
if(sw.isChecked()){
scannType = " -a ";
editor.putBoolean("SDScanner_scann_type", true);
}
else{
editor.putBoolean("SDScanner_scann_type", false);
}
Intent intent = new Intent();
intent.putExtra("path", pt);
intent.putExtra("depth", depth.getText().toString());
intent.putExtra("items", numberOfItems.getText().toString());
intent.putExtra("scannType", scannType);
if(displayType.isChecked()){
intent.setClass(SDScannerConfigActivity.this, SDScannerActivityList.class);
editor.putBoolean("SDScanner_display_type", true);
}
else{
intent.setClass(SDScannerConfigActivity.this, SDScannerActivity.class);
editor.putBoolean("SDScanner_display_type", false);
}
startActivity(intent);
editor.putString("SDScanner_path", path.getText().toString());
editor.putString("SDScanner_depth", depth.getText().toString());
editor.putString("SDScanner_items", numberOfItems.getText().toString());
editor.commit();
}
});
((Button)findViewById(R.id.browse)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
startActivityForResult(new Intent(SDScannerConfigActivity.this, FMActivity.class), GET_CODE);
}
});
ListView summaryListView = (ListView) findViewById(R.id.list);
summaryAdapter = new SDSummaryAdapter(this, R.layout.sd_conf_list_row);
summaryListView.setAdapter(summaryAdapter);
summaryAdapter.add(new SDSummaryEntry(names[0], CALCULATING, 0, 0, icons[0]));
summaryAdapter.add(new SDSummaryEntry(names[1], CALCULATING, 0, 0, icons[1]));
summaryAdapter.add(new SDSummaryEntry(names[2], CALCULATING, 0, 0, icons[2]));
summaryAdapter.add(new SDSummaryEntry(names[3], CALCULATING, 0, 0, icons[3]));
summaryAdapter.add(new SDSummaryEntry(names[4], CALCULATING, 0, 0, icons[4]));
summaryAdapter.add(new SDSummaryEntry(names[5], CALCULATING, 0, 0, icons[5]));
int apiLevel = Build.VERSION.SDK_INT;
if(apiLevel <= android.os.Build.VERSION_CODES.HONEYCOMB){
scanSDCard.execute();
}
else{
scanSDCard.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
|
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsIndex.java b/lucene/codecs/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsIndex.java
index 3262293ab..b7be254af 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsIndex.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/compressing/CompressingStoredFieldsIndex.java
@@ -1,411 +1,411 @@
package org.apache.lucene.codecs.compressing;
/*
* 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.IOException;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.packed.GrowableWriter;
import org.apache.lucene.util.packed.PackedInts;
/**
* A format for the stored fields index file (.fdx).
* <p>
* These formats allow different memory/speed trade-offs to locate documents
* into the fields data file (.fdt).
* @lucene.experimental
*/
public enum CompressingStoredFieldsIndex {
/**
* This format stores the document index on disk using 64-bits pointers to
* the start offsets of chunks in the fields data file.
* <p>
* This format has no memory overhead and requires at most 1 disk seek to
* locate a document in the fields data file. Use this format in
* memory-constrained environments.
*/
DISK_DOC(0) {
@Override
Writer newWriter(IndexOutput out) {
return new DiskDocFieldsIndexWriter(out);
}
@Override
Reader newReader(IndexInput in, SegmentInfo si) throws IOException {
return new DiskDocFieldsIndexReader(in, si);
}
},
/**
* For every document in the segment, this format stores the offset of the
* compressed chunk that contains it in the fields data file.
* <p>
* This fields index format requires at most <code>8 * numDocs</code> bytes
* of memory. Locating a document in the fields data file requires no disk
* seek. Use this format when blocks are very likely to contain few
* documents (in particular when <code>chunkSize = 1</code>).
*/
MEMORY_DOC(1) {
@Override
Writer newWriter(IndexOutput out) throws IOException {
return new ChunksFieldsIndexWriter(out);
}
@Override
Reader newReader(IndexInput in, SegmentInfo si) throws IOException {
return new MemoryDocFieldsIndexReader(in, si);
}
},
/**
* For every chunk of compressed documents, this format stores the first doc
* ID of the chunk as well as the start offset of the chunk.
* <p>
* This fields index format require at most
* <code>12 * numChunks</code> bytes of memory. Locating a document in the
* fields data file requires no disk seek. Use this format when chunks are
* likely to contain several documents.
*/
MEMORY_CHUNK(2) {
@Override
Writer newWriter(IndexOutput out) throws IOException {
return new ChunksFieldsIndexWriter(out);
}
@Override
Reader newReader(IndexInput in, SegmentInfo si) throws IOException {
return new MemoryChunkFieldsIndexReader(in, si);
}
};
/**
* Retrieve a {@link CompressingStoredFieldsIndex} according to its
* <code>ID</code>.
*/
public static CompressingStoredFieldsIndex byId(int id) {
for (CompressingStoredFieldsIndex idx : CompressingStoredFieldsIndex.values()) {
if (idx.getId() == id) {
return idx;
}
}
throw new IllegalArgumentException("Unknown id: " + id);
}
private final int id;
private CompressingStoredFieldsIndex(int id) {
this.id = id;
}
/**
* Returns an ID for this compression mode. Should be unique across
* {@link CompressionMode}s as it is used for serialization and
* unserialization.
*/
public final int getId() {
return id;
}
abstract Writer newWriter(IndexOutput out) throws IOException;
abstract Reader newReader(IndexInput in, SegmentInfo si) throws IOException;
static abstract class Writer implements Closeable {
protected final IndexOutput fieldsIndexOut;
Writer(IndexOutput indexOutput) {
this.fieldsIndexOut = indexOutput;
}
/** Write the index file for a chunk of <code>numDocs</code> docs starting
* at offset <code>startPointer</code>. */
abstract void writeIndex(int numDocs, long startPointer) throws IOException;
/** Finish writing an index file of <code>numDocs</code> documents. */
abstract void finish(int numDocs) throws IOException;
@Override
public void close() throws IOException {
fieldsIndexOut.close();
}
}
private static class DiskDocFieldsIndexWriter extends Writer {
final long startOffset;
DiskDocFieldsIndexWriter(IndexOutput fieldsIndexOut) {
super(fieldsIndexOut);
startOffset = fieldsIndexOut.getFilePointer();
}
@Override
void writeIndex(int numDocs, long startPointer) throws IOException {
for (int i = 0; i < numDocs; ++i) {
fieldsIndexOut.writeLong(startPointer);
}
}
@Override
void finish(int numDocs) throws IOException {
if (startOffset + ((long) numDocs) * 8 != fieldsIndexOut.getFilePointer()) {
// see Lucene40StoredFieldsWriter#finish
throw new RuntimeException((fieldsIndexOut.getFilePointer() - startOffset)/8 + " fdx size mismatch: docCount is " + numDocs + " but fdx file size is " + fieldsIndexOut.getFilePointer() + " file=" + fieldsIndexOut.toString() + "; now aborting this merge to prevent index corruption");
}
}
}
private static class ChunksFieldsIndexWriter extends Writer {
int numChunks;
long maxStartPointer;
GrowableWriter docBaseDeltas;
GrowableWriter startPointerDeltas;
ChunksFieldsIndexWriter(IndexOutput indexOutput) {
super(indexOutput);
numChunks = 0;
maxStartPointer = 0;
docBaseDeltas = new GrowableWriter(2, 128, PackedInts.COMPACT);
startPointerDeltas = new GrowableWriter(5, 128, PackedInts.COMPACT);
}
@Override
void writeIndex(int numDocs, long startPointer) throws IOException {
if (numChunks == docBaseDeltas.size()) {
final int newSize = ArrayUtil.oversize(numChunks + 1, 1);
docBaseDeltas = docBaseDeltas.resize(newSize);
startPointerDeltas = startPointerDeltas.resize(newSize);
}
docBaseDeltas.set(numChunks, numDocs);
startPointerDeltas.set(numChunks, startPointer - maxStartPointer);
++numChunks;
maxStartPointer = startPointer;
}
@Override
void finish(int numDocs) throws IOException {
if (numChunks != docBaseDeltas.size()) {
docBaseDeltas = docBaseDeltas.resize(numChunks);
startPointerDeltas = startPointerDeltas.resize(numChunks);
}
fieldsIndexOut.writeVInt(numChunks);
fieldsIndexOut.writeByte((byte) PackedInts.bitsRequired(maxStartPointer));
docBaseDeltas.save(fieldsIndexOut);
startPointerDeltas.save(fieldsIndexOut);
}
}
static abstract class Reader implements Cloneable, Closeable {
protected final IndexInput fieldsIndexIn;
Reader(IndexInput fieldsIndexIn) {
this.fieldsIndexIn = fieldsIndexIn;
}
/** Get the start pointer of the compressed block that contains docID */
abstract long getStartPointer(int docID) throws IOException;
public void close() throws IOException {
if (fieldsIndexIn != null) {
fieldsIndexIn.close();
}
}
public abstract Reader clone();
}
private static class DiskDocFieldsIndexReader extends Reader {
final long startPointer;
DiskDocFieldsIndexReader(IndexInput fieldsIndexIn, SegmentInfo si) throws CorruptIndexException {
this(fieldsIndexIn, fieldsIndexIn.getFilePointer());
final long indexSize = fieldsIndexIn.length() - fieldsIndexIn.getFilePointer();
final int numDocs = (int) (indexSize >> 3);
// Verify two sources of "maxDoc" agree:
if (numDocs != si.getDocCount()) {
throw new CorruptIndexException("doc counts differ for segment " + si + ": fieldsReader shows " + numDocs + " but segmentInfo shows " + si.getDocCount());
}
}
private DiskDocFieldsIndexReader(IndexInput fieldsIndexIn, long startPointer) {
super(fieldsIndexIn);
this.startPointer = startPointer;
}
@Override
long getStartPointer(int docID) throws IOException {
fieldsIndexIn.seek(startPointer + docID * 8L);
return fieldsIndexIn.readLong();
}
@Override
public Reader clone() {
return new DiskDocFieldsIndexReader(fieldsIndexIn.clone(), startPointer);
}
}
private static class MemoryDocFieldsIndexReader extends Reader {
private final PackedInts.Reader startPointers;
MemoryDocFieldsIndexReader(IndexInput fieldsIndexIn, SegmentInfo si) throws IOException {
super(fieldsIndexIn);
final int numChunks = fieldsIndexIn.readVInt();
final int bitsPerStartPointer = fieldsIndexIn.readByte() & 0xFF;
if (bitsPerStartPointer > 64) {
throw new CorruptIndexException("Corrupted");
}
final PackedInts.Reader chunkDocs = PackedInts.getReader(fieldsIndexIn);
if (chunkDocs.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + chunkDocs.size());
}
final PackedInts.ReaderIterator startPointerDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (startPointerDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + startPointerDeltas.size());
}
final PackedInts.Mutable startPointers = PackedInts.getMutable(si.getDocCount(), bitsPerStartPointer, PackedInts.COMPACT);
int docID = 0;
long startPointer = 0;
for (int i = 0; i < numChunks; ++i) {
startPointer += startPointerDeltas.next();
final int chunkDocCount = (int) chunkDocs.get(i);
for (int j = 0; j < chunkDocCount; ++j) {
startPointers.set(docID++, startPointer);
}
}
if (docID != si.getDocCount()) {
throw new CorruptIndexException("Expected " + si.getDocCount() + " docs, got " + docID);
}
this.startPointers = startPointers;
}
private MemoryDocFieldsIndexReader(PackedInts.Reader startPointers) {
super(null);
this.startPointers = startPointers;
}
@Override
long getStartPointer(int docID) throws IOException {
return startPointers.get(docID);
}
@Override
public Reader clone() {
if (fieldsIndexIn == null) {
return this;
} else {
return new MemoryDocFieldsIndexReader(startPointers);
}
}
}
private static class MemoryChunkFieldsIndexReader extends Reader {
private final PackedInts.Reader docBases;
private final PackedInts.Reader startPointers;
MemoryChunkFieldsIndexReader(IndexInput fieldsIndexIn, SegmentInfo si) throws IOException {
super(fieldsIndexIn);
final int numChunks = fieldsIndexIn.readVInt();
final int bitsPerStartPointer = fieldsIndexIn.readByte() & 0xFF;
if (bitsPerStartPointer > 64) {
throw new CorruptIndexException("Corrupted");
}
final PackedInts.ReaderIterator docBaseDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (docBaseDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + docBaseDeltas.size());
}
final PackedInts.Mutable docBases = PackedInts.getMutable(numChunks, PackedInts.bitsRequired(Math.max(0, si.getDocCount() - 1)), PackedInts.COMPACT);
int docBase = 0;
for (int i = 0; i < numChunks; ++i) {
docBases.set(i, docBase);
docBase += docBaseDeltas.next();
}
if (docBase != si.getDocCount()) {
throw new CorruptIndexException("Expected " + si.getDocCount() + " docs, got " + docBase);
}
final PackedInts.ReaderIterator startPointerDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (startPointerDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + startPointerDeltas.size());
}
final PackedInts.Mutable startPointers = PackedInts.getMutable(numChunks, bitsPerStartPointer, PackedInts.COMPACT);
- int startPointer = 0;
+ long startPointer = 0;
for (int i = 0; i < numChunks; ++i) {
startPointer += startPointerDeltas.next();
startPointers.set(i, startPointer);
}
this.docBases = docBases;
this.startPointers = startPointers;
}
private MemoryChunkFieldsIndexReader(PackedInts.Reader docBases, PackedInts.Reader startPointers) {
super(null);
this.docBases = docBases;
this.startPointers = startPointers;
}
@Override
long getStartPointer(int docID) {
assert docBases.size() > 0;
int lo = 0, hi = docBases.size() - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
final long midValue = docBases.get(mid);
if (midValue == docID) {
return startPointers.get(mid);
} else if (midValue < docID) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return startPointers.get(hi);
}
@Override
public Reader clone() {
if (fieldsIndexIn == null) {
return this;
} else {
return new MemoryChunkFieldsIndexReader(docBases, startPointers);
}
}
}
}
| true | true | MemoryChunkFieldsIndexReader(IndexInput fieldsIndexIn, SegmentInfo si) throws IOException {
super(fieldsIndexIn);
final int numChunks = fieldsIndexIn.readVInt();
final int bitsPerStartPointer = fieldsIndexIn.readByte() & 0xFF;
if (bitsPerStartPointer > 64) {
throw new CorruptIndexException("Corrupted");
}
final PackedInts.ReaderIterator docBaseDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (docBaseDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + docBaseDeltas.size());
}
final PackedInts.Mutable docBases = PackedInts.getMutable(numChunks, PackedInts.bitsRequired(Math.max(0, si.getDocCount() - 1)), PackedInts.COMPACT);
int docBase = 0;
for (int i = 0; i < numChunks; ++i) {
docBases.set(i, docBase);
docBase += docBaseDeltas.next();
}
if (docBase != si.getDocCount()) {
throw new CorruptIndexException("Expected " + si.getDocCount() + " docs, got " + docBase);
}
final PackedInts.ReaderIterator startPointerDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (startPointerDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + startPointerDeltas.size());
}
final PackedInts.Mutable startPointers = PackedInts.getMutable(numChunks, bitsPerStartPointer, PackedInts.COMPACT);
int startPointer = 0;
for (int i = 0; i < numChunks; ++i) {
startPointer += startPointerDeltas.next();
startPointers.set(i, startPointer);
}
this.docBases = docBases;
this.startPointers = startPointers;
}
| MemoryChunkFieldsIndexReader(IndexInput fieldsIndexIn, SegmentInfo si) throws IOException {
super(fieldsIndexIn);
final int numChunks = fieldsIndexIn.readVInt();
final int bitsPerStartPointer = fieldsIndexIn.readByte() & 0xFF;
if (bitsPerStartPointer > 64) {
throw new CorruptIndexException("Corrupted");
}
final PackedInts.ReaderIterator docBaseDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (docBaseDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + docBaseDeltas.size());
}
final PackedInts.Mutable docBases = PackedInts.getMutable(numChunks, PackedInts.bitsRequired(Math.max(0, si.getDocCount() - 1)), PackedInts.COMPACT);
int docBase = 0;
for (int i = 0; i < numChunks; ++i) {
docBases.set(i, docBase);
docBase += docBaseDeltas.next();
}
if (docBase != si.getDocCount()) {
throw new CorruptIndexException("Expected " + si.getDocCount() + " docs, got " + docBase);
}
final PackedInts.ReaderIterator startPointerDeltas = PackedInts.getReaderIterator(fieldsIndexIn, PackedInts.DEFAULT_BUFFER_SIZE);
if (startPointerDeltas.size() != numChunks) {
throw new CorruptIndexException("Expected " + numChunks + " chunks, but got " + startPointerDeltas.size());
}
final PackedInts.Mutable startPointers = PackedInts.getMutable(numChunks, bitsPerStartPointer, PackedInts.COMPACT);
long startPointer = 0;
for (int i = 0; i < numChunks; ++i) {
startPointer += startPointerDeltas.next();
startPointers.set(i, startPointer);
}
this.docBases = docBases;
this.startPointers = startPointers;
}
|
diff --git a/project-set/commons/utilities/src/main/java/com/rackspace/papi/commons/util/servlet/http/HeaderValuesImpl.java b/project-set/commons/utilities/src/main/java/com/rackspace/papi/commons/util/servlet/http/HeaderValuesImpl.java
index 1b5044fac3..429cbe9442 100644
--- a/project-set/commons/utilities/src/main/java/com/rackspace/papi/commons/util/servlet/http/HeaderValuesImpl.java
+++ b/project-set/commons/utilities/src/main/java/com/rackspace/papi/commons/util/servlet/http/HeaderValuesImpl.java
@@ -1,223 +1,225 @@
package com.rackspace.papi.commons.util.servlet.http;
import com.rackspace.papi.commons.util.http.HttpDate;
import com.rackspace.papi.commons.util.http.header.HeaderFieldParser;
import com.rackspace.papi.commons.util.http.header.HeaderValue;
import com.rackspace.papi.commons.util.http.header.HeaderValueImpl;
import com.rackspace.papi.commons.util.http.header.QualityFactorHeaderChooser;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class HeaderValuesImpl implements HeaderValues {
private static final String HEADERS_PREFIX = "repose.headers.";
private final Map<String, List<HeaderValue>> headers;
public static HeaderValues extract(HttpServletRequest request) {
return new HeaderValuesImpl(request, new RequestHeaderContainer(request));
}
public static HeaderValues extract(HttpServletRequest request, HttpServletResponse response) {
return new HeaderValuesImpl(request, new ResponseHeaderContainer(response));
}
private HeaderValuesImpl(HttpServletRequest request, HeaderContainer container) {
this.headers = initHeaders(request, container);
cloneHeaders(container);
}
private Map<String, List<HeaderValue>> initHeaders(HttpServletRequest request, HeaderContainer container) {
Map<String, List<HeaderValue>> currentHeaderMap = (Map<String, List<HeaderValue>>) request.getAttribute(HEADERS_PREFIX + container.getContainerType().name());
if (currentHeaderMap == null) {
currentHeaderMap = new HashMap<String, List<HeaderValue>>();
request.setAttribute(HEADERS_PREFIX + container.getContainerType().name(), currentHeaderMap);
}
return currentHeaderMap;
}
private void cloneHeaders(HeaderContainer request) {
final Map<String, List<HeaderValue>> headerMap = new HashMap<String, List<HeaderValue>>();
final List<String> headerNames = request.getHeaderNames();
for (String headerName : headerNames) {
final List<HeaderValue> headerValues = request.getHeaderValues(headerName.toLowerCase());
headerMap.put(headerName, headerValues);
}
headers.clear();
headers.putAll(headerMap);
}
private List<HeaderValue> parseHeaderValues(String value) {
HeaderFieldParser parser = new HeaderFieldParser(value);
return parser.parse();
}
@Override
public void addHeader(String name, String value) {
final String lowerCaseName = name.toLowerCase();
List<HeaderValue> headerValues = headers.get(lowerCaseName);
if (headerValues == null) {
headerValues = new LinkedList<HeaderValue>();
}
headerValues.addAll(parseHeaderValues(value));
headers.put(lowerCaseName, headerValues);
}
@Override
public void replaceHeader(String name, String value) {
final List<HeaderValue> headerValues = new LinkedList<HeaderValue>();
headerValues.addAll(parseHeaderValues(value));
headers.put(name.toLowerCase(), headerValues);
}
@Override
public void removeHeader(String name) {
headers.remove(name.toLowerCase());
}
@Override
public void clearHeaders() {
headers.clear();
}
@Override
public String getHeader(String name) {
HeaderValue value = fromMap(headers, name.toLowerCase());
return value != null ? value.toString() : null;
}
@Override
public HeaderValue getHeaderValue(String name) {
HeaderValue value = fromMap(headers, name.toLowerCase());
return value;
}
static <T> T fromMap(Map<String, List<T>> headers, String headerName) {
final List<T> headerValues = headers.get(headerName);
return (headerValues != null && headerValues.size() > 0) ? headerValues.get(0) : null;
}
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(headers.keySet());
}
@Override
public Enumeration<String> getHeaders(String name) {
final List<HeaderValue> headerValues = headers.get(name.toLowerCase());
final List<String> values = new LinkedList<String>();
if (headerValues != null) {
for (HeaderValue value : headerValues) {
values.add(value.toString());
}
}
return Collections.enumeration(values != null ? values : Collections.EMPTY_SET);
}
@Override
public List<HeaderValue> getPreferredHeaderValues(String name, HeaderValue defaultValue) {
/*
HeaderFieldParser parser = new HeaderFieldParser(headers.get(name.toLowerCase()));
List<HeaderValue> headerValues = parser.parse();
*/
List<HeaderValue> headerValues = headers.get(name.toLowerCase());
QualityFactorHeaderChooser chooser = new QualityFactorHeaderChooser<HeaderValue>();
List<HeaderValue> values = chooser.choosePreferredHeaderValues(headerValues);
if (values.isEmpty() && defaultValue != null) {
values.add(defaultValue);
}
return values;
}
@Override
public List<HeaderValue> getPreferredHeaders(String name, HeaderValue defaultValue) {
/*
HeaderFieldParser parser = new HeaderFieldParser(headers.get(name.toLowerCase()));
List<HeaderValue> headerValues = parser.parse();
*/
List<HeaderValue> headerValues = headers.get(name.toLowerCase());
- if (headerValues == null) {
- return new ArrayList<HeaderValue>();
+ if (headerValues == null || headerValues.isEmpty()) {
+ headerValues = new ArrayList<HeaderValue>();
+ headerValues.add(defaultValue);
+ return headerValues;
}
Map<Double, List<HeaderValue>> groupedHeaderValues = new LinkedHashMap<Double, List<HeaderValue>>();
for (HeaderValue value : headerValues) {
if (!groupedHeaderValues.keySet().contains(value.getQualityFactor())) {
groupedHeaderValues.put(value.getQualityFactor(), new LinkedList<HeaderValue>());
}
groupedHeaderValues.get(value.getQualityFactor()).add(value);
}
headerValues.clear();
List<Double> qualities = new ArrayList<Double>(groupedHeaderValues.keySet());
java.util.Collections.sort(qualities);
java.util.Collections.reverse(qualities);
for (Double quality : qualities) {
headerValues.addAll(groupedHeaderValues.get(quality));
}
if (headerValues.isEmpty() && defaultValue != null) {
headerValues.add(defaultValue);
}
return headerValues;
}
@Override
public boolean containsHeader(String name) {
return headers.containsKey(name);
}
@Override
public void addDateHeader(String name, long value) {
final String lowerCaseName = name.toLowerCase();
List<HeaderValue> headerValues = headers.get(lowerCaseName);
if (headerValues == null) {
headerValues = new LinkedList<HeaderValue>();
}
HttpDate date = new HttpDate(new Date(value));
headerValues.add(new HeaderValueImpl(date.toRFC1123()));
headers.put(lowerCaseName, headerValues);
}
@Override
public void replaceDateHeader(String name, long value) {
headers.remove(name);
addDateHeader(name, value);
}
@Override
public List<HeaderValue> getHeaderValues(String name) {
return headers.get(name);
}
}
| true | true | public List<HeaderValue> getPreferredHeaders(String name, HeaderValue defaultValue) {
/*
HeaderFieldParser parser = new HeaderFieldParser(headers.get(name.toLowerCase()));
List<HeaderValue> headerValues = parser.parse();
*/
List<HeaderValue> headerValues = headers.get(name.toLowerCase());
if (headerValues == null) {
return new ArrayList<HeaderValue>();
}
Map<Double, List<HeaderValue>> groupedHeaderValues = new LinkedHashMap<Double, List<HeaderValue>>();
for (HeaderValue value : headerValues) {
if (!groupedHeaderValues.keySet().contains(value.getQualityFactor())) {
groupedHeaderValues.put(value.getQualityFactor(), new LinkedList<HeaderValue>());
}
groupedHeaderValues.get(value.getQualityFactor()).add(value);
}
headerValues.clear();
List<Double> qualities = new ArrayList<Double>(groupedHeaderValues.keySet());
java.util.Collections.sort(qualities);
java.util.Collections.reverse(qualities);
for (Double quality : qualities) {
headerValues.addAll(groupedHeaderValues.get(quality));
}
if (headerValues.isEmpty() && defaultValue != null) {
headerValues.add(defaultValue);
}
return headerValues;
}
| public List<HeaderValue> getPreferredHeaders(String name, HeaderValue defaultValue) {
/*
HeaderFieldParser parser = new HeaderFieldParser(headers.get(name.toLowerCase()));
List<HeaderValue> headerValues = parser.parse();
*/
List<HeaderValue> headerValues = headers.get(name.toLowerCase());
if (headerValues == null || headerValues.isEmpty()) {
headerValues = new ArrayList<HeaderValue>();
headerValues.add(defaultValue);
return headerValues;
}
Map<Double, List<HeaderValue>> groupedHeaderValues = new LinkedHashMap<Double, List<HeaderValue>>();
for (HeaderValue value : headerValues) {
if (!groupedHeaderValues.keySet().contains(value.getQualityFactor())) {
groupedHeaderValues.put(value.getQualityFactor(), new LinkedList<HeaderValue>());
}
groupedHeaderValues.get(value.getQualityFactor()).add(value);
}
headerValues.clear();
List<Double> qualities = new ArrayList<Double>(groupedHeaderValues.keySet());
java.util.Collections.sort(qualities);
java.util.Collections.reverse(qualities);
for (Double quality : qualities) {
headerValues.addAll(groupedHeaderValues.get(quality));
}
if (headerValues.isEmpty() && defaultValue != null) {
headerValues.add(defaultValue);
}
return headerValues;
}
|
diff --git a/ridiculousRPG/src/com/madthrax/ridiculousRPG/animations/BoundedImage.java b/ridiculousRPG/src/com/madthrax/ridiculousRPG/animations/BoundedImage.java
index f8f43e0..00530ce 100644
--- a/ridiculousRPG/src/com/madthrax/ridiculousRPG/animations/BoundedImage.java
+++ b/ridiculousRPG/src/com/madthrax/ridiculousRPG/animations/BoundedImage.java
@@ -1,68 +1,68 @@
package com.madthrax.ridiculousRPG.animations;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.madthrax.ridiculousRPG.GameBase;
import com.madthrax.ridiculousRPG.TextureRegionLoader.TextureRegionRef;
public class BoundedImage {
private TextureRegionRef image;
private Rectangle bounds;
private boolean scroll;
private Rectangle scrollReference;
/**
* Scales the image to fit into the bounds
*
* @param image
* the image to draw
* @param bounds
* the bounds for drawing the image
*/
public BoundedImage(TextureRegionRef image, Rectangle bounds) {
this(image, bounds, false, null);
}
/**
* The image will not be scaled, but scrolls inside the bounds.<br>
* Scrolling is performed when scrollReference.x or scrollReference.y
* changes. The scroll speed/amount is computed relatively from
* bounds.width/scrollReference.width and
* bounds.height/scrollReference.height.
*
* @param image
* the image to draw
* @param bounds
* the bounds for drawing the image
* @param scrollReference
* the bounds which are used to compute/perform scrolling.<br>
* If null GameBase.$().getPlane() will be used.
*/
public BoundedImage(TextureRegionRef image, Rectangle bounds,
Rectangle scrollReference) {
this(image, bounds, true, scrollReference);
}
private BoundedImage(TextureRegionRef image, Rectangle bounds,
boolean scroll, Rectangle scrollReference) {
this.image = image;
this.bounds = bounds;
this.scroll = scroll;
this.scrollReference = scrollReference;
if (scroll && scrollReference == null) {
// TODO: change Gamebase.screenWidth, Gamebase.planeWidth,
// Gamebase.originalWidth
// to Rectangles for easier usage.
- scrollReference = GameBase.$().getPlane();
+ //scrollReference = GameBase.$().getPlane();
}
}
public void draw(SpriteBatch spriteBatch) {
if (scroll) {
// TODO: scroll in bounds relative depending on scrollReference
} else {
spriteBatch.draw(image, bounds.x, bounds.y, bounds.width,
bounds.height);
}
}
}
| true | true | private BoundedImage(TextureRegionRef image, Rectangle bounds,
boolean scroll, Rectangle scrollReference) {
this.image = image;
this.bounds = bounds;
this.scroll = scroll;
this.scrollReference = scrollReference;
if (scroll && scrollReference == null) {
// TODO: change Gamebase.screenWidth, Gamebase.planeWidth,
// Gamebase.originalWidth
// to Rectangles for easier usage.
scrollReference = GameBase.$().getPlane();
}
}
| private BoundedImage(TextureRegionRef image, Rectangle bounds,
boolean scroll, Rectangle scrollReference) {
this.image = image;
this.bounds = bounds;
this.scroll = scroll;
this.scrollReference = scrollReference;
if (scroll && scrollReference == null) {
// TODO: change Gamebase.screenWidth, Gamebase.planeWidth,
// Gamebase.originalWidth
// to Rectangles for easier usage.
//scrollReference = GameBase.$().getPlane();
}
}
|
diff --git a/src/com/android/exchange/eas/EasOperation.java b/src/com/android/exchange/eas/EasOperation.java
index 3d4fe224..893bf74f 100644
--- a/src/com/android/exchange/eas/EasOperation.java
+++ b/src/com/android/exchange/eas/EasOperation.java
@@ -1,522 +1,522 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.android.exchange.eas;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SyncResult;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.format.DateUtils;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.Eas;
import com.android.exchange.EasResponse;
import com.android.exchange.adapter.Serializer;
import com.android.exchange.adapter.Tags;
import com.android.exchange.service.EasServerConnection;
import com.android.mail.utils.LogUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import java.io.IOException;
/**
* Base class for all Exchange operations that use a POST to talk to the server.
*
* The core of this class is {@link #performOperation}, which provides the skeleton of making
* a request, handling common errors, and setting fields on the {@link SyncResult} if there is one.
* This class abstracts the connection handling from its subclasses and callers.
*
* A subclass must implement the abstract functions below that create the request and parse the
* response. There are also a set of functions that a subclass may override if it's substantially
* different from the "normal" operation (e.g. most requests use the same request URI, but auto
* discover deviates since it's not account-specific), but the default implementation should suffice
* for most. The subclass must also define a public function which calls {@link #performOperation},
* possibly doing nothing other than that. (I chose to force subclasses to do this, rather than
* provide that function in the base class, in order to force subclasses to consider, for example,
* whether it needs a {@link SyncResult} parameter, and what the proper name for the "doWork"
* function ought to be for the subclass.)
*/
public abstract class EasOperation {
public static final String LOG_TAG = Eas.LOG_TAG;
/** The maximum number of server redirects we allow before returning failure. */
private static final int MAX_REDIRECTS = 3;
/** Message MIME type for EAS version 14 and later. */
private static final String EAS_14_MIME_TYPE = "application/vnd.ms-sync.wbxml";
/** Error code indicating the operation was cancelled via {@link #abort}. */
public static final int RESULT_ABORT = -1;
/** Error code indicating the operation was cancelled via {@link #restart}. */
public static final int RESULT_RESTART = -2;
/** Error code indicating the Exchange servers redirected too many times. */
public static final int RESULT_TOO_MANY_REDIRECTS = -3;
/** Error code indicating the request failed due to a network problem. */
public static final int RESULT_REQUEST_FAILURE = -4;
/** Error code indicating a 403 (forbidden) error. */
public static final int RESULT_FORBIDDEN = -5;
/** Error code indicating an unresolved provisioning error. */
public static final int RESULT_PROVISIONING_ERROR = -6;
/** Error code indicating an authentication problem. */
public static final int RESULT_AUTHENTICATION_ERROR = -7;
/** Error code indicating the client is missing a certificate. */
public static final int RESULT_CLIENT_CERTIFICATE_REQUIRED = -8;
/** Error code indicating we don't have a protocol version in common with the server. */
public static final int RESULT_PROTOCOL_VERSION_UNSUPPORTED = -9;
/** Error code indicating some other failure. */
public static final int RESULT_OTHER_FAILURE = -10;
protected final Context mContext;
/**
* The account id for this operation.
* NOTE: You will be tempted to add a reference to the {@link Account} here. Resist.
* It's too easy for that to lead to creep and stale data.
*/
protected final long mAccountId;
private final EasServerConnection mConnection;
// TODO: Make this private again when EasSyncHandler is converted to be a subclass.
protected EasOperation(final Context context, final long accountId,
final EasServerConnection connection) {
mContext = context;
mAccountId = accountId;
mConnection = connection;
}
protected EasOperation(final Context context, final Account account, final HostAuth hostAuth) {
this(context, account.mId, new EasServerConnection(context, account, hostAuth));
}
protected EasOperation(final Context context, final Account account) {
this(context, account, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
}
/**
* This constructor is for use by operations that are created by other operations, e.g.
* {@link EasProvision}.
* @param parentOperation The {@link EasOperation} that is creating us.
*/
protected EasOperation(final EasOperation parentOperation) {
this(parentOperation.mContext, parentOperation.mAccountId, parentOperation.mConnection);
}
/**
* Request that this operation terminate. Intended for use by the sync service to interrupt
* running operations, primarily Ping.
*/
public final void abort() {
mConnection.stop(EasServerConnection.STOPPED_REASON_ABORT);
}
/**
* Request that this operation restart. Intended for use by the sync service to interrupt
* running operations, primarily Ping.
*/
public final void restart() {
mConnection.stop(EasServerConnection.STOPPED_REASON_RESTART);
}
/**
* The skeleton of performing an operation. This function handles all the common code and
* error handling, calling into virtual functions that are implemented or overridden by the
* subclass to do the operation-specific logic.
*
* The result codes work as follows:
* - Negative values indicate common error codes and are defined above (the various RESULT_*
* constants).
* - Non-negative values indicate the result of {@link #handleResponse}. These are obviously
* specific to the subclass, and may indicate success or error conditions.
*
* The common error codes primarily indicate conditions that occur when performing the POST
* itself, such as network errors and handling of the HTTP response. However, some errors that
* can be indicated in the HTTP response code can also be indicated in the payload of the
* response as well, so {@link #handleResponse} should in those cases return the appropriate
* negative result code, which will be handled the same as if it had been indicated in the HTTP
* response code.
*
* @param syncResult If this operation is a sync, the {@link SyncResult} object that should
* be written to for this sync; otherwise null.
* @return A result code for the outcome of this operation, as described above.
*/
protected final int performOperation(final SyncResult syncResult) {
// We handle server redirects by looping, but we need to protect against too much looping.
int redirectCount = 0;
do {
// Perform the HTTP request and handle exceptions.
final EasResponse response;
try {
if (registerClientCert()) {
response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout());
} else {
// TODO: Is this the best stat to increment?
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
} catch (final IOException e) {
// If we were stopped, return the appropriate result code.
switch (mConnection.getStoppedReason()) {
case EasServerConnection.STOPPED_REASON_ABORT:
return RESULT_ABORT;
case EasServerConnection.STOPPED_REASON_RESTART:
return RESULT_RESTART;
default:
break;
}
// If we're here, then we had a IOException that's not from a stop request.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
} catch (final IllegalStateException e) {
// Subclasses use ISE to signal a hard error when building the request.
// TODO: Switch away from ISEs.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
syncResult.databaseError = true;
}
return RESULT_OTHER_FAILURE;
}
// The POST completed, so process the response.
try {
final int result;
// First off, the success case.
if (response.isSuccess()) {
try {
result = handleResponse(response, syncResult);
if (result >= 0) {
return result;
}
} catch (final IOException e) {
LogUtils.e(LOG_TAG, e, "Exception while handling response");
if (syncResult != null) {
++syncResult.stats.numParseExceptions;
}
return RESULT_OTHER_FAILURE;
}
} else {
result = RESULT_OTHER_FAILURE;
}
// If this operation has distinct handling for 403 errors, do that.
if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) {
LogUtils.e(LOG_TAG, "Forbidden response");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_FORBIDDEN;
}
// Handle provisioning errors.
if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) {
if (handleProvisionError(syncResult, mAccountId)) {
// The provisioning error has been taken care of, so we should re-do this
// request.
continue;
}
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_PROVISIONING_ERROR;
}
// Handle authentication errors.
if (response.isAuthError()) {
LogUtils.e(LOG_TAG, "Authentication error");
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
if (response.isMissingCertificate()) {
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
return RESULT_AUTHENTICATION_ERROR;
}
// Handle redirects.
if (response.isRedirectError()) {
++redirectCount;
mConnection.redirectHostAuth(response.getRedirectAddress());
// Note that unlike other errors, we do NOT return here; we just keep looping.
} else {
// All other errors.
- LogUtils.e(LOG_TAG, "Generic error");
+ LogUtils.e(LOG_TAG, "Generic error: " + response.getStatus());
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numIoExceptions;
}
return RESULT_OTHER_FAILURE;
}
} finally {
response.close();
}
} while (redirectCount < MAX_REDIRECTS);
// Non-redirects return immediately after handling, so the only way to reach here is if we
// looped too many times.
LogUtils.e(LOG_TAG, "Too many redirects");
if (syncResult != null) {
syncResult.tooManyRetries = true;
}
return RESULT_TOO_MANY_REDIRECTS;
}
/**
* Reset the protocol version to use for this connection. If it's changed, and our account is
* persisted, also write back the changes to the DB.
* @param protocolVersion The new protocol version to use, as a string.
*/
protected final void setProtocolVersion(final String protocolVersion) {
if (mConnection.setProtocolVersion(protocolVersion) && mAccountId != Account.NOT_SAVED) {
final Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
final ContentValues cv = new ContentValues(2);
if (getProtocolVersion() >= 12.0) {
final int oldFlags = Utility.getFirstRowInt(mContext, uri,
Account.ACCOUNT_FLAGS_PROJECTION, null, null, null,
Account.ACCOUNT_FLAGS_COLUMN_FLAGS, 0);
final int newFlags = oldFlags
| Account.FLAGS_SUPPORTS_GLOBAL_SEARCH + Account.FLAGS_SUPPORTS_SEARCH;
if (oldFlags != newFlags) {
cv.put(EmailContent.AccountColumns.FLAGS, newFlags);
}
}
cv.put(EmailContent.AccountColumns.PROTOCOL_VERSION, protocolVersion);
mContext.getContentResolver().update(uri, cv, null, null);
}
}
/**
* Create the request object for this operation.
* Most operations use a POST, but some use other request types (e.g. Options).
* @return An {@link HttpUriRequest}.
* @throws IOException
*/
private final HttpUriRequest makeRequest() throws IOException {
final String requestUri = getRequestUri();
if (requestUri == null) {
return mConnection.makeOptions();
}
return mConnection.makePost(requestUri, getRequestEntity(),
getRequestContentType(), addPolicyKeyHeaderToRequest());
}
/**
* The following functions MUST be overridden by subclasses; these are things that are unique
* to each operation.
*/
/**
* Get the name of the operation, used as the "Cmd=XXX" query param in the request URI. Note
* that if you override {@link #getRequestUri}, then this function may be unused, but it's
* abstract in order to make it impossible to omit for the subclasses that do need it.
* @return The name of the command for this operation as defined by the EAS protocol.
*/
protected abstract String getCommand();
/**
* Build the {@link HttpEntity} which is used to construct the POST. Typically this function
* will build the Exchange request using a {@link Serializer} and then call {@link #makeEntity}.
* If the subclass is not using a POST, then it should override this to return null.
* @return The {@link HttpEntity} to pass to {@link EasServerConnection#makePost}.
* @throws IOException
*/
protected abstract HttpEntity getRequestEntity() throws IOException;
/**
* Parse the response from the Exchange perform whatever actions are dictated by that.
* @param response The {@link EasResponse} to our request.
* @param syncResult The {@link SyncResult} object for this operation, or null if we're not
* handling a sync.
* @return A result code. Non-negative values are returned directly to the caller; negative
* values
*
* that is returned to the caller of {@link #performOperation}.
* @throws IOException
*/
protected abstract int handleResponse(final EasResponse response, final SyncResult syncResult)
throws IOException;
/**
* The following functions may be overriden by a subclass, but most operations will not need
* to do so.
*/
/**
* Get the URI for the Exchange server and this operation. Most (signed in) operations need
* not override this; the notable operation that needs to override it is auto-discover.
* @return
*/
protected String getRequestUri() {
return mConnection.makeUriString(getCommand());
}
/**
* @return Whether to set the X-MS-PolicyKey header. Only Ping does not want this header.
*/
protected boolean addPolicyKeyHeaderToRequest() {
return true;
}
/**
* @return The content type of this request.
*/
protected String getRequestContentType() {
return EAS_14_MIME_TYPE;
}
/**
* @return The timeout to use for the POST.
*/
protected long getTimeout() {
return 30 * DateUtils.SECOND_IN_MILLIS;
}
/**
* If 403 responses should be handled in a special way, this function should be overridden to
* do that.
* @return Whether we handle 403 responses; if false, then treat 403 as a provisioning error.
*/
protected boolean handleForbidden() {
return false;
}
/**
* Handle a provisioning error. Subclasses may override this to do something different, e.g.
* to validate rather than actually do the provisioning.
* @param syncResult
* @param accountId
* @return
*/
protected boolean handleProvisionError(final SyncResult syncResult, final long accountId) {
final EasProvision provisionOperation = new EasProvision(this);
return provisionOperation.provision(syncResult, accountId);
}
/**
* Convenience methods for subclasses to use.
*/
/**
* Convenience method to make an {@link HttpEntity} from {@link Serializer}.
*/
protected final HttpEntity makeEntity(final Serializer s) {
return new ByteArrayEntity(s.toByteArray());
}
/**
* Check whether we should ask the server what protocol versions it supports and set this
* account to use that version.
* @return Whether we need a new protocol version from the server.
*/
protected final boolean shouldGetProtocolVersion() {
// TODO: Find conditions under which we should check other than not having one yet.
return !mConnection.isProtocolVersionSet();
}
/**
* @return The protocol version to use.
*/
protected final double getProtocolVersion() {
return mConnection.getProtocolVersion();
}
/**
* @return Our useragent.
*/
protected final String getUserAgent() {
return mConnection.getUserAgent();
}
/**
* @return Whether we succeeeded in registering the client cert.
*/
protected final boolean registerClientCert() {
return mConnection.registerClientCert();
}
/**
* Add the device information to the current request.
* @param s The {@link Serializer} for our current request.
* @throws IOException
*/
protected final void addDeviceInformationToSerlializer(final Serializer s) throws IOException {
s.start(Tags.SETTINGS_DEVICE_INFORMATION).start(Tags.SETTINGS_SET);
s.data(Tags.SETTINGS_MODEL, Build.MODEL);
//s.data(Tags.SETTINGS_IMEI, "");
//s.data(Tags.SETTINGS_FRIENDLY_NAME, "Friendly Name");
s.data(Tags.SETTINGS_OS, "Android " + Build.VERSION.RELEASE);
//s.data(Tags.SETTINGS_OS_LANGUAGE, "");
//s.data(Tags.SETTINGS_PHONE_NUMBER, "");
//s.data(Tags.SETTINGS_MOBILE_OPERATOR, "");
s.data(Tags.SETTINGS_USER_AGENT, getUserAgent());
s.end().end(); // SETTINGS_SET, SETTINGS_DEVICE_INFORMATION
}
/**
* Convenience method for adding a Message to an account's outbox
* @param account The {@link Account} from which to send the message.
* @param msg the message to send
*/
protected final void sendMessage(final Account account, final EmailContent.Message msg) {
long mailboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX);
// TODO: Improve system mailbox handling.
if (mailboxId == Mailbox.NO_MAILBOX) {
LogUtils.d(LOG_TAG, "No outbox for account %d, creating it", account.mId);
final Mailbox outbox =
Mailbox.newSystemMailbox(mContext, account.mId, Mailbox.TYPE_OUTBOX);
outbox.save(mContext);
mailboxId = outbox.mId;
}
msg.mMailboxKey = mailboxId;
msg.mAccountKey = account.mId;
msg.save(mContext);
requestSyncForMailbox(new android.accounts.Account(account.mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), EmailContent.AUTHORITY, mailboxId);
}
/**
* Issue a {@link android.content.ContentResolver#requestSync} for a specific mailbox.
* @param amAccount The {@link android.accounts.Account} for the account we're pinging.
* @param authority The authority for the mailbox that needs to sync.
* @param mailboxId The id of the mailbox that needs to sync.
*/
protected static void requestSyncForMailbox(final android.accounts.Account amAccount,
final String authority, final long mailboxId) {
final Bundle extras = new Bundle(1);
extras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId);
ContentResolver.requestSync(amAccount, authority, extras);
LogUtils.i(LOG_TAG, "requestSync EasOperation requestSyncForMailbox %s, %s",
amAccount.toString(), extras.toString());
}
}
| true | true | protected final int performOperation(final SyncResult syncResult) {
// We handle server redirects by looping, but we need to protect against too much looping.
int redirectCount = 0;
do {
// Perform the HTTP request and handle exceptions.
final EasResponse response;
try {
if (registerClientCert()) {
response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout());
} else {
// TODO: Is this the best stat to increment?
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
} catch (final IOException e) {
// If we were stopped, return the appropriate result code.
switch (mConnection.getStoppedReason()) {
case EasServerConnection.STOPPED_REASON_ABORT:
return RESULT_ABORT;
case EasServerConnection.STOPPED_REASON_RESTART:
return RESULT_RESTART;
default:
break;
}
// If we're here, then we had a IOException that's not from a stop request.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
} catch (final IllegalStateException e) {
// Subclasses use ISE to signal a hard error when building the request.
// TODO: Switch away from ISEs.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
syncResult.databaseError = true;
}
return RESULT_OTHER_FAILURE;
}
// The POST completed, so process the response.
try {
final int result;
// First off, the success case.
if (response.isSuccess()) {
try {
result = handleResponse(response, syncResult);
if (result >= 0) {
return result;
}
} catch (final IOException e) {
LogUtils.e(LOG_TAG, e, "Exception while handling response");
if (syncResult != null) {
++syncResult.stats.numParseExceptions;
}
return RESULT_OTHER_FAILURE;
}
} else {
result = RESULT_OTHER_FAILURE;
}
// If this operation has distinct handling for 403 errors, do that.
if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) {
LogUtils.e(LOG_TAG, "Forbidden response");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_FORBIDDEN;
}
// Handle provisioning errors.
if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) {
if (handleProvisionError(syncResult, mAccountId)) {
// The provisioning error has been taken care of, so we should re-do this
// request.
continue;
}
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_PROVISIONING_ERROR;
}
// Handle authentication errors.
if (response.isAuthError()) {
LogUtils.e(LOG_TAG, "Authentication error");
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
if (response.isMissingCertificate()) {
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
return RESULT_AUTHENTICATION_ERROR;
}
// Handle redirects.
if (response.isRedirectError()) {
++redirectCount;
mConnection.redirectHostAuth(response.getRedirectAddress());
// Note that unlike other errors, we do NOT return here; we just keep looping.
} else {
// All other errors.
LogUtils.e(LOG_TAG, "Generic error");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numIoExceptions;
}
return RESULT_OTHER_FAILURE;
}
} finally {
response.close();
}
} while (redirectCount < MAX_REDIRECTS);
// Non-redirects return immediately after handling, so the only way to reach here is if we
// looped too many times.
LogUtils.e(LOG_TAG, "Too many redirects");
if (syncResult != null) {
syncResult.tooManyRetries = true;
}
return RESULT_TOO_MANY_REDIRECTS;
}
| protected final int performOperation(final SyncResult syncResult) {
// We handle server redirects by looping, but we need to protect against too much looping.
int redirectCount = 0;
do {
// Perform the HTTP request and handle exceptions.
final EasResponse response;
try {
if (registerClientCert()) {
response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout());
} else {
// TODO: Is this the best stat to increment?
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
} catch (final IOException e) {
// If we were stopped, return the appropriate result code.
switch (mConnection.getStoppedReason()) {
case EasServerConnection.STOPPED_REASON_ABORT:
return RESULT_ABORT;
case EasServerConnection.STOPPED_REASON_RESTART:
return RESULT_RESTART;
default:
break;
}
// If we're here, then we had a IOException that's not from a stop request.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
} catch (final IllegalStateException e) {
// Subclasses use ISE to signal a hard error when building the request.
// TODO: Switch away from ISEs.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
syncResult.databaseError = true;
}
return RESULT_OTHER_FAILURE;
}
// The POST completed, so process the response.
try {
final int result;
// First off, the success case.
if (response.isSuccess()) {
try {
result = handleResponse(response, syncResult);
if (result >= 0) {
return result;
}
} catch (final IOException e) {
LogUtils.e(LOG_TAG, e, "Exception while handling response");
if (syncResult != null) {
++syncResult.stats.numParseExceptions;
}
return RESULT_OTHER_FAILURE;
}
} else {
result = RESULT_OTHER_FAILURE;
}
// If this operation has distinct handling for 403 errors, do that.
if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) {
LogUtils.e(LOG_TAG, "Forbidden response");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_FORBIDDEN;
}
// Handle provisioning errors.
if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) {
if (handleProvisionError(syncResult, mAccountId)) {
// The provisioning error has been taken care of, so we should re-do this
// request.
continue;
}
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_PROVISIONING_ERROR;
}
// Handle authentication errors.
if (response.isAuthError()) {
LogUtils.e(LOG_TAG, "Authentication error");
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
if (response.isMissingCertificate()) {
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
return RESULT_AUTHENTICATION_ERROR;
}
// Handle redirects.
if (response.isRedirectError()) {
++redirectCount;
mConnection.redirectHostAuth(response.getRedirectAddress());
// Note that unlike other errors, we do NOT return here; we just keep looping.
} else {
// All other errors.
LogUtils.e(LOG_TAG, "Generic error: " + response.getStatus());
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numIoExceptions;
}
return RESULT_OTHER_FAILURE;
}
} finally {
response.close();
}
} while (redirectCount < MAX_REDIRECTS);
// Non-redirects return immediately after handling, so the only way to reach here is if we
// looped too many times.
LogUtils.e(LOG_TAG, "Too many redirects");
if (syncResult != null) {
syncResult.tooManyRetries = true;
}
return RESULT_TOO_MANY_REDIRECTS;
}
|
diff --git a/amibe/src/org/jcae/mesh/amibe/validation/QualityFloat.java b/amibe/src/org/jcae/mesh/amibe/validation/QualityFloat.java
index 9ff3247a..bddc7765 100644
--- a/amibe/src/org/jcae/mesh/amibe/validation/QualityFloat.java
+++ b/amibe/src/org/jcae/mesh/amibe/validation/QualityFloat.java
@@ -1,423 +1,425 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
Copyright (C) 2005, by EADS CRC
Copyright (C) 2007, by EADS France
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
package org.jcae.mesh.amibe.validation;
import gnu.trove.TFloatArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.PrintStream;
import org.apache.log4j.Logger;
/**
* Manage statistics for quality values.
*
* This class allows easy computation of mesh quality. A criterion
* factor can be selected, then quality is computed and results are
* printed on screen or in files. Quality values are stored in a list
* of floats.
*
* Example:
* <pre>
* QualityFloat data = new QualityFloat();
* data.setQualityProcedure(new DihedralAngle());
* for (Iterator itf = mesh.getTriangles().iterator(); itf.hasNext(); )
* {
* Triangle f = (Triangle) itf.next();
* data.compute(f);
* }
* // Print all results in the BB mesh format.
* data.printMeshBB("foo.bb");
* // Gather results into 10 blocks...
* data.split(10);
* // ... and display them on screen.
* data.printLayers();
* </pre>
*/
public class QualityFloat
{
private static Logger logger=Logger.getLogger(QualityFloat.class);
private TFloatArrayList data;
private QualityProcedure qproc;
private int [] sorted;
private float [] bounds;
private int layers = -1;
private float scaleFactor = 1.0f;
private float qmin, qmax, qavg, qavg2;
private int imin, imax;
public QualityFloat()
{
data = new TFloatArrayList();
}
/**
* Create a new <code>QualityFloat</code> instance
*
* @param n initial capacity of the list.
*/
public QualityFloat(int n)
{
data = new TFloatArrayList(n);
}
/**
* Define the procedure which will compute quality values.
*
* @param q the procedure which will compute quality values.
*/
public void setQualityProcedure(QualityProcedure q)
{
qproc = q;
qproc.bindResult(data);
scaleFactor = qproc.getScaleFactor();
}
/**
* Compute the quality of an object and add it to the list.
*
* @param x the object on which quality is computed.
*/
public void compute(Object x)
{
assert qproc != null;
data.add(qproc.quality(x));
}
/**
* Add a value to the list.
*
* @param x the value to add to the list.
*/
public void add(float x)
{
data.add(x);
}
/**
* Call the {@link QualityProcedure#finish} procedure.
*/
public void finish()
{
qproc.finish();
qmin = Float.MAX_VALUE;
qmax = Float.MIN_VALUE;
qavg = 0.0f;
qavg2 = 0.0f;
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i) * scaleFactor;
data.set(i, val);
}
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
qavg += val / n;
qavg2 += val * val / n;
if (qmin > val)
{
qmin = val;
imin = i;
}
if (qmax < val)
{
qmax = val;
imax = i;
}
}
}
/**
* Return value by its distribution index. Returned value is
* such that there are <code>p*N</code> values below it, where
* <code>N</code> is the total number of values. For instance,
* <code>getValueByPercent(0.0)</code> (resp. 1 and 0.5) returns
* minimum value (resp. maximum value and median value).
*
* @param p number between 0 and 1
* @return value associated to this distribution index
*/
public float getValueByPercent(double p)
{
if (p <= 0.0)
return qmin;
if (p >= 1.0)
return qmax;
float [] values = new float[1000];
int [] number = new int[values.length+1];
int target = (int) (p * data.size());
return getValueByPercentPrivate(target, qmin, qmax, values, number);
}
private float getValueByPercentPrivate(int target, float q1, float q2, float [] values, int [] number)
{
float delta = (q2 - q1) / values.length;
if (delta == 0.0f)
return q1;
if (delta < 0.0f)
throw new IllegalArgumentException();
for (int i = 0; i < values.length; i++)
values[i] = q1 + i * delta;
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
int cell = (int) ((val - q1) / delta + 1.001f);
if (cell <= 0)
number[0]++;
else if (cell < number.length)
number[cell]++;
+ else
+ number[number.length - 1]++;
}
- int sum = number[0];
- for (int i = 1; i <= number.length; i++)
+ for (int i = 1; i < number.length; i++)
+ number[i] += number[i-1];
+ for (int i = 1; i < number.length; i++)
{
- if (sum == target)
+ if (number[i] == target)
return values[i-1];
- else if (sum > target)
+ else if (number[i] > target)
{
- if (number[i] == 1)
+ if (number[i]-number[i-1] <= 1 || i == number.length - 1)
return values[i-1];
return getValueByPercentPrivate(target, values[i-1], values[i], values, number);
}
- sum += number[i];
}
throw new RuntimeException();
}
/**
* Return mean value
*/
public float getMeanValue()
{
return qavg;
}
/**
* Return standard deviation
*/
public float getStandardDeviation()
{
return (float) Math.sqrt(qavg2 - qavg*qavg);
}
/**
* Return the number of quality values.
*
* @return the number of quality values.
*/
public int size()
{
return data.size();
}
/**
* Normalize quality target. This method divides all values
* by the given factor. This is useful to scale quality
* factors so that they are in the range </code>[0..1]</code>.
*
* @param factor the scale factor.
*/
public void setTarget(float factor)
{
scaleFactor = 1.0f / factor;
}
/**
* Split quality values into buckets. The minimal and
* maximal quality values are computed, this range is divided
* into <code>n</code> subsegments of equal length, and
* the number of quality values for each subsegment is
* computed. These numbers can then be displayed by
* {@link #printLayers}.
*
* @param nr the desired number of subsegments.
*/
public void split(int nr)
{
layers = nr;
if (layers <= 0)
return;
// min() and max() methods are buggy in trove 1.0.2
float delta = (qmax - qmin) / layers;
// In printLayers:
// sorted[0]: number of points with value < qmin
// sorted[layers+1]: number of points with value > qmax
sorted = new int[layers+2];
bounds = new float[layers+1];
for (int i = 0; i < bounds.length; i++)
bounds[i] = qmin + i * delta;
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
int cell = (int) ((val - qmin) / delta + 1.001f);
assert cell > 0 && cell <= layers;
sorted[cell]++;
}
}
/**
* Split quality values into buckets. The range between minimal
* and maximal quality values is divided into <code>nr</code>
* subsegments of equal length, and the number of quality values
* for each subsegment is computed. These numbers can then be
* displayed by {@link #printLayers}.
*
* @param v1 minimal value to consider.
* @param v2 maximal value to consider.
* @param nr the desired number of subsegments.
*/
public void split(float v1, float v2, int nr)
{
layers = nr;
float vmin = v1;
float vmax = v2;
if (layers <= 0)
return;
// The last cell is for v >= vmax
float delta = (vmax - vmin) / layers;
sorted = new int[layers+2];
bounds = new float[layers+1];
for (int i = 0; i < bounds.length; i++)
bounds[i] = vmin + i * delta;
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
int cell = (int) ((val - vmin) / delta + 1.001f);
if (cell < 0)
cell = 0;
else if (cell >= layers + 1)
{
if (val > vmax)
cell = layers + 1;
else
cell = layers;
}
sorted[cell]++;
}
}
public void split(float... v)
{
layers = v.length - 1;
if (layers < 0)
return;
bounds = new float[layers+1];
int cnt = 0;
for (float f: v)
bounds[cnt++] = f;
sorted = new int[layers+2];
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
int cell = 0;
for (; cell < bounds.length; cell++)
if (val < bounds[cell])
break;
sorted[cell]++;
}
}
/**
* Display histogram about quality values.
*/
public void printLayers()
{
if (layers < 0)
{
logger.error("split() method must be called before printLayers()");
return;
}
int nrTotal = data.size();
if (sorted[0] > 0)
System.out.println(" < "+bounds[0]+" "+sorted[0]+" ("+(((float) 100.0 * sorted[0])/nrTotal)+"%)");
for (int i = 0; i < layers; i++)
{
System.out.println(" "+bounds[i]+" ; "+bounds[i+1]+" "+sorted[i+1]+" ("+(((float) 100.0 * sorted[i+1])/nrTotal)+"%)");
}
if (sorted[layers+1] > 0)
System.out.println(" > "+bounds[layers]+" "+sorted[layers+1]+" ("+(((float) 100.0 * sorted[layers+1])/nrTotal)+"%)");
printStatistics();
}
/**
* Display statistics about quality values.
*/
public void printStatistics()
{
int nrTotal = data.size();
System.out.println("total: "+nrTotal);
System.out.println("qmin: "+qmin+" (index="+imin+" starting from 0)");
System.out.println("qmax: "+qmax+" (index="+imax+" starting from 0)");
System.out.println("qavg: "+qavg);
System.out.println("qdev: "+Math.sqrt(qavg2 - qavg*qavg));
}
/**
* Write quality values into a file. They are stored in the
* BB medit format, in the same order as they have been
* computed. This means that a mesh file had been written with
* the same order.
*
* @param file name of the output file
*/
public void printMeshBB(String file)
{
int nrTotal = data.size();
try
{
PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(file)));
out.println("3 1 "+nrTotal+" "+qproc.getType());
for (int i = 0; i < nrTotal; i++)
out.println(""+data.get(i));
out.close();
}
catch (FileNotFoundException ex)
{
logger.error("Cannot write into: "+file);
}
}
/**
* Write quality values into a raw file. They are stored in
* machine format, in the same order as they have been computed.
*
* @param file name of the output file
*/
public void writeRawData(String file)
{
try
{
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for (int i = 0, n = data.size(); i < n; i++)
out.writeFloat(data.get(i));
out.close();
}
catch (FileNotFoundException ex)
{
logger.error("Cannot write into: "+file);
}
catch (IOException ex)
{
logger.error("Error when writing data into "+file);
}
}
}
| false | true | private float getValueByPercentPrivate(int target, float q1, float q2, float [] values, int [] number)
{
float delta = (q2 - q1) / values.length;
if (delta == 0.0f)
return q1;
if (delta < 0.0f)
throw new IllegalArgumentException();
for (int i = 0; i < values.length; i++)
values[i] = q1 + i * delta;
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
int cell = (int) ((val - q1) / delta + 1.001f);
if (cell <= 0)
number[0]++;
else if (cell < number.length)
number[cell]++;
}
int sum = number[0];
for (int i = 1; i <= number.length; i++)
{
if (sum == target)
return values[i-1];
else if (sum > target)
{
if (number[i] == 1)
return values[i-1];
return getValueByPercentPrivate(target, values[i-1], values[i], values, number);
}
sum += number[i];
}
throw new RuntimeException();
}
| private float getValueByPercentPrivate(int target, float q1, float q2, float [] values, int [] number)
{
float delta = (q2 - q1) / values.length;
if (delta == 0.0f)
return q1;
if (delta < 0.0f)
throw new IllegalArgumentException();
for (int i = 0; i < values.length; i++)
values[i] = q1 + i * delta;
for (int i = 0, n = data.size(); i < n; i++)
{
float val = data.get(i);
int cell = (int) ((val - q1) / delta + 1.001f);
if (cell <= 0)
number[0]++;
else if (cell < number.length)
number[cell]++;
else
number[number.length - 1]++;
}
for (int i = 1; i < number.length; i++)
number[i] += number[i-1];
for (int i = 1; i < number.length; i++)
{
if (number[i] == target)
return values[i-1];
else if (number[i] > target)
{
if (number[i]-number[i-1] <= 1 || i == number.length - 1)
return values[i-1];
return getValueByPercentPrivate(target, values[i-1], values[i], values, number);
}
}
throw new RuntimeException();
}
|
diff --git a/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/TargetToRepoMojo.java b/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/TargetToRepoMojo.java
index c15d516..a6a09f0 100644
--- a/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/TargetToRepoMojo.java
+++ b/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/TargetToRepoMojo.java
@@ -1,188 +1,188 @@
/**
* Copyright (c) 2012, Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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
*
* Contributor:
* Mickael Istria (Red Hat, Inc.) - initial API and implementation
*/
package org.jboss.tools.tycho.targets;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import org.eclipse.sisu.equinox.EquinoxServiceFactory;
import org.eclipse.tycho.BuildOutputDirectory;
import org.eclipse.tycho.artifacts.TargetPlatform;
import org.eclipse.tycho.core.resolver.shared.MavenRepositoryLocation;
import org.eclipse.tycho.osgi.adapters.MavenLoggerAdapter;
import org.eclipse.tycho.p2.resolver.TargetDefinitionFile;
import org.eclipse.tycho.p2.resolver.facade.P2ResolutionResult;
import org.eclipse.tycho.p2.resolver.facade.P2Resolver;
import org.eclipse.tycho.p2.resolver.facade.P2ResolverFactory;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.InstallableUnitLocation;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Location;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Repository;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Unit;
import org.eclipse.tycho.p2.target.facade.TargetPlatformBuilder;
import org.eclipse.tycho.p2.tools.DestinationRepositoryDescriptor;
import org.eclipse.tycho.p2.tools.RepositoryReferences;
import org.eclipse.tycho.p2.tools.mirroring.facade.IUDescription;
import org.eclipse.tycho.p2.tools.mirroring.facade.MirrorApplicationService;
import org.eclipse.tycho.p2.tools.mirroring.facade.MirrorOptions;
/**
* Mirrors a target file as a p2 repo. Suitable for sharing/caching target/dependency sites.
*
* @author mistria
* @goal mirror-target-to-repo
*/
public class TargetToRepoMojo extends AbstractMojo {
/**
* @parameter default-value="${project}"
* @readonly
*/
private MavenProject project;
/**
* @parameter expression="${session}"
* @readonly
*/
private MavenSession session;
/**
* @component
*/
@Requirement
private RepositorySystem repositorySystem;
/**
* @parameter
*/
private File sourceTargetFile;
/**
* @parameter
*/
private TargetArtifact sourceTargetArtifact;
/**
* @parameter expression="${mirror-target-to-repo.includeSources}"
*/
private boolean includeSources;
/**
* @parameter expression="${project.build.directory}/${project.artifactId}.target.repo"
*/
private File outputRepository;
/** @component */
private EquinoxServiceFactory equinox;
/** @component */
private Logger plexusLogger;
public void execute() throws MojoExecutionException, MojoFailureException {
try {
if (this.sourceTargetArtifact != null && this.sourceTargetFile != null) {
getLog().debug("sourceTargetArtifact: " + this.sourceTargetArtifact.toString());
getLog().debug("sourceTargetFile; " + this.sourceTargetFile.toString());
throw new MojoExecutionException("Set either 'sourceTargetArtifact' XOR 'sourceTargetFile'");
}
if (this.sourceTargetFile == null && this.sourceTargetArtifact == null) {
this.sourceTargetFile = new File(this.project.getBasedir(), this.project.getArtifactId() + ".target");
}
if (this.sourceTargetArtifact != null) {
this.sourceTargetFile = this.sourceTargetArtifact.getFile(this.repositorySystem, this.session, this.project);
}
if (!this.sourceTargetFile.isFile()) {
throw new MojoExecutionException("Specified 'targetFile' (value: " + sourceTargetFile + ") is not a valid file");
}
this.outputRepository.mkdirs();
final MirrorApplicationService mirrorService = equinox.getService(MirrorApplicationService.class);
TargetDefinitionFile target = TargetDefinitionFile.read(sourceTargetFile);
final RepositoryReferences sourceDescriptor = new RepositoryReferences();
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
for (Repository repo : ((InstallableUnitLocation)loc).getRepositories()) {
sourceDescriptor.addMetadataRepository(repo.getLocation());
sourceDescriptor.addArtifactRepository(repo.getLocation());
}
}
}
final DestinationRepositoryDescriptor destinationDescriptor = new DestinationRepositoryDescriptor(this.outputRepository, this.sourceTargetFile.getName(), true, false, true);
mirrorService.mirrorStandalone(sourceDescriptor, destinationDescriptor, createIUDescriptions(target), createMirrorOptions(), new BuildOutputDirectory(this.project.getBuild().getOutputDirectory()));
} catch (Exception ex) {
throw new MojoExecutionException("Internal error", ex);
}
}
private Collection<IUDescription> createIUDescriptions(TargetDefinitionFile target) {
List<IUDescription> result = new ArrayList<IUDescription>();
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
for (Unit unit : ((InstallableUnitLocation)loc).getUnits()) {
result.add(new IUDescription(unit.getId(), unit.getVersion()));
}
}
}
if (this.includeSources) {
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
InstallableUnitLocation location = (InstallableUnitLocation)loc;
TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(new MockExecutionEnvironment());
for (Repository repo : location.getRepositories()) {
tpBuilder.addP2Repository(new MavenRepositoryLocation(repo.getId(), repo.getLocation()));
}
TargetPlatform site = tpBuilder.buildTargetPlatform();
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : ((InstallableUnitLocation)loc).getUnits()) {
- String newUnitId = null;
+ String sourceUnitId = null;
int featureSuffixIndex = unit.getId().lastIndexOf(".feature.group");
if (featureSuffixIndex >= 0) {
- newUnitId = unit.getId().substring(0, featureSuffixIndex) + ".source.feature.group";
+ sourceUnitId = unit.getId().substring(0, featureSuffixIndex) + ".source.feature.group";
} else {
- newUnitId = unit.getId() + ".source";
+ sourceUnitId = unit.getId() + ".source";
}
- P2ResolutionResult resolvedSource = resolver.resolveInstallableUnit(site, newUnitId, "[" + unit.getVersion() + "," + unit.getVersion() + "]");
+ P2ResolutionResult resolvedSource = resolver.resolveInstallableUnit(site, sourceUnitId, "[" + unit.getVersion() + "," + unit.getVersion() + "]");
if (resolvedSource.getArtifacts().size() > 0 || resolvedSource.getNonReactorUnits().size() > 0) {
- result.add(new IUDescription(unit.getId() + ".source", unit.getVersion()));
+ result.add(new IUDescription(sourceUnitId, unit.getVersion()));
getLog().debug("Got source for " + unit.getId() + "/" + unit.getVersion());
} else {
getLog().warn("Could not find source for " + unit.getId() + "/" + unit.getVersion());
}
}
}
}
}
return result;
}
private static MirrorOptions createMirrorOptions() {
MirrorOptions options = new MirrorOptions();
options.setFollowOnlyFilteredRequirements(false);
options.setFollowStrictOnly(true);
options.setIncludeFeatures(true);
options.setIncludeNonGreedy(true);
options.setIncludeOptional(true);
options.setLatestVersionOnly(false);
return options;
}
}
| false | true | private Collection<IUDescription> createIUDescriptions(TargetDefinitionFile target) {
List<IUDescription> result = new ArrayList<IUDescription>();
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
for (Unit unit : ((InstallableUnitLocation)loc).getUnits()) {
result.add(new IUDescription(unit.getId(), unit.getVersion()));
}
}
}
if (this.includeSources) {
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
InstallableUnitLocation location = (InstallableUnitLocation)loc;
TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(new MockExecutionEnvironment());
for (Repository repo : location.getRepositories()) {
tpBuilder.addP2Repository(new MavenRepositoryLocation(repo.getId(), repo.getLocation()));
}
TargetPlatform site = tpBuilder.buildTargetPlatform();
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : ((InstallableUnitLocation)loc).getUnits()) {
String newUnitId = null;
int featureSuffixIndex = unit.getId().lastIndexOf(".feature.group");
if (featureSuffixIndex >= 0) {
newUnitId = unit.getId().substring(0, featureSuffixIndex) + ".source.feature.group";
} else {
newUnitId = unit.getId() + ".source";
}
P2ResolutionResult resolvedSource = resolver.resolveInstallableUnit(site, newUnitId, "[" + unit.getVersion() + "," + unit.getVersion() + "]");
if (resolvedSource.getArtifacts().size() > 0 || resolvedSource.getNonReactorUnits().size() > 0) {
result.add(new IUDescription(unit.getId() + ".source", unit.getVersion()));
getLog().debug("Got source for " + unit.getId() + "/" + unit.getVersion());
} else {
getLog().warn("Could not find source for " + unit.getId() + "/" + unit.getVersion());
}
}
}
}
}
return result;
}
| private Collection<IUDescription> createIUDescriptions(TargetDefinitionFile target) {
List<IUDescription> result = new ArrayList<IUDescription>();
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
for (Unit unit : ((InstallableUnitLocation)loc).getUnits()) {
result.add(new IUDescription(unit.getId(), unit.getVersion()));
}
}
}
if (this.includeSources) {
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
for (final Location loc : target.getLocations()) {
if (loc instanceof InstallableUnitLocation) {
InstallableUnitLocation location = (InstallableUnitLocation)loc;
TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(new MockExecutionEnvironment());
for (Repository repo : location.getRepositories()) {
tpBuilder.addP2Repository(new MavenRepositoryLocation(repo.getId(), repo.getLocation()));
}
TargetPlatform site = tpBuilder.buildTargetPlatform();
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : ((InstallableUnitLocation)loc).getUnits()) {
String sourceUnitId = null;
int featureSuffixIndex = unit.getId().lastIndexOf(".feature.group");
if (featureSuffixIndex >= 0) {
sourceUnitId = unit.getId().substring(0, featureSuffixIndex) + ".source.feature.group";
} else {
sourceUnitId = unit.getId() + ".source";
}
P2ResolutionResult resolvedSource = resolver.resolveInstallableUnit(site, sourceUnitId, "[" + unit.getVersion() + "," + unit.getVersion() + "]");
if (resolvedSource.getArtifacts().size() > 0 || resolvedSource.getNonReactorUnits().size() > 0) {
result.add(new IUDescription(sourceUnitId, unit.getVersion()));
getLog().debug("Got source for " + unit.getId() + "/" + unit.getVersion());
} else {
getLog().warn("Could not find source for " + unit.getId() + "/" + unit.getVersion());
}
}
}
}
}
return result;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/MicromanagerReader.java b/components/bio-formats/src/loci/formats/in/MicromanagerReader.java
index 32e1cbb67..bf3cbbcf7 100644
--- a/components/bio-formats/src/loci/formats/in/MicromanagerReader.java
+++ b/components/bio-formats/src/loci/formats/in/MicromanagerReader.java
@@ -1,448 +1,450 @@
//
// MicromanagerReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.text.*;
import java.util.*;
import loci.common.*;
import loci.formats.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
/**
* MicromanagerReader is the file format reader for Micro-Manager files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/MicromanagerReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/MicromanagerReader.java">SVN</a></dd></dl>
*/
public class MicromanagerReader extends FormatReader {
// -- Constants --
/** File containing extra metadata. */
private static final String METADATA = "metadata.txt";
// -- Fields --
/** Helper reader for TIFF files. */
private MinimalTiffReader tiffReader;
/** List of TIFF files to open. */
private Vector tiffs;
private String metadataFile;
private String[] channels;
private String comment, time;
private Float exposureTime, sliceThickness, pixelSize;
private Float[] timestamps;
private int gain;
private String binning, detectorID, detectorModel, detectorManufacturer;
private float temperature;
private Vector voltage;
private String cameraRef;
private String cameraMode;
// -- Constructor --
/** Constructs a new Micromanager reader. */
public MicromanagerReader() {
super("Micro-Manager", new String[] {"tif", "tiff", "txt"});
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (name.equals(METADATA) || name.endsWith(File.separator + METADATA)) {
try {
RandomAccessStream stream = new RandomAccessStream(name);
long length = stream.length();
stream.close();
return length > 0;
}
catch (IOException e) {
return false;
}
}
if (!open) return false; // not allowed to touch the file system
try {
Location parent = new Location(name).getAbsoluteFile().getParentFile();
Location metaFile = new Location(parent, METADATA);
return metaFile.exists() && metaFile.length() > 0;
}
catch (NullPointerException e) { }
return false;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessStream) */
public boolean isThisType(RandomAccessStream stream) throws IOException {
return tiffReader.isThisType(stream);
}
/* @see loci.formats.IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
String[] s = new String[tiffs.size() + 1];
tiffs.copyInto(s);
s[tiffs.size()] = metadataFile;
return s;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
int[] coords = getZCTCoords(no);
tiffReader.setId((String) tiffs.get(no));
return tiffReader.openBytes(0, buf, x, y, w, h);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
if (fileOnly) {
if (tiffReader != null) tiffReader.close(fileOnly);
}
else close();
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
if (tiffReader != null) tiffReader.close();
tiffReader = null;
tiffs = null;
comment = time = null;
exposureTime = sliceThickness = pixelSize = null;
timestamps = null;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
public void initFile(String id) throws FormatException, IOException {
super.initFile(id);
tiffReader = new MinimalTiffReader();
status("Reading metadata file");
// find metadata.txt
Location file = new Location(currentId).getAbsoluteFile();
metadataFile = file.exists() ? new Location(file.getParentFile(),
METADATA).getAbsolutePath() : METADATA;
in = new RandomAccessStream(metadataFile);
String parent = file.exists() ?
file.getParentFile().getAbsolutePath() + File.separator : "";
// usually a small file, so we can afford to read it into memory
byte[] meta = new byte[(int) in.length()];
in.read(meta);
String s = new String(meta);
meta = null;
status("Finding image file names");
// find the name of a TIFF file
String baseTiff = null;
tiffs = new Vector();
int pos = 0;
while (true) {
pos = s.indexOf("FileName", pos);
if (pos == -1 || pos >= in.length()) break;
String name = s.substring(s.indexOf(":", pos), s.indexOf(",", pos));
baseTiff = parent + name.substring(3, name.length() - 1);
pos++;
}
// now parse the rest of the metadata
// metadata.txt looks something like this:
//
// {
// "Section Name": {
// "Key": "Value",
// "Array key": [
// first array value, second array value
// ]
// }
//
// }
status("Populating metadata");
Vector stamps = new Vector();
Vector voltage = new Vector();
StringTokenizer st = new StringTokenizer(s, "\n");
int[] slice = new int[3];
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
boolean open = token.indexOf("[") != -1;
boolean closed = token.indexOf("]") != -1;
if (open || (!open && !closed && !token.equals("{") &&
!token.startsWith("}")))
{
int quote = token.indexOf("\"") + 1;
String key = token.substring(quote, token.indexOf("\"", quote));
String value = null;
if (!open && !closed) {
value = token.substring(token.indexOf(":") + 1);
}
else if (!closed){
StringBuffer valueBuffer = new StringBuffer();
while (!closed) {
token = st.nextToken();
closed = token.indexOf("]") != -1;
valueBuffer.append(token);
}
value = valueBuffer.toString();
value = value.replaceAll("\n", "");
}
int startIndex = value.indexOf("[");
int endIndex = value.indexOf("]");
if (endIndex == -1) endIndex = value.length();
value = value.substring(startIndex + 1, endIndex).trim();
value = value.substring(0, value.length() - 1);
value = value.replaceAll("\"", "");
if (value.endsWith(",")) value = value.substring(0, value.length() - 1);
addMeta(key, value);
if (key.equals("Channels")) core[0].sizeC = Integer.parseInt(value);
else if (key.equals("ChNames")) {
StringTokenizer t = new StringTokenizer(value, ",");
int nTokens = t.countTokens();
channels = new String[nTokens];
for (int q=0; q<nTokens; q++) {
channels[q] = t.nextToken().replaceAll("\"", "").trim();
}
}
else if (key.equals("Frames")) {
core[0].sizeT = Integer.parseInt(value);
}
else if (key.equals("Slices")) {
core[0].sizeZ = Integer.parseInt(value);
}
else if (key.equals("PixelSize_um")) {
pixelSize = new Float(value);
}
else if (key.equals("z-step_um")) {
sliceThickness = new Float(value);
}
else if (key.equals("Time")) time = value;
else if (key.equals("Comment")) comment = value;
}
if (token.startsWith("\"FrameKey")) {
int dash = token.indexOf("-") + 1;
int nextDash = token.indexOf("-", dash);
slice[2] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
nextDash = token.indexOf("-", dash);
slice[1] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
slice[0] = Integer.parseInt(token.substring(dash,
token.indexOf("\"", dash)));
token = st.nextToken().trim();
String key = "", value = "";
while (!token.startsWith("}")) {
int colon = token.indexOf(":");
key = token.substring(1, colon).trim();
value = token.substring(colon + 1, token.length() - 1).trim();
key = key.replaceAll("\"", "");
value = value.replaceAll("\"", "");
addMeta(key, value);
if (key.equals("Exposure-ms")) {
float t = Float.parseFloat(value);
exposureTime = new Float(t / 1000);
}
else if (key.equals("ElapsedTime-ms")) {
float t = Float.parseFloat(value);
stamps.add(new Float(t / 1000));
}
else if (key.equals("Core-Camera")) cameraRef = value;
else if (key.equals(cameraRef + "-Binning")) {
binning = value;
}
else if (key.equals(cameraRef + "-CameraID")) detectorID = value;
else if (key.equals(cameraRef + "-CameraName")) detectorModel = value;
else if (key.equals(cameraRef + "-Gain")) {
gain = Integer.parseInt(value);
}
else if (key.equals(cameraRef + "-Name")) {
detectorManufacturer = value;
}
else if (key.equals(cameraRef + "-Temperature")) {
temperature = Float.parseFloat(value);
}
else if (key.equals(cameraRef + "-CCDMode")) {
cameraMode = value;
}
else if (key.startsWith("DAC-") && key.endsWith("-Volts")) {
voltage.add(new Float(value));
}
token = st.nextToken().trim();
}
}
}
timestamps = (Float[]) stamps.toArray(new Float[0]);
Arrays.sort(timestamps);
// build list of TIFF files
String prefix = "";
if (baseTiff.indexOf(File.separator) != -1) {
prefix = baseTiff.substring(0, baseTiff.lastIndexOf(File.separator) + 1);
baseTiff = baseTiff.substring(baseTiff.lastIndexOf(File.separator) + 1);
}
String[] blocks = baseTiff.split("_");
StringBuffer filename = new StringBuffer();
for (int t=0; t<getSizeT(); t++) {
for (int c=0; c<getSizeC(); c++) {
for (int z=0; z<getSizeZ(); z++) {
// file names are of format:
// img_<T>_<channel name>_<T>.tif
filename.append(prefix);
filename.append(blocks[0]);
filename.append("_");
int zeros = blocks[1].length() - String.valueOf(t).length();
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(t);
filename.append("_");
filename.append(channels[c]);
filename.append("_");
zeros = blocks[3].length() - String.valueOf(z).length() - 4;
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(z);
filename.append(".tif");
tiffs.add(filename.toString());
filename.delete(0, filename.length());
}
}
}
tiffReader.setId((String) tiffs.get(0));
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = tiffs.size() / getSizeC();
core[0].sizeX = tiffReader.getSizeX();
core[0].sizeY = tiffReader.getSizeY();
core[0].dimensionOrder = "XYZCT";
core[0].pixelType = tiffReader.getPixelType();
core[0].rgb = tiffReader.isRGB();
core[0].interleaved = false;
core[0].littleEndian = tiffReader.isLittleEndian();
core[0].imageCount = getSizeZ() * getSizeC() * getSizeT();
core[0].indexed = false;
core[0].falseColor = false;
core[0].metadataComplete = true;
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this, true);
store.setImageName("", 0);
store.setImageDescription(comment, 0);
if (time != null) {
SimpleDateFormat parser =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
long stamp = parser.parse(time).getTime();
store.setImageCreationDate(
DataTools.convertDate(stamp, DataTools.UNIX), 0);
}
catch (ParseException e) {
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
else MetadataTools.setDefaultCreationDate(store, id, 0);
// link Instrument and Image
store.setInstrumentID("Instrument:0", 0);
store.setImageInstrumentRef("Instrument:0", 0);
for (int i=0; i<channels.length; i++) {
store.setLogicalChannelName(channels[i], 0, i);
}
store.setDimensionsPhysicalSizeX(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeY(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeZ(sliceThickness, 0, 0);
for (int i=0; i<getImageCount(); i++) {
store.setPlaneTimingExposureTime(exposureTime, 0, 0, i);
if (i < timestamps.length) {
store.setPlaneTimingDeltaT(timestamps[i], 0, 0, i);
}
}
for (int i=0; i<channels.length; i++) {
store.setDetectorSettingsBinning(binning, 0, i);
store.setDetectorSettingsGain(new Float(gain), 0, i);
- store.setDetectorSettingsVoltage((Float) voltage.get(i), 0, i);
+ if (i < voltage.size()) {
+ store.setDetectorSettingsVoltage((Float) voltage.get(i), 0, i);
+ }
store.setDetectorSettingsDetector(detectorID, 0, i);
}
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(detectorModel, 0, 0);
store.setDetectorManufacturer(detectorManufacturer, 0, 0);
store.setDetectorType(cameraMode, 0, 0);
store.setImagingEnvironmentTemperature(new Float(temperature), 0);
}
}
| true | true | public void initFile(String id) throws FormatException, IOException {
super.initFile(id);
tiffReader = new MinimalTiffReader();
status("Reading metadata file");
// find metadata.txt
Location file = new Location(currentId).getAbsoluteFile();
metadataFile = file.exists() ? new Location(file.getParentFile(),
METADATA).getAbsolutePath() : METADATA;
in = new RandomAccessStream(metadataFile);
String parent = file.exists() ?
file.getParentFile().getAbsolutePath() + File.separator : "";
// usually a small file, so we can afford to read it into memory
byte[] meta = new byte[(int) in.length()];
in.read(meta);
String s = new String(meta);
meta = null;
status("Finding image file names");
// find the name of a TIFF file
String baseTiff = null;
tiffs = new Vector();
int pos = 0;
while (true) {
pos = s.indexOf("FileName", pos);
if (pos == -1 || pos >= in.length()) break;
String name = s.substring(s.indexOf(":", pos), s.indexOf(",", pos));
baseTiff = parent + name.substring(3, name.length() - 1);
pos++;
}
// now parse the rest of the metadata
// metadata.txt looks something like this:
//
// {
// "Section Name": {
// "Key": "Value",
// "Array key": [
// first array value, second array value
// ]
// }
//
// }
status("Populating metadata");
Vector stamps = new Vector();
Vector voltage = new Vector();
StringTokenizer st = new StringTokenizer(s, "\n");
int[] slice = new int[3];
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
boolean open = token.indexOf("[") != -1;
boolean closed = token.indexOf("]") != -1;
if (open || (!open && !closed && !token.equals("{") &&
!token.startsWith("}")))
{
int quote = token.indexOf("\"") + 1;
String key = token.substring(quote, token.indexOf("\"", quote));
String value = null;
if (!open && !closed) {
value = token.substring(token.indexOf(":") + 1);
}
else if (!closed){
StringBuffer valueBuffer = new StringBuffer();
while (!closed) {
token = st.nextToken();
closed = token.indexOf("]") != -1;
valueBuffer.append(token);
}
value = valueBuffer.toString();
value = value.replaceAll("\n", "");
}
int startIndex = value.indexOf("[");
int endIndex = value.indexOf("]");
if (endIndex == -1) endIndex = value.length();
value = value.substring(startIndex + 1, endIndex).trim();
value = value.substring(0, value.length() - 1);
value = value.replaceAll("\"", "");
if (value.endsWith(",")) value = value.substring(0, value.length() - 1);
addMeta(key, value);
if (key.equals("Channels")) core[0].sizeC = Integer.parseInt(value);
else if (key.equals("ChNames")) {
StringTokenizer t = new StringTokenizer(value, ",");
int nTokens = t.countTokens();
channels = new String[nTokens];
for (int q=0; q<nTokens; q++) {
channels[q] = t.nextToken().replaceAll("\"", "").trim();
}
}
else if (key.equals("Frames")) {
core[0].sizeT = Integer.parseInt(value);
}
else if (key.equals("Slices")) {
core[0].sizeZ = Integer.parseInt(value);
}
else if (key.equals("PixelSize_um")) {
pixelSize = new Float(value);
}
else if (key.equals("z-step_um")) {
sliceThickness = new Float(value);
}
else if (key.equals("Time")) time = value;
else if (key.equals("Comment")) comment = value;
}
if (token.startsWith("\"FrameKey")) {
int dash = token.indexOf("-") + 1;
int nextDash = token.indexOf("-", dash);
slice[2] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
nextDash = token.indexOf("-", dash);
slice[1] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
slice[0] = Integer.parseInt(token.substring(dash,
token.indexOf("\"", dash)));
token = st.nextToken().trim();
String key = "", value = "";
while (!token.startsWith("}")) {
int colon = token.indexOf(":");
key = token.substring(1, colon).trim();
value = token.substring(colon + 1, token.length() - 1).trim();
key = key.replaceAll("\"", "");
value = value.replaceAll("\"", "");
addMeta(key, value);
if (key.equals("Exposure-ms")) {
float t = Float.parseFloat(value);
exposureTime = new Float(t / 1000);
}
else if (key.equals("ElapsedTime-ms")) {
float t = Float.parseFloat(value);
stamps.add(new Float(t / 1000));
}
else if (key.equals("Core-Camera")) cameraRef = value;
else if (key.equals(cameraRef + "-Binning")) {
binning = value;
}
else if (key.equals(cameraRef + "-CameraID")) detectorID = value;
else if (key.equals(cameraRef + "-CameraName")) detectorModel = value;
else if (key.equals(cameraRef + "-Gain")) {
gain = Integer.parseInt(value);
}
else if (key.equals(cameraRef + "-Name")) {
detectorManufacturer = value;
}
else if (key.equals(cameraRef + "-Temperature")) {
temperature = Float.parseFloat(value);
}
else if (key.equals(cameraRef + "-CCDMode")) {
cameraMode = value;
}
else if (key.startsWith("DAC-") && key.endsWith("-Volts")) {
voltage.add(new Float(value));
}
token = st.nextToken().trim();
}
}
}
timestamps = (Float[]) stamps.toArray(new Float[0]);
Arrays.sort(timestamps);
// build list of TIFF files
String prefix = "";
if (baseTiff.indexOf(File.separator) != -1) {
prefix = baseTiff.substring(0, baseTiff.lastIndexOf(File.separator) + 1);
baseTiff = baseTiff.substring(baseTiff.lastIndexOf(File.separator) + 1);
}
String[] blocks = baseTiff.split("_");
StringBuffer filename = new StringBuffer();
for (int t=0; t<getSizeT(); t++) {
for (int c=0; c<getSizeC(); c++) {
for (int z=0; z<getSizeZ(); z++) {
// file names are of format:
// img_<T>_<channel name>_<T>.tif
filename.append(prefix);
filename.append(blocks[0]);
filename.append("_");
int zeros = blocks[1].length() - String.valueOf(t).length();
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(t);
filename.append("_");
filename.append(channels[c]);
filename.append("_");
zeros = blocks[3].length() - String.valueOf(z).length() - 4;
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(z);
filename.append(".tif");
tiffs.add(filename.toString());
filename.delete(0, filename.length());
}
}
}
tiffReader.setId((String) tiffs.get(0));
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = tiffs.size() / getSizeC();
core[0].sizeX = tiffReader.getSizeX();
core[0].sizeY = tiffReader.getSizeY();
core[0].dimensionOrder = "XYZCT";
core[0].pixelType = tiffReader.getPixelType();
core[0].rgb = tiffReader.isRGB();
core[0].interleaved = false;
core[0].littleEndian = tiffReader.isLittleEndian();
core[0].imageCount = getSizeZ() * getSizeC() * getSizeT();
core[0].indexed = false;
core[0].falseColor = false;
core[0].metadataComplete = true;
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this, true);
store.setImageName("", 0);
store.setImageDescription(comment, 0);
if (time != null) {
SimpleDateFormat parser =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
long stamp = parser.parse(time).getTime();
store.setImageCreationDate(
DataTools.convertDate(stamp, DataTools.UNIX), 0);
}
catch (ParseException e) {
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
else MetadataTools.setDefaultCreationDate(store, id, 0);
// link Instrument and Image
store.setInstrumentID("Instrument:0", 0);
store.setImageInstrumentRef("Instrument:0", 0);
for (int i=0; i<channels.length; i++) {
store.setLogicalChannelName(channels[i], 0, i);
}
store.setDimensionsPhysicalSizeX(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeY(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeZ(sliceThickness, 0, 0);
for (int i=0; i<getImageCount(); i++) {
store.setPlaneTimingExposureTime(exposureTime, 0, 0, i);
if (i < timestamps.length) {
store.setPlaneTimingDeltaT(timestamps[i], 0, 0, i);
}
}
for (int i=0; i<channels.length; i++) {
store.setDetectorSettingsBinning(binning, 0, i);
store.setDetectorSettingsGain(new Float(gain), 0, i);
store.setDetectorSettingsVoltage((Float) voltage.get(i), 0, i);
store.setDetectorSettingsDetector(detectorID, 0, i);
}
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(detectorModel, 0, 0);
store.setDetectorManufacturer(detectorManufacturer, 0, 0);
store.setDetectorType(cameraMode, 0, 0);
store.setImagingEnvironmentTemperature(new Float(temperature), 0);
}
| public void initFile(String id) throws FormatException, IOException {
super.initFile(id);
tiffReader = new MinimalTiffReader();
status("Reading metadata file");
// find metadata.txt
Location file = new Location(currentId).getAbsoluteFile();
metadataFile = file.exists() ? new Location(file.getParentFile(),
METADATA).getAbsolutePath() : METADATA;
in = new RandomAccessStream(metadataFile);
String parent = file.exists() ?
file.getParentFile().getAbsolutePath() + File.separator : "";
// usually a small file, so we can afford to read it into memory
byte[] meta = new byte[(int) in.length()];
in.read(meta);
String s = new String(meta);
meta = null;
status("Finding image file names");
// find the name of a TIFF file
String baseTiff = null;
tiffs = new Vector();
int pos = 0;
while (true) {
pos = s.indexOf("FileName", pos);
if (pos == -1 || pos >= in.length()) break;
String name = s.substring(s.indexOf(":", pos), s.indexOf(",", pos));
baseTiff = parent + name.substring(3, name.length() - 1);
pos++;
}
// now parse the rest of the metadata
// metadata.txt looks something like this:
//
// {
// "Section Name": {
// "Key": "Value",
// "Array key": [
// first array value, second array value
// ]
// }
//
// }
status("Populating metadata");
Vector stamps = new Vector();
Vector voltage = new Vector();
StringTokenizer st = new StringTokenizer(s, "\n");
int[] slice = new int[3];
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
boolean open = token.indexOf("[") != -1;
boolean closed = token.indexOf("]") != -1;
if (open || (!open && !closed && !token.equals("{") &&
!token.startsWith("}")))
{
int quote = token.indexOf("\"") + 1;
String key = token.substring(quote, token.indexOf("\"", quote));
String value = null;
if (!open && !closed) {
value = token.substring(token.indexOf(":") + 1);
}
else if (!closed){
StringBuffer valueBuffer = new StringBuffer();
while (!closed) {
token = st.nextToken();
closed = token.indexOf("]") != -1;
valueBuffer.append(token);
}
value = valueBuffer.toString();
value = value.replaceAll("\n", "");
}
int startIndex = value.indexOf("[");
int endIndex = value.indexOf("]");
if (endIndex == -1) endIndex = value.length();
value = value.substring(startIndex + 1, endIndex).trim();
value = value.substring(0, value.length() - 1);
value = value.replaceAll("\"", "");
if (value.endsWith(",")) value = value.substring(0, value.length() - 1);
addMeta(key, value);
if (key.equals("Channels")) core[0].sizeC = Integer.parseInt(value);
else if (key.equals("ChNames")) {
StringTokenizer t = new StringTokenizer(value, ",");
int nTokens = t.countTokens();
channels = new String[nTokens];
for (int q=0; q<nTokens; q++) {
channels[q] = t.nextToken().replaceAll("\"", "").trim();
}
}
else if (key.equals("Frames")) {
core[0].sizeT = Integer.parseInt(value);
}
else if (key.equals("Slices")) {
core[0].sizeZ = Integer.parseInt(value);
}
else if (key.equals("PixelSize_um")) {
pixelSize = new Float(value);
}
else if (key.equals("z-step_um")) {
sliceThickness = new Float(value);
}
else if (key.equals("Time")) time = value;
else if (key.equals("Comment")) comment = value;
}
if (token.startsWith("\"FrameKey")) {
int dash = token.indexOf("-") + 1;
int nextDash = token.indexOf("-", dash);
slice[2] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
nextDash = token.indexOf("-", dash);
slice[1] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
slice[0] = Integer.parseInt(token.substring(dash,
token.indexOf("\"", dash)));
token = st.nextToken().trim();
String key = "", value = "";
while (!token.startsWith("}")) {
int colon = token.indexOf(":");
key = token.substring(1, colon).trim();
value = token.substring(colon + 1, token.length() - 1).trim();
key = key.replaceAll("\"", "");
value = value.replaceAll("\"", "");
addMeta(key, value);
if (key.equals("Exposure-ms")) {
float t = Float.parseFloat(value);
exposureTime = new Float(t / 1000);
}
else if (key.equals("ElapsedTime-ms")) {
float t = Float.parseFloat(value);
stamps.add(new Float(t / 1000));
}
else if (key.equals("Core-Camera")) cameraRef = value;
else if (key.equals(cameraRef + "-Binning")) {
binning = value;
}
else if (key.equals(cameraRef + "-CameraID")) detectorID = value;
else if (key.equals(cameraRef + "-CameraName")) detectorModel = value;
else if (key.equals(cameraRef + "-Gain")) {
gain = Integer.parseInt(value);
}
else if (key.equals(cameraRef + "-Name")) {
detectorManufacturer = value;
}
else if (key.equals(cameraRef + "-Temperature")) {
temperature = Float.parseFloat(value);
}
else if (key.equals(cameraRef + "-CCDMode")) {
cameraMode = value;
}
else if (key.startsWith("DAC-") && key.endsWith("-Volts")) {
voltage.add(new Float(value));
}
token = st.nextToken().trim();
}
}
}
timestamps = (Float[]) stamps.toArray(new Float[0]);
Arrays.sort(timestamps);
// build list of TIFF files
String prefix = "";
if (baseTiff.indexOf(File.separator) != -1) {
prefix = baseTiff.substring(0, baseTiff.lastIndexOf(File.separator) + 1);
baseTiff = baseTiff.substring(baseTiff.lastIndexOf(File.separator) + 1);
}
String[] blocks = baseTiff.split("_");
StringBuffer filename = new StringBuffer();
for (int t=0; t<getSizeT(); t++) {
for (int c=0; c<getSizeC(); c++) {
for (int z=0; z<getSizeZ(); z++) {
// file names are of format:
// img_<T>_<channel name>_<T>.tif
filename.append(prefix);
filename.append(blocks[0]);
filename.append("_");
int zeros = blocks[1].length() - String.valueOf(t).length();
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(t);
filename.append("_");
filename.append(channels[c]);
filename.append("_");
zeros = blocks[3].length() - String.valueOf(z).length() - 4;
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(z);
filename.append(".tif");
tiffs.add(filename.toString());
filename.delete(0, filename.length());
}
}
}
tiffReader.setId((String) tiffs.get(0));
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = tiffs.size() / getSizeC();
core[0].sizeX = tiffReader.getSizeX();
core[0].sizeY = tiffReader.getSizeY();
core[0].dimensionOrder = "XYZCT";
core[0].pixelType = tiffReader.getPixelType();
core[0].rgb = tiffReader.isRGB();
core[0].interleaved = false;
core[0].littleEndian = tiffReader.isLittleEndian();
core[0].imageCount = getSizeZ() * getSizeC() * getSizeT();
core[0].indexed = false;
core[0].falseColor = false;
core[0].metadataComplete = true;
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this, true);
store.setImageName("", 0);
store.setImageDescription(comment, 0);
if (time != null) {
SimpleDateFormat parser =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
long stamp = parser.parse(time).getTime();
store.setImageCreationDate(
DataTools.convertDate(stamp, DataTools.UNIX), 0);
}
catch (ParseException e) {
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
else MetadataTools.setDefaultCreationDate(store, id, 0);
// link Instrument and Image
store.setInstrumentID("Instrument:0", 0);
store.setImageInstrumentRef("Instrument:0", 0);
for (int i=0; i<channels.length; i++) {
store.setLogicalChannelName(channels[i], 0, i);
}
store.setDimensionsPhysicalSizeX(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeY(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeZ(sliceThickness, 0, 0);
for (int i=0; i<getImageCount(); i++) {
store.setPlaneTimingExposureTime(exposureTime, 0, 0, i);
if (i < timestamps.length) {
store.setPlaneTimingDeltaT(timestamps[i], 0, 0, i);
}
}
for (int i=0; i<channels.length; i++) {
store.setDetectorSettingsBinning(binning, 0, i);
store.setDetectorSettingsGain(new Float(gain), 0, i);
if (i < voltage.size()) {
store.setDetectorSettingsVoltage((Float) voltage.get(i), 0, i);
}
store.setDetectorSettingsDetector(detectorID, 0, i);
}
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(detectorModel, 0, 0);
store.setDetectorManufacturer(detectorManufacturer, 0, 0);
store.setDetectorType(cameraMode, 0, 0);
store.setImagingEnvironmentTemperature(new Float(temperature), 0);
}
|
diff --git a/src/main/org/openscience/jchempaint/application/JChemPaint.java b/src/main/org/openscience/jchempaint/application/JChemPaint.java
index 39bb807..6e76696 100644
--- a/src/main/org/openscience/jchempaint/application/JChemPaint.java
+++ b/src/main/org/openscience/jchempaint/application/JChemPaint.java
@@ -1,726 +1,729 @@
/*
* $RCSfile$
* $Author: egonw $
* $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $
* $Revision: 7634 $
*
* Copyright (C) 1997-2008 Stefan Kuhn
* Some portions Copyright (C) 2009 Konstantin Tokarev
*
* Contact: [email protected]
*
* This program 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.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openscience.jchempaint.application;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.vecmath.Point2d;
import javax.vecmath.Vector2d;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.openscience.cdk.ChemFile;
import org.openscience.cdk.ChemModel;
import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.Molecule;
import org.openscience.cdk.MoleculeSet;
import org.openscience.cdk.atomtype.CDKAtomTypeMatcher;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.geometry.GeometryTools;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IAtomType;
import org.openscience.cdk.interfaces.IChemFile;
import org.openscience.cdk.interfaces.IChemModel;
import org.openscience.cdk.interfaces.IChemObject;
import org.openscience.cdk.interfaces.IMolecule;
import org.openscience.cdk.interfaces.IMoleculeSet;
import org.openscience.cdk.interfaces.IPseudoAtom;
import org.openscience.cdk.interfaces.IReaction;
import org.openscience.cdk.interfaces.IReactionSet;
import org.openscience.cdk.io.CMLReader;
import org.openscience.cdk.io.ISimpleChemObjectReader;
import org.openscience.cdk.io.RGroupQueryReader;
import org.openscience.cdk.io.SMILESReader;
import org.openscience.cdk.isomorphism.matchers.IRGroupQuery;
import org.openscience.cdk.isomorphism.matchers.RGroupQuery;
import org.openscience.cdk.layout.StructureDiagramGenerator;
import org.openscience.cdk.layout.TemplateHandler;
import org.openscience.cdk.tools.CDKHydrogenAdder;
import org.openscience.cdk.tools.manipulator.ChemModelManipulator;
import org.openscience.cdk.tools.manipulator.ReactionSetManipulator;
import org.openscience.jchempaint.AbstractJChemPaintPanel;
import org.openscience.jchempaint.GT;
import org.openscience.jchempaint.JCPPropertyHandler;
import org.openscience.jchempaint.JChemPaintPanel;
import org.openscience.jchempaint.controller.ControllerHub;
import org.openscience.jchempaint.controller.undoredo.IUndoRedoFactory;
import org.openscience.jchempaint.controller.undoredo.IUndoRedoable;
import org.openscience.jchempaint.controller.undoredo.UndoRedoHandler;
import org.openscience.jchempaint.dialog.WaitDialog;
import org.openscience.jchempaint.inchi.StdInChIReader;
import org.openscience.jchempaint.io.FileHandler;
import org.openscience.jchempaint.rgroups.RGroupHandler;
public class JChemPaint {
public static int instancecounter = 1;
public static List<JFrame> frameList = new ArrayList<JFrame>();
public final static String GUI_APPLICATION="application";
@SuppressWarnings("static-access")
public static void main(String[] args) {
try {
String vers = System.getProperty("java.version");
String requiredJVM = "1.5.0";
Package self = Package.getPackage("org.openscience.jchempaint");
String version = GT._("Could not determine JCP version");
if (self != null)
version = JCPPropertyHandler.getInstance(true).getVersion();
if (vers.compareTo(requiredJVM) < 0) {
System.err.println(GT._("WARNING: JChemPaint {0} must be run with a Java VM version {1} or higher.", new String[]{version, requiredJVM}));
System.err.println(GT._("Your JVM version is {0}", vers));
System.exit(1);
}
Options options = new Options();
options.addOption("h", "help", false, GT._("gives this help page"));
options.addOption("v", "version", false, GT
._("gives JChemPaints version number"));
options.addOption("d", "debug", false,
"switches on various debug options");
options.addOption(OptionBuilder.withArgName("property=value")
.hasArg().withValueSeparator().withDescription(
GT._("supported options are given below")).create(
"D"));
CommandLine line = null;
try {
CommandLineParser parser = new PosixParser();
line = parser.parse(options, args);
} catch (UnrecognizedOptionException exception) {
System.err.println(exception.getMessage());
System.exit(-1);
} catch (ParseException exception) {
System.err.println("Unexpected exception: "
+ exception.toString());
}
if (line.hasOption("v")) {
System.out.println("JChemPaint v." + version + "\n");
System.exit(0);
}
if (line.hasOption("h")) {
System.out.println("JChemPaint v." + version + "\n");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("JChemPaint", options);
// now report on the -D options
System.out.println();
System.out
.println("The -D options are as follows (defaults in parathesis):");
System.out.println(" cdk.debugging [true|false] (false)");
System.out.println(" cdk.debug.stdout [true|false] (false)");
System.out.println(" user.language [ar|ca|cs|de|en|es|hu|nb|nl|pl|pt|ru|th] (en)");
System.out.println(" user.language [ar|ca|cs|de|hu|nb|nl|pl|pt_BR|ru|th] (EN)");
System.exit(0);
}
boolean debug = false;
if (line.hasOption("d")) {
debug = true;
}
// Set Look&Feel
Properties props = JCPPropertyHandler.getInstance(true).getJCPProperties();
try {
UIManager.setLookAndFeel(props.getProperty("LookAndFeelClass"));
} catch (Throwable e) {
String sys = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(sys);
props.setProperty("LookAndFeelClass", sys);
}
// Language
props.setProperty("General.language", System.getProperty("user.language", "en"));
// Process command line arguments
String modelFilename = "";
args = line.getArgs();
if (args.length > 0) {
modelFilename = args[0];
File file = new File(modelFilename);
if (!file.exists()) {
System.err.println(GT._("File does not exist") + ": "
+ modelFilename);
System.exit(-1);
}
showInstance(file, null, null, debug);
} else {
showEmptyInstance(debug);
}
} catch (Throwable t) {
System.err.println("uncaught exception: " + t);
t.printStackTrace(System.err);
}
}
public static void showEmptyInstance(boolean debug) {
IChemModel chemModel = emptyModel();
showInstance(chemModel, GT._("Untitled") + " "
+ (instancecounter++), debug);
}
public static IChemModel emptyModel() {
IChemModel chemModel = DefaultChemObjectBuilder.getInstance().newInstance(IChemModel.class);
chemModel.setMoleculeSet(chemModel.getBuilder().newInstance(IMoleculeSet.class));
chemModel.getMoleculeSet().addAtomContainer(
chemModel.getBuilder().newInstance(IMolecule.class));
return chemModel;
}
public static void showInstance(File inFile, String type,
AbstractJChemPaintPanel jcpPanel, boolean debug) {
try {
IChemModel chemModel = JChemPaint.readFromFile(inFile, type, jcpPanel);
String name = inFile.getName();
JChemPaintPanel p = JChemPaint.showInstance(chemModel, name, debug);
p.setCurrentWorkDirectory(inFile.getParentFile());
p.setLastOpenedFile(inFile);
p.setIsAlreadyAFile(inFile);
} catch (CDKException ex) {
JOptionPane.showMessageDialog(jcpPanel, ex.getMessage());
return;
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(jcpPanel, GT._("File does not exist")
+ ": " + inFile.getPath());
return;
}
}
public static JChemPaintPanel showInstance(IChemModel chemModel,
String title, boolean debug) {
JFrame f = new JFrame(title + " - JChemPaint");
chemModel.setID(title);
f.addWindowListener(new JChemPaintPanel.AppCloser());
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
JChemPaintPanel p = new JChemPaintPanel(chemModel, GUI_APPLICATION, debug, null, new ArrayList<String>());
p.updateStatusBar();
f.setPreferredSize(new Dimension(800, 494)); //1.618
f.add(p);
f.pack();
Point point = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getCenterPoint();
int w2 = (f.getWidth() / 2);
int h2 = (f.getHeight() / 2);
f.setLocation(point.x - w2, point.y - h2);
f.setVisible(true);
frameList.add(f);
return p;
}
public static IChemModel readFromFileReader(URL fileURL, String url,
String type, AbstractJChemPaintPanel panel) throws CDKException {
IChemModel chemModel = null;
WaitDialog.showDialog();
// InChI workaround - guessing for InChI results into an INChIReader
// (this does not work, we'd need an INChIPlainTextReader..)
// Instead here we use STDInChIReader, to be consistent throughout JCP
// using the nestedVm based classes.
try {
ISimpleChemObjectReader cor=null;
if(url.endsWith("txt")) {
chemModel = StdInChIReader.readInChI(fileURL);
}
else {
cor = FileHandler.createReader(fileURL, url,type);
chemModel = JChemPaint.getChemModelFromReader(cor,panel);
}
boolean avoidOverlap=true;
if (cor instanceof RGroupQueryReader)
avoidOverlap=false;
JChemPaint.cleanUpChemModel(chemModel, avoidOverlap, panel);
}
finally {
WaitDialog.hideDialog();
}
return chemModel;
}
/**
* Read an IChemModel from a given file.
* @param file
* @param type
* @param panel
* @return
* @throws CDKException
* @throws FileNotFoundException
*/
public static IChemModel readFromFile(File file, String type, AbstractJChemPaintPanel panel)
throws CDKException, FileNotFoundException {
String url = file.toURI().toString();
ISimpleChemObjectReader cor = null;
try {
cor = FileHandler.createReader(file.toURI().toURL(), url, type);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (cor instanceof CMLReader)
cor.setReader(new FileInputStream(file)); // hack
else
cor.setReader(new FileReader(file)); // hack
IChemModel chemModel = JChemPaint.getChemModelFromReader(cor,panel);
boolean avoidOverlap=true;
if (cor instanceof RGroupQueryReader)
avoidOverlap=false;
JChemPaint.cleanUpChemModel(chemModel, avoidOverlap, panel);
return chemModel;
}
/**
* Clean up chemical model ,removing duplicates empty molecules etc
* @param chemModel
* @param avoidOverlap
* @throws CDKException
*/
public static void cleanUpChemModel(IChemModel chemModel, boolean avoidOverlap, AbstractJChemPaintPanel panel)
throws CDKException {
JChemPaint.setReactionIDs(chemModel);
JChemPaint.replaceReferencesWithClones(chemModel);
// check the model is not completely empty
if (ChemModelManipulator.getBondCount(chemModel) == 0 &&
ChemModelManipulator.getAtomCount(chemModel) == 0) {
throw new CDKException(
"Structure does not have bonds or atoms. Cannot depict structure.");
}
JChemPaint.removeDuplicateMolecules(chemModel);
JChemPaint.checkCoordinates(chemModel);
JChemPaint.removeEmptyMolecules(chemModel);
if (avoidOverlap) {
try {
ControllerHub.avoidOverlap(chemModel);
} catch (Exception e) {
JOptionPane.showMessageDialog(panel, GT._("Structure could not be generated"));
throw new CDKException(
"Cannot depict structure");
}
}
//We update implicit Hs in any case
CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(chemModel.getBuilder());
for (IAtomContainer container :
ChemModelManipulator.getAllAtomContainers(chemModel)) {
for (IAtom atom : container.atoms()) {
if (!(atom instanceof IPseudoAtom)) {
try {
IAtomType type = matcher.findMatchingAtomType(
container, atom
);
if (type != null &&
type.getFormalNeighbourCount() != null) {
int connectedAtomCount = container.getConnectedAtomsCount(atom);
atom.setImplicitHydrogenCount(
type.getFormalNeighbourCount() - connectedAtomCount
);
}
} catch ( CDKException e ) {
e.printStackTrace();
}
}
}
}
}
/**
* Returns an IChemModel, using the reader provided (picked).
* @param cor
* @param panel
* @return
* @throws CDKException
*/
public static IChemModel getChemModelFromReader(ISimpleChemObjectReader cor,AbstractJChemPaintPanel panel)
throws CDKException {
panel.get2DHub().setRGroupHandler(null);
String error = null;
ChemModel chemModel = null;
IChemFile chemFile = null;
if (cor.accepts(IChemFile.class) && chemModel==null) {
// try to read a ChemFile
try {
chemFile = (IChemFile) cor.read((IChemObject) new ChemFile());
if (chemFile == null) {
error = "The object chemFile was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
throw new CDKException(error);
}
+ if (chemModel == null && chemFile != null) {
+ chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
+ }
if (cor.accepts(ChemModel.class) && chemModel==null) {
// try to read a ChemModel
try {
chemModel = (ChemModel) cor.read((IChemObject) new ChemModel());
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// Smiles reading
if (cor.accepts(MoleculeSet.class) && chemModel==null) {
// try to read a Molecule set
try {
IMoleculeSet som = (MoleculeSet) cor.read(new MoleculeSet());
chemModel = new ChemModel();
chemModel.setMoleculeSet(som);
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// MDLV3000 reading
if (cor.accepts(Molecule.class) && chemModel==null) {
// try to read a Molecule
IMolecule mol = (Molecule) cor.read(new Molecule());
if(mol!=null )
try{
IMoleculeSet newSet = new MoleculeSet();
newSet.addMolecule(mol);
chemModel = new ChemModel();
chemModel.setMoleculeSet(newSet);
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// RGroupQuery reading
if (cor.accepts(RGroupQuery.class) && chemModel==null) {
IRGroupQuery rgroupQuery = (RGroupQuery) cor.read(new RGroupQuery());
if(rgroupQuery!=null )
try{
chemModel = new ChemModel();
RGroupHandler rgHandler = new RGroupHandler(rgroupQuery);
panel.get2DHub().setRGroupHandler(rgHandler);
chemModel.setMoleculeSet(rgHandler.getMoleculeSet(chemModel));
rgHandler.layoutRgroup();
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
throw new CDKException(error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
//SmilesParser sets valencies, switch off by default.
if(cor instanceof SMILESReader){
IAtomContainer allinone = JChemPaintPanel.getAllAtomContainersInOne(chemModel);
for(int k=0;k<allinone.getAtomCount();k++){
allinone.getAtom(k).setValency(null);
}
}
return chemModel;
}
/**
* Inserts a molecule into the current set, usually from Combobox or Insert field, with possible
* shifting of the existing set.
* @param chemPaintPanel
* @param molecule
* @param generateCoordinates
* @param shiftPanel
* @throws CDKException
*/
public static void generateModel(AbstractJChemPaintPanel chemPaintPanel, IMolecule molecule, boolean generateCoordinates, boolean shiftPasted)
throws CDKException {
if (molecule == null) return;
IChemModel chemModel = chemPaintPanel.getChemModel();
IMoleculeSet moleculeSet = chemModel.getMoleculeSet();
if (moleculeSet == null) {
moleculeSet = new MoleculeSet();
}
// On copy & paste on top of an existing drawn structure, prevent the
// pasted section to be drawn exactly on top or to far away from the
// original by shifting it to a fixed position next to it.
if (shiftPasted) {
double maxXCurr = Double.NEGATIVE_INFINITY;
double minXPaste = Double.POSITIVE_INFINITY;
for (IAtomContainer atc : moleculeSet.atomContainers()) {
// Detect the right border of the current structure..
for (IAtom atom : atc.atoms()) {
if(atom.getPoint2d().x>maxXCurr)
maxXCurr = atom.getPoint2d().x;
}
// Detect the left border of the pasted structure..
for (IAtom atom : molecule.atoms()) {
if(atom.getPoint2d().x<minXPaste)
minXPaste = atom.getPoint2d().x;
}
}
if (maxXCurr != Double.NEGATIVE_INFINITY && minXPaste != Double.POSITIVE_INFINITY) {
// Shift the pasted structure to be nicely next to the existing one.
final int MARGIN=1;
final double SHIFT = maxXCurr - minXPaste;
for (IAtom atom : molecule.atoms()) {
atom.setPoint2d(new Point2d (atom.getPoint2d().x+MARGIN+SHIFT, atom.getPoint2d().y ));
}
}
}
if(generateCoordinates){
// now generate 2D coordinates
StructureDiagramGenerator sdg = new StructureDiagramGenerator();
sdg.setTemplateHandler(new TemplateHandler(moleculeSet.getBuilder()));
try {
sdg.setMolecule(molecule);
sdg.generateCoordinates(new Vector2d(0, 1));
molecule = sdg.getMolecule();
} catch (Exception exc) {
JOptionPane.showMessageDialog(chemPaintPanel, GT._("Structure could not be generated"));
throw new CDKException(
"Cannot depict structure");
}
}
if(moleculeSet.getAtomContainer(0).getAtomCount()==0)
moleculeSet.getAtomContainer(0).add(molecule);
else
moleculeSet.addAtomContainer(molecule);
IUndoRedoFactory undoRedoFactory= chemPaintPanel.get2DHub().getUndoRedoFactory();
UndoRedoHandler undoRedoHandler= chemPaintPanel.get2DHub().getUndoRedoHandler();
if (undoRedoFactory!=null) {
IUndoRedoable undoredo = undoRedoFactory.getAddAtomsAndBondsEdit(chemPaintPanel.get2DHub().getIChemModel(),
molecule, null, "Paste", chemPaintPanel.get2DHub());
undoRedoHandler.postEdit(undoredo);
}
chemPaintPanel.getChemModel().setMoleculeSet(moleculeSet);
chemPaintPanel.updateUndoRedoControls();
chemPaintPanel.get2DHub().updateView();
}
private static void setReactionIDs(IChemModel chemModel) {
// we give all reactions an ID, in case they have none
// IDs are needed for handling in JCP
IReactionSet reactionSet = chemModel.getReactionSet();
if (reactionSet != null) {
int i = 0;
for (IReaction reaction : reactionSet.reactions()) {
if (reaction.getID() == null)
reaction.setID("Reaction " + (++i));
}
}
}
private static void replaceReferencesWithClones(IChemModel chemModel)
throws CDKException {
// we make references in products/reactants clones, since same compounds
// in different reactions need separate layout (different positions etc)
if (chemModel.getReactionSet() != null) {
for (IReaction reaction : chemModel.getReactionSet().reactions()) {
int i = 0;
IMoleculeSet products = reaction.getProducts();
for (IAtomContainer product : products.atomContainers()) {
try {
products.replaceAtomContainer(i,
(IAtomContainer) product.clone());
} catch (CloneNotSupportedException e) {
}
i++;
}
i = 0;
IMoleculeSet reactants = reaction.getReactants();
for (IAtomContainer reactant : reactants.atomContainers()) {
try {
reactants.replaceAtomContainer(i,
(IAtomContainer) reactant.clone());
} catch (CloneNotSupportedException e) {
}
i++;
}
}
}
}
private static void removeDuplicateMolecules(IChemModel chemModel) {
// we remove molecules which are in MoleculeSet as well as in a reaction
IReactionSet reactionSet = chemModel.getReactionSet();
IMoleculeSet moleculeSet = chemModel.getMoleculeSet();
if (reactionSet != null && moleculeSet != null) {
List<IAtomContainer> aclist = ReactionSetManipulator
.getAllAtomContainers(reactionSet);
for (int i = moleculeSet.getAtomContainerCount() - 1; i >= 0; i--) {
for (int k = 0; k < aclist.size(); k++) {
String label = moleculeSet.getAtomContainer(i).getID();
if (aclist.get(k).getID().equals(label)) {
chemModel.getMoleculeSet().removeAtomContainer(i);
break;
}
}
}
}
}
private static void removeEmptyMolecules(IChemModel chemModel) {
IMoleculeSet moleculeSet = chemModel.getMoleculeSet();
if (moleculeSet != null && moleculeSet.getAtomContainerCount() == 0) {
chemModel.setMoleculeSet(null);
}
}
private static void checkCoordinates(IChemModel chemModel)
throws CDKException {
for (IAtomContainer next : ChemModelManipulator
.getAllAtomContainers(chemModel)) {
if (GeometryTools.has2DCoordinatesNew(next) != 2) {
String error = GT._("Not all atoms have 2D coordinates."
+ " JCP can only show full 2D specified structures."
+ " Shall we lay out the structure?");
int answer = JOptionPane.showConfirmDialog(null, error,
"No 2D coordinates", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.NO_OPTION) {
throw new CDKException(GT
._("Cannot display without 2D coordinates"));
} else {
// CreateCoordinatesForFileDialog frame =
// new CreateCoordinatesForFileDialog(chemModel);
// frame.pack();
// frame.show();
WaitDialog.showDialog();
List<IAtomContainer> acs=ChemModelManipulator.getAllAtomContainers(chemModel);
generate2dCoordinates(acs);
WaitDialog.hideDialog();
return;
}
}
}
/*
* Add implicit hydrogens (in ControllerParameters,
* autoUpdateImplicitHydrogens is true by default, so we need to do that
* anyway)
*/
CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(chemModel
.getBuilder());
for (IAtomContainer molecule : ChemModelManipulator
.getAllAtomContainers(chemModel)) {
if (molecule != null) {
try {
hAdder.addImplicitHydrogens(molecule);
} catch (CDKException e) {
// do nothing
}
}
}
}
/**
* Helper method to generate 2d coordinates when JChempaint loads a molecule
* without 2D coordinates. Typically happens for SMILES strings.
*
* @param molecules
* @throws Exception
*/
private static void generate2dCoordinates(List<IAtomContainer> molecules) {
StructureDiagramGenerator sdg = new StructureDiagramGenerator();
for (int atIdx = 0; atIdx < molecules.size(); atIdx++) {
IAtomContainer mol = molecules.get(atIdx);
sdg.setMolecule(mol.getBuilder().newInstance(IMolecule.class,mol));
try {
sdg.generateCoordinates();
} catch (Exception e) {
e.printStackTrace();
}
IAtomContainer ac = sdg.getMolecule();
for(int i=0;i<ac.getAtomCount();i++){
mol.getAtom(i).setPoint2d(ac.getAtom(i).getPoint2d());
}
}
}
}
| true | true | public static IChemModel getChemModelFromReader(ISimpleChemObjectReader cor,AbstractJChemPaintPanel panel)
throws CDKException {
panel.get2DHub().setRGroupHandler(null);
String error = null;
ChemModel chemModel = null;
IChemFile chemFile = null;
if (cor.accepts(IChemFile.class) && chemModel==null) {
// try to read a ChemFile
try {
chemFile = (IChemFile) cor.read((IChemObject) new ChemFile());
if (chemFile == null) {
error = "The object chemFile was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
throw new CDKException(error);
}
if (cor.accepts(ChemModel.class) && chemModel==null) {
// try to read a ChemModel
try {
chemModel = (ChemModel) cor.read((IChemObject) new ChemModel());
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// Smiles reading
if (cor.accepts(MoleculeSet.class) && chemModel==null) {
// try to read a Molecule set
try {
IMoleculeSet som = (MoleculeSet) cor.read(new MoleculeSet());
chemModel = new ChemModel();
chemModel.setMoleculeSet(som);
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// MDLV3000 reading
if (cor.accepts(Molecule.class) && chemModel==null) {
// try to read a Molecule
IMolecule mol = (Molecule) cor.read(new Molecule());
if(mol!=null )
try{
IMoleculeSet newSet = new MoleculeSet();
newSet.addMolecule(mol);
chemModel = new ChemModel();
chemModel.setMoleculeSet(newSet);
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// RGroupQuery reading
if (cor.accepts(RGroupQuery.class) && chemModel==null) {
IRGroupQuery rgroupQuery = (RGroupQuery) cor.read(new RGroupQuery());
if(rgroupQuery!=null )
try{
chemModel = new ChemModel();
RGroupHandler rgHandler = new RGroupHandler(rgroupQuery);
panel.get2DHub().setRGroupHandler(rgHandler);
chemModel.setMoleculeSet(rgHandler.getMoleculeSet(chemModel));
rgHandler.layoutRgroup();
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
throw new CDKException(error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
//SmilesParser sets valencies, switch off by default.
if(cor instanceof SMILESReader){
IAtomContainer allinone = JChemPaintPanel.getAllAtomContainersInOne(chemModel);
for(int k=0;k<allinone.getAtomCount();k++){
allinone.getAtom(k).setValency(null);
}
}
return chemModel;
}
| public static IChemModel getChemModelFromReader(ISimpleChemObjectReader cor,AbstractJChemPaintPanel panel)
throws CDKException {
panel.get2DHub().setRGroupHandler(null);
String error = null;
ChemModel chemModel = null;
IChemFile chemFile = null;
if (cor.accepts(IChemFile.class) && chemModel==null) {
// try to read a ChemFile
try {
chemFile = (IChemFile) cor.read((IChemObject) new ChemFile());
if (chemFile == null) {
error = "The object chemFile was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
throw new CDKException(error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
if (cor.accepts(ChemModel.class) && chemModel==null) {
// try to read a ChemModel
try {
chemModel = (ChemModel) cor.read((IChemObject) new ChemModel());
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// Smiles reading
if (cor.accepts(MoleculeSet.class) && chemModel==null) {
// try to read a Molecule set
try {
IMoleculeSet som = (MoleculeSet) cor.read(new MoleculeSet());
chemModel = new ChemModel();
chemModel.setMoleculeSet(som);
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// MDLV3000 reading
if (cor.accepts(Molecule.class) && chemModel==null) {
// try to read a Molecule
IMolecule mol = (Molecule) cor.read(new Molecule());
if(mol!=null )
try{
IMoleculeSet newSet = new MoleculeSet();
newSet.addMolecule(mol);
chemModel = new ChemModel();
chemModel.setMoleculeSet(newSet);
if (chemModel == null) {
error = "The object chemModel was empty unexpectedly!";
}
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
// RGroupQuery reading
if (cor.accepts(RGroupQuery.class) && chemModel==null) {
IRGroupQuery rgroupQuery = (RGroupQuery) cor.read(new RGroupQuery());
if(rgroupQuery!=null )
try{
chemModel = new ChemModel();
RGroupHandler rgHandler = new RGroupHandler(rgroupQuery);
panel.get2DHub().setRGroupHandler(rgHandler);
chemModel.setMoleculeSet(rgHandler.getMoleculeSet(chemModel));
rgHandler.layoutRgroup();
} catch (Exception exception) {
error = "Error while reading file: " + exception.getMessage();
exception.printStackTrace();
}
}
if (error != null) {
throw new CDKException(error);
}
if (chemModel == null && chemFile != null) {
chemModel = (ChemModel) chemFile.getChemSequence(0).getChemModel(0);
}
//SmilesParser sets valencies, switch off by default.
if(cor instanceof SMILESReader){
IAtomContainer allinone = JChemPaintPanel.getAllAtomContainersInOne(chemModel);
for(int k=0;k<allinone.getAtomCount();k++){
allinone.getAtom(k).setValency(null);
}
}
return chemModel;
}
|
diff --git a/src/java/org/grails/jaxrs/provider/XMLWriter.java b/src/java/org/grails/jaxrs/provider/XMLWriter.java
index 52dce51..0a087ae 100644
--- a/src/java/org/grails/jaxrs/provider/XMLWriter.java
+++ b/src/java/org/grails/jaxrs/provider/XMLWriter.java
@@ -1,102 +1,101 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.grails.jaxrs.provider;
import grails.converters.XML;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import org.codehaus.groovy.grails.web.converters.configuration.ConvertersConfigurationHolder;
import org.grails.jaxrs.support.MessageBodyWriterSupport;
/**
* Provider for Grails' {@link XML} converter class.
*
* Message body writer that supports {@link XML} response entities. For example,
* to create an XML representation from a list of Grails domain objects:
*
* <pre>
* @Path('/notes')
* @Produces('text/xml') // or 'application/xml'
* class NotesResource {
*
* @GET
* XML findNotes() {
* Note.findAll() as XML
* }
*
* }
* </pre>
*
* Alternatively, one could write
*
* <pre>
* @Path('/notes')
* @Produces('text/xml') // or 'application/xml'
* class NotesResource {
*
* @GET
* Response findNotes() {
* Response.ok(Note.findAll() as XML).build()
* }
*
* }
* </pre>
*
* @author Martin Krasser
*/
@Provider
@Produces({"text/xml", "application/xml"})
public class XMLWriter extends MessageBodyWriterSupport<XML> {
public static final String DEFAULT_CHARSET = "UTF-8";
/**
* Renders the <code>xml</code> object to the response's
* <code>entityStream</code> using the encoding set by the Grails
* application.
*
* @param xml
* XML object.
* @param httpHeaders
* HTTP headers
* @param entityStream
* XML response entity stream.
*/
@Override
protected void writeTo(XML xml, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
String charset = ConvertersConfigurationHolder.getConverterConfiguration(XML.class).getEncoding();
Writer writer = null;
if (charset == null) {
writer = new OutputStreamWriter(entityStream, DEFAULT_CHARSET);
} else {
writer = new OutputStreamWriter(entityStream, charset);
}
xml.render(writer);
- writer.flush();
}
}
| true | true | protected void writeTo(XML xml, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
String charset = ConvertersConfigurationHolder.getConverterConfiguration(XML.class).getEncoding();
Writer writer = null;
if (charset == null) {
writer = new OutputStreamWriter(entityStream, DEFAULT_CHARSET);
} else {
writer = new OutputStreamWriter(entityStream, charset);
}
xml.render(writer);
writer.flush();
}
| protected void writeTo(XML xml, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
String charset = ConvertersConfigurationHolder.getConverterConfiguration(XML.class).getEncoding();
Writer writer = null;
if (charset == null) {
writer = new OutputStreamWriter(entityStream, DEFAULT_CHARSET);
} else {
writer = new OutputStreamWriter(entityStream, charset);
}
xml.render(writer);
}
|
diff --git a/Npr/src/org/npr/android/news/ListenActivity.java b/Npr/src/org/npr/android/news/ListenActivity.java
index a94c48d..7c99a78 100644
--- a/Npr/src/org/npr/android/news/ListenActivity.java
+++ b/Npr/src/org/npr/android/news/ListenActivity.java
@@ -1,606 +1,607 @@
// Copyright 2009 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.npr.android.news;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import org.npr.android.util.M3uParser;
import org.npr.android.util.PlaylistParser;
import org.npr.android.util.PlaylistProvider;
import org.npr.android.util.PlsParser;
import org.npr.android.util.PlaylistProvider.Items;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ListenActivity extends Activity implements OnClickListener,
OnBufferingUpdateListener, OnCompletionListener, OnErrorListener,
OnInfoListener, OnSeekBarChangeListener, OnPreparedListener,
OnDrawerOpenListener, OnDrawerCloseListener {
private static final String LOG_TAG = ListenActivity.class.toString();
public static final String EXTRA_CONTENT_URL = "extra_content_url";
public static final String EXTRA_CONTENT_TITLE = "extra_content_title";
public static final String EXTRA_CONTENT_ID = "extra_content_id";
public static final String EXTRA_ENQUEUE = "extra_enqueue";
public static final String EXTRA_PLAY_IMMEDIATELY = "extra_play_immediately";
public static final String EXTRA_STREAM = "extra_stream";
private PlaylistEntry current = null;
private ImageButton streamButton;
private ImageButton playButton;
private SeekBar progressBar;
private TextView infoText;
private TextView lengthText;
private SlidingDrawer drawer;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
setPlayButton();
break;
case 1:
updateProgress();
break;
case 2:
enableProgress(true);
break;
case 3:
enableProgress(false);
break;
}
}
};
private Thread updateProgressThread;
private BroadcastReceiver receiver = new ListenBroadcastReceiver();
private ServiceConnection conn;
private PlaybackService player;
private boolean isPausedInCall = false;
private TelephonyManager telephonyManager = null;
private PhoneStateListener listener = null;
// amount of time to rewind playback when resuming after call
private final static int RESUME_REWIND_TIME = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listen);
drawer = (SlidingDrawer) findViewById(R.id.drawer);
drawer.setOnDrawerOpenListener(this);
drawer.setOnDrawerCloseListener(this);
playButton = (ImageButton) findViewById(R.id.StreamPlayButton);
playButton.setEnabled(false);
playButton.setOnClickListener(this);
streamButton = (ImageButton) findViewById(R.id.StreamShareButton);
streamButton.setOnClickListener(this);
streamButton.setEnabled(false);
Button playlistButton = (Button) findViewById(R.id.StreamPlaylistButton);
playlistButton.setOnClickListener(this);
progressBar = (SeekBar) findViewById(R.id.StreamProgressBar);
progressBar.setMax(100);
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(false);
infoText = (TextView) findViewById(R.id.StreamTextView);
lengthText = (TextView) findViewById(R.id.StreamLengthText);
lengthText.setText("");
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
// Create a PhoneStateListener to watch for offhook and idle events
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
- // phone going offhook, pause the player
+ case TelephonyManager.CALL_STATE_RINGING:
+ // phone going offhook or ringing, pause the player
if (player != null && player.isPlaying()) {
player.pause();
isPausedInCall = true;
setPlayButton();
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// phone idle. rewind a couple of seconds and start playing
if (isPausedInCall && player != null) {
int resumePosition = player.getPosition() - RESUME_REWIND_TIME;
if (resumePosition < 0) {
resumePosition = 0;
}
player.seekTo(resumePosition);
player.play();
setPlayButton();
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
registerReceiver(receiver, new IntentFilter(this.getClass().getName()));
Intent serviceIntent = new Intent(this, PlaybackService.class);
conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
player = ((PlaybackService.ListenBinder) service).getService();
onBindComplete((PlaybackService.ListenBinder) service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.w(LOG_TAG, "DISCONNECT");
player = null;
}
};
if (!PlaybackService.isRunning) {
getApplicationContext().startService(serviceIntent);
}
getApplicationContext().bindService(serviceIntent, conn, 1);
}
private void onBindComplete(PlaybackService.ListenBinder binder) {
binder.setListener(this);
if (player.isPlaying()) {
current = player.getCurrentEntry();
setPlayButton();
play();
startUpdateThread();
}
}
private void play() {
resetUI();
new Thread(new Runnable() {
public void run() {
startListening();
}
}).start();
Log.d(LOG_TAG, "started playing");
}
private void resetUI() {
Log.d(LOG_TAG, "resetUI()");
infoText.setText(current.title);
infoText.setTypeface(infoText.getTypeface(), Typeface.NORMAL);
progressBar.setProgress(0);
progressBar.setSecondaryProgress(0);
streamButton.setEnabled(true);
}
private void enableProgress(boolean enabled) {
progressBar.setEnabled(enabled);
}
private void togglePlay() {
// cancel pause while in a phone call if user manually starts playing
if (isPausedInCall) {
isPausedInCall = false;
}
if (player.isPlaying()) {
player.pause();
} else {
player.play();
}
setPlayButton();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StreamPlayButton:
togglePlay();
break;
case R.id.StreamPlaylistButton:
startActivity(new Intent(this, PlaylistActivity.class));
break;
case R.id.StreamShareButton:
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, current.title);
shareIntent.putExtra(Intent.EXTRA_TEXT, String.format("%s: %s",
current.title, current.url));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent,
getString(R.string.msg_share_story)));
break;
}
}
private void setPlayButton() {
playButton.setEnabled(true);
if (player.isPlaying()) {
playButton.setImageResource(android.R.drawable.ic_media_pause);
} else {
playButton.setImageResource(android.R.drawable.ic_media_play);
}
}
public void updateProgress() {
try {
if (player.isPlaying()) {
if (player.getDuration() > 0) {
int progress = 100 * player.getPosition() / player.getDuration();
progressBar.setProgress(progress);
}
updatePlayTime();
}
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "update progress", e);
}
}
private void listen(final String url, boolean stream)
throws IllegalArgumentException, IllegalStateException, IOException {
Log.d(LOG_TAG, "listening to " + url);
if (updateProgressThread != null && updateProgressThread.isAlive()) {
updateProgressThread.interrupt();
try {
updateProgressThread.join();
} catch (InterruptedException e) {
Log.e(LOG_TAG, "error in updateProgressthread", e);
}
}
player.stop();
player.listen(url, stream);
handler.sendEmptyMessage(stream ? 3 : 2);
}
private void startListening() {
String url = current.url;
try {
if (url == null || url.equals("")) {
Log.d(LOG_TAG, "no url");
// Do nothing.
} else if (isPlaylist(url)) {
downloadPlaylistAndPlay();
} else {
listen(url, current.isStream);
}
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
} catch (IOException e) {
Log.e(LOG_TAG, "", e);
}
Log.d(LOG_TAG, "playing commenced");
}
private boolean isPlaylist(String url) {
return url.indexOf("m3u") > -1 || url.indexOf("pls") > -1;
}
private void downloadPlaylistAndPlay() throws MalformedURLException,
IOException {
String url = current.url;
Log.d(LOG_TAG, "downloading " + url);
URLConnection cn = new URL(url).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log
.e(getClass().getName(),
"Unable to create InputStream for url: + url");
}
File downloadingMediaFile = new File(getCacheDir(), "playlist_data");
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
int numread;
while ((numread = stream.read(buf)) > 0) {
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
}
stream.close();
out.close();
PlaylistParser parser;
if (url.indexOf("m3u") > -1) {
parser = new M3uParser(downloadingMediaFile);
} else if (url.indexOf("pls") > -1) {
parser = new PlsParser(downloadingMediaFile);
} else {
return;
}
String mp3Url = parser.getNextUrl();
listen(mp3Url, current.isStream);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (telephonyManager != null && listener != null) {
telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
}
unregisterReceiver(receiver);
getApplicationContext().unbindService(conn);
}
class ListenBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.w(LOG_TAG, "broadcast received");
String url = intent.getStringExtra(EXTRA_CONTENT_URL);
String title = intent.getStringExtra(EXTRA_CONTENT_TITLE);
long id = intent.getLongExtra(EXTRA_CONTENT_ID, -1);
boolean enqueue = intent.getBooleanExtra(EXTRA_ENQUEUE, false);
boolean playImmediately = intent.getBooleanExtra(EXTRA_PLAY_IMMEDIATELY,
false);
boolean stream = intent.getBooleanExtra(EXTRA_STREAM, false);
String storyID = intent.getStringExtra(Constants.EXTRA_STORY_ID);
Log.d(LOG_TAG, "Received play request: " + url);
Log.d(LOG_TAG, " entitled: " + title);
Log.d(LOG_TAG, " enqueue: " + enqueue);
Log.d(LOG_TAG, " play now: " + playImmediately);
Log.d(LOG_TAG, " stream: " + stream);
PlaylistEntry entry;
if (id != -1) {
entry = retrievePlaylistEntryById(id);
if (entry == null) {
return;
}
} else {
entry = new PlaylistEntry(id, url, title, stream, -1, storyID);
}
if (enqueue) {
addPlaylistItem(entry);
Toast.makeText(getApplicationContext(),
R.string.msg_item_added_to_playlist, Toast.LENGTH_SHORT).show();
}
if (playImmediately) {
current = entry;
PlaybackService.setCurrent(current);
play();
drawer.animateOpen();
}
}
}
private static String msecToTime(int msec) {
int sec = (msec / 1000) % 60;
int min = (msec / 1000 / 60) % 60;
int hour = msec / 1000 / 60 / 60;
StringBuilder output = new StringBuilder();
if (hour > 0) {
output.append(hour).append(":");
output.append(String.format("%02d", min)).append(":");
} else {
output.append(String.format("%d", min)).append(":");
}
output.append(String.format("%02d", sec));
return output.toString();
}
public void updatePlayTime() {
if (player.isPlaying()) {
String current = msecToTime(player.getCurrentPosition());
String total = msecToTime(player.getDuration());
lengthText.setText(current + " / " + total);
}
}
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (percent > 20 && percent % 5 != 0) {
// Throttle events, since we get too many of them at first.
return;
}
progressBar.setSecondaryProgress(percent);
updatePlayTime();
}
@Override
public void onCompletion(MediaPlayer mp) {
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
new AlertDialog.Builder(this).setMessage(
"Received error: " + what + ", " + extra).setCancelable(true).show();
setPlayButton();
return false;
}
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int possibleProgress = progress > seekBar.getSecondaryProgress() ? seekBar
.getSecondaryProgress() : progress;
if (fromUser) {
// Only seek to position if we've downloaded the content.
int msec = player.getDuration() * possibleProgress / seekBar.getMax();
player.seekTo(msec);
}
updatePlayTime();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onPrepared(MediaPlayer mp) {
current = player.getCurrentEntry();
resetUI();
Log.d(LOG_TAG, "prepared and started");
startUpdateThread();
drawer.animateClose();
}
private void startUpdateThread() {
handler.sendEmptyMessage(0);
updateProgressThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
while (true) {
handler.sendEmptyMessage(1);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
}
});
updateProgressThread.start();
}
public static class PlaylistEntry {
long id;
final String url;
final String title;
final boolean isStream;
int order;
final String storyID;
public PlaylistEntry(long id, String url, String title, boolean isStream,
int order) {
this(id, url, title, isStream, order, null);
}
public PlaylistEntry(long id, String url, String title, boolean isStream,
int order, String storyID) {
this.id = id;
this.url = url;
this.title = title;
this.isStream = isStream;
this.order = order;
this.storyID = storyID;
}
}
private void addPlaylistItem(PlaylistEntry entry) {
ContentValues values = new ContentValues();
values.put(Items.NAME, entry.title);
values.put(Items.URL, entry.url);
values.put(Items.IS_READ, false);
values.put(Items.PLAY_ORDER, PlaylistProvider.getMax(this) + 1);
values.put(Items.STORY_ID, entry.storyID);
Log.d(LOG_TAG, "Adding playlist item to db");
Uri insert = getContentResolver().insert(PlaylistProvider.CONTENT_URI,
values);
entry.id = ContentUris.parseId(insert);
}
private PlaylistEntry retrievePlaylistEntryById(long id) {
Uri query = ContentUris.withAppendedId(PlaylistProvider.CONTENT_URI, id);
Cursor cursor = getContentResolver().query(query, null, null, null,
PlaylistProvider.Items.PLAY_ORDER);
startManagingCursor(cursor);
return getFromCursor(cursor);
}
private PlaylistEntry getFromCursor(Cursor c) {
String title = null, url = null, storyID = null;
long id;
int order;
if (c.moveToFirst()) {
id = c.getInt(c.getColumnIndex(PlaylistProvider.Items._ID));
title = c.getString(c.getColumnIndex(PlaylistProvider.Items.NAME));
url = c.getString(c.getColumnIndex(PlaylistProvider.Items.URL));
order = c.getInt(c.getColumnIndex(PlaylistProvider.Items.PLAY_ORDER));
storyID = c.getString(c.getColumnIndex(PlaylistProvider.Items.STORY_ID));
c.close();
return new PlaylistEntry(id, url, title, false, order, storyID);
}
c.close();
return null;
}
@Override
public void onDrawerOpened() {
ImageView arrow = (ImageView) findViewById(R.id.DrawerArrowImage);
arrow.setImageDrawable(getResources().getDrawable(R.drawable.arrow_down));
}
@Override
public void onDrawerClosed() {
ImageView arrow = (ImageView) findViewById(R.id.DrawerArrowImage);
arrow.setImageDrawable(getResources().getDrawable(R.drawable.arrow_up));
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listen);
drawer = (SlidingDrawer) findViewById(R.id.drawer);
drawer.setOnDrawerOpenListener(this);
drawer.setOnDrawerCloseListener(this);
playButton = (ImageButton) findViewById(R.id.StreamPlayButton);
playButton.setEnabled(false);
playButton.setOnClickListener(this);
streamButton = (ImageButton) findViewById(R.id.StreamShareButton);
streamButton.setOnClickListener(this);
streamButton.setEnabled(false);
Button playlistButton = (Button) findViewById(R.id.StreamPlaylistButton);
playlistButton.setOnClickListener(this);
progressBar = (SeekBar) findViewById(R.id.StreamProgressBar);
progressBar.setMax(100);
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(false);
infoText = (TextView) findViewById(R.id.StreamTextView);
lengthText = (TextView) findViewById(R.id.StreamLengthText);
lengthText.setText("");
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
// Create a PhoneStateListener to watch for offhook and idle events
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
// phone going offhook, pause the player
if (player != null && player.isPlaying()) {
player.pause();
isPausedInCall = true;
setPlayButton();
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// phone idle. rewind a couple of seconds and start playing
if (isPausedInCall && player != null) {
int resumePosition = player.getPosition() - RESUME_REWIND_TIME;
if (resumePosition < 0) {
resumePosition = 0;
}
player.seekTo(resumePosition);
player.play();
setPlayButton();
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
registerReceiver(receiver, new IntentFilter(this.getClass().getName()));
Intent serviceIntent = new Intent(this, PlaybackService.class);
conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
player = ((PlaybackService.ListenBinder) service).getService();
onBindComplete((PlaybackService.ListenBinder) service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.w(LOG_TAG, "DISCONNECT");
player = null;
}
};
if (!PlaybackService.isRunning) {
getApplicationContext().startService(serviceIntent);
}
getApplicationContext().bindService(serviceIntent, conn, 1);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listen);
drawer = (SlidingDrawer) findViewById(R.id.drawer);
drawer.setOnDrawerOpenListener(this);
drawer.setOnDrawerCloseListener(this);
playButton = (ImageButton) findViewById(R.id.StreamPlayButton);
playButton.setEnabled(false);
playButton.setOnClickListener(this);
streamButton = (ImageButton) findViewById(R.id.StreamShareButton);
streamButton.setOnClickListener(this);
streamButton.setEnabled(false);
Button playlistButton = (Button) findViewById(R.id.StreamPlaylistButton);
playlistButton.setOnClickListener(this);
progressBar = (SeekBar) findViewById(R.id.StreamProgressBar);
progressBar.setMax(100);
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(false);
infoText = (TextView) findViewById(R.id.StreamTextView);
lengthText = (TextView) findViewById(R.id.StreamLengthText);
lengthText.setText("");
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
// Create a PhoneStateListener to watch for offhook and idle events
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
// phone going offhook or ringing, pause the player
if (player != null && player.isPlaying()) {
player.pause();
isPausedInCall = true;
setPlayButton();
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// phone idle. rewind a couple of seconds and start playing
if (isPausedInCall && player != null) {
int resumePosition = player.getPosition() - RESUME_REWIND_TIME;
if (resumePosition < 0) {
resumePosition = 0;
}
player.seekTo(resumePosition);
player.play();
setPlayButton();
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
registerReceiver(receiver, new IntentFilter(this.getClass().getName()));
Intent serviceIntent = new Intent(this, PlaybackService.class);
conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
player = ((PlaybackService.ListenBinder) service).getService();
onBindComplete((PlaybackService.ListenBinder) service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.w(LOG_TAG, "DISCONNECT");
player = null;
}
};
if (!PlaybackService.isRunning) {
getApplicationContext().startService(serviceIntent);
}
getApplicationContext().bindService(serviceIntent, conn, 1);
}
|
diff --git a/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java b/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java
index 99d6bf7..a54a5d6 100644
--- a/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java
+++ b/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java
@@ -1,901 +1,909 @@
/**
* Copyright (C) 2009-2013 enstratius, 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.dasein.cloud.cloudstack.compute;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.cloudstack.CSCloud;
import org.dasein.cloud.cloudstack.CSException;
import org.dasein.cloud.cloudstack.CSMethod;
import org.dasein.cloud.cloudstack.CSServiceProvider;
import org.dasein.cloud.cloudstack.CSVersion;
import org.dasein.cloud.cloudstack.Param;
import org.dasein.cloud.compute.AbstractVolumeSupport;
import org.dasein.cloud.compute.Platform;
import org.dasein.cloud.compute.Snapshot;
import org.dasein.cloud.compute.VirtualMachine;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.compute.Volume;
import org.dasein.cloud.compute.VolumeCreateOptions;
import org.dasein.cloud.compute.VolumeFormat;
import org.dasein.cloud.compute.VolumeProduct;
import org.dasein.cloud.compute.VolumeState;
import org.dasein.cloud.compute.VolumeType;
import org.dasein.cloud.util.APITrace;
import org.dasein.cloud.util.Cache;
import org.dasein.cloud.util.CacheLevel;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Storage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Volumes extends AbstractVolumeSupport {
static private final Logger logger = Logger.getLogger(Volumes.class);
static private final String ATTACH_VOLUME = "attachVolume";
static private final String CREATE_VOLUME = "createVolume";
static private final String DELETE_VOLUME = "deleteVolume";
static private final String DETACH_VOLUME = "detachVolume";
static private final String LIST_DISK_OFFERINGS = "listDiskOfferings";
static private final String LIST_VOLUMES = "listVolumes";
static public class DiskOffering {
public String id;
public long diskSize;
public String name;
public String description;
public String type;
public String toString() {return "DiskOffering ["+id+"] of size "+diskSize;}
}
private CSCloud provider;
Volumes(CSCloud provider) {
super(provider);
this.provider = provider;
}
@Override
public void attach(@Nonnull String volumeId, @Nonnull String serverId, @Nullable String deviceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.attach");
try {
Param[] params;
if( logger.isInfoEnabled() ) {
logger.info("attaching " + volumeId + " to " + serverId + " as " + deviceId);
}
VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(serverId);
if( vm == null ) {
throw new CloudException("No such virtual machine: " + serverId);
}
long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L);
while( timeout > System.currentTimeMillis() ) {
if( VmState.RUNNING.equals(vm.getCurrentState()) || VmState.STOPPED.equals(vm.getCurrentState()) ) {
break;
}
try { Thread.sleep(15000L); }
catch( InterruptedException ignore ) { }
try { vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(serverId); }
catch( Throwable ignore ) { }
if( vm == null ) {
throw new CloudException("Virtual machine " + serverId + " disappeared waiting for it to enter an attachable state");
}
}
if( deviceId == null ) {
params = new Param[] { new Param("id", volumeId), new Param("virtualMachineId", serverId) };
}
else {
deviceId = toDeviceNumber(deviceId);
if( logger.isDebugEnabled() ) {
logger.debug("Device mapping is: " + deviceId);
}
params = new Param[] { new Param("id", volumeId), new Param("virtualMachineId", serverId), new Param("deviceId", deviceId) };
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(ATTACH_VOLUME, params), ATTACH_VOLUME);
if( doc == null ) {
throw new CloudException("No such volume or server");
}
provider.waitForJob(doc, "Attach Volume");
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.createVolume");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was provided for this request");
}
if( options.getFormat().equals(VolumeFormat.NFS) ) {
throw new OperationNotSupportedException("NFS volumes are not currently supported in " + getProvider().getCloudName());
}
String snapshotId = options.getSnapshotId();
String productId = options.getVolumeProductId();
VolumeProduct product = null;
if( productId != null ) {
for( VolumeProduct prd : listVolumeProducts() ) {
if( productId.equals(prd.getProviderProductId()) ) {
product = prd;
break;
}
}
}
Storage<Gigabyte> size;
if( snapshotId == null ) {
if( product == null ) {
size = options.getVolumeSize();
if( size.intValue() < getMinimumVolumeSize().intValue() ) {
size = getMinimumVolumeSize();
}
Iterable<VolumeProduct> products = listVolumeProducts();
VolumeProduct best = null;
+ VolumeProduct custom = null;
for( VolumeProduct p : products ) {
Storage<Gigabyte> s = p.getVolumeSize();
if( s == null || s.intValue() == 0 ) {
- product = p;
- break;
+ if (custom == null) {
+ custom = p;
+ }
+ continue;
}
long currentSize = s.getQuantity().longValue();
s = (best == null ? null : best.getVolumeSize());
long bestSize = (s == null ? 0L : s.getQuantity().longValue());
if( size.longValue() > 0L && size.longValue() == currentSize ) {
product = p;
break;
}
if( best == null ) {
best = p;
}
else if( bestSize > 0L || currentSize > 0L ) {
if( size.longValue() > 0L ) {
if( bestSize < size.longValue() && bestSize >0L && currentSize > size.longValue() ) {
best = p;
}
else if( bestSize > size.longValue() && currentSize > size.longValue() && currentSize < bestSize ) {
best = p;
}
}
else if( currentSize > 0L && currentSize < bestSize ) {
best = p;
}
}
}
if( product == null ) {
- product = best;
+ if (custom != null) {
+ product = custom;
+ }
+ else {
+ product = best;
+ }
}
}
else {
size = product.getVolumeSize();
if( size == null || size.intValue() < 1 ) {
size = options.getVolumeSize();
}
}
if( product == null && size.longValue() < 1L ) {
throw new CloudException("No offering matching " + options.getVolumeProductId());
}
}
else {
Snapshot snapshot = provider.getComputeServices().getSnapshotSupport().getSnapshot(snapshotId);
if( snapshot == null ) {
throw new CloudException("No such snapshot: " + snapshotId);
}
int s = snapshot.getSizeInGb();
if( s < 1 || s < getMinimumVolumeSize().intValue() ) {
size = getMinimumVolumeSize();
}
else {
size = new Storage<Gigabyte>(s, Storage.GIGABYTE);
}
}
Param[] params;
if( product == null && snapshotId == null ) {
/*params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("size", String.valueOf(size.longValue()))
}; */
throw new CloudException("A suitable snapshot or disk offering could not be found to pass to CloudStack createVolume request");
}
else if( snapshotId != null ) {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("snapshotId", snapshotId),
new Param("size", String.valueOf(size.longValue()))
};
}
else {
Storage<Gigabyte> s = product.getVolumeSize();
if( s == null || s.intValue() < 1 ) {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("diskOfferingId", product.getProviderProductId()),
new Param("size", String.valueOf(size.longValue()))
};
}
else {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("diskOfferingId", product.getProviderProductId())
};
}
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(CREATE_VOLUME, params), CREATE_VOLUME);
NodeList matches = doc.getElementsByTagName("volumeid"); // v2.1
String volumeId = null;
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
if( volumeId == null ) {
matches = doc.getElementsByTagName("id"); // v2.2
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
}
if( volumeId == null ) {
matches = doc.getElementsByTagName("jobid"); // v4.1
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
}
if( volumeId == null ) {
throw new CloudException("Failed to create volume");
}
Document responseDoc = provider.waitForJob(doc, "Create Volume");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("volume");
if (nodeList.getLength() > 0) {
Node volume = nodeList.item(0);
NodeList attributes = volume.getChildNodes();
for (int i = 0; i<attributes.getLength(); i++) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if (name.equalsIgnoreCase("id")) {
volumeId = value;
break;
}
}
}
}
return volumeId;
}
finally {
APITrace.end();
}
}
@Override
public void detach(@Nonnull String volumeId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.detach");
try {
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(DETACH_VOLUME, new Param("id", volumeId)), DETACH_VOLUME);
provider.waitForJob(doc, "Detach Volume");
}
finally {
APITrace.end();
}
}
@Override
public int getMaximumVolumeCount() throws InternalException, CloudException {
return -2;
}
@Override
public @Nonnull Storage<Gigabyte> getMaximumVolumeSize() throws InternalException, CloudException {
return new Storage<Gigabyte>(5000, Storage.GIGABYTE);
}
@Override
public @Nonnull Storage<Gigabyte> getMinimumVolumeSize() throws InternalException, CloudException {
return new Storage<Gigabyte>(1, Storage.GIGABYTE);
}
@Nonnull Collection<DiskOffering> getDiskOfferings() throws InternalException, CloudException {
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_DISK_OFFERINGS), LIST_DISK_OFFERINGS);
ArrayList<DiskOffering> offerings = new ArrayList<DiskOffering>();
NodeList matches = doc.getElementsByTagName("diskoffering");
for( int i=0; i<matches.getLength(); i++ ) {
DiskOffering offering = new DiskOffering();
Node node = matches.item(i);
NodeList attributes;
attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node n = attributes.item(j);
String value;
if( n.getChildNodes().getLength() > 0 ) {
value = n.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( n.getNodeName().equals("id") ) {
offering.id = value;
}
else if( n.getNodeName().equals("disksize") ) {
offering.diskSize = Long.parseLong(value);
}
else if( n.getNodeName().equalsIgnoreCase("name") ) {
offering.name = value;
}
else if( n.getNodeName().equalsIgnoreCase("displayText") ) {
offering.description = value;
}
else if( n.getNodeName().equalsIgnoreCase("storagetype") ) {
offering.type = value;
}
}
if( offering.id != null ) {
if( offering.name == null ) {
if( offering.diskSize > 0 ) {
offering.name = offering.diskSize + " GB";
}
else {
offering.name = "Custom #" + offering.id;
}
}
if( offering.description == null ) {
offering.description = offering.name;
}
offerings.add(offering);
}
}
return offerings;
}
@Override
public @Nonnull String getProviderTermForVolume(@Nonnull Locale locale) {
return "volume";
}
@Nullable String getRootVolumeId(@Nonnull String serverId) throws InternalException, CloudException {
Volume volume = getRootVolume(serverId);
return (volume == null ? null : volume.getProviderVolumeId());
}
private @Nullable Volume getRootVolume(@Nonnull String serverId) throws InternalException, CloudException {
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("virtualMachineId", serverId)), LIST_VOLUMES);
NodeList matches = doc.getElementsByTagName("volume");
for( int i=0; i<matches.getLength(); i++ ) {
Node v = matches.item(i);
if( v != null ) {
Volume volume = toVolume(v, true);
if( volume != null ) {
return volume;
}
}
}
return null;
}
@Override
public @Nullable Volume getVolume(@Nonnull String volumeId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.getVolume");
try {
try {
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("id", volumeId), new Param("zoneId", getContext().getRegionId())), LIST_VOLUMES);
NodeList matches = doc.getElementsByTagName("volume");
for( int i=0; i<matches.getLength(); i++ ) {
Node v = matches.item(i);
if( v != null ) {
return toVolume(v, false);
}
}
return null;
}
catch( CSException e ) {
if( e.getHttpCode() == 431 ) {
return null;
}
throw e;
}
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement getVolumeProductRequirement() throws InternalException, CloudException {
return Requirement.OPTIONAL;
}
@Override
public boolean isVolumeSizeDeterminedByProduct() throws InternalException, CloudException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "Volume.isSubscribed");
try {
return provider.getComputeServices().getVirtualMachineSupport().isSubscribed();
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<String> listPossibleDeviceIds(@Nonnull Platform platform) throws InternalException, CloudException {
Cache<String> cache;
if( platform.isWindows() ) {
cache = Cache.getInstance(getProvider(), "windowsDeviceIds", String.class, CacheLevel.CLOUD);
}
else {
cache = Cache.getInstance(getProvider(), "unixDeviceIds", String.class, CacheLevel.CLOUD);
}
Iterable<String> ids = cache.get(getContext());
if( ids == null ) {
ArrayList<String> list = new ArrayList<String>();
if( platform.isWindows() ) {
list.add("hde");
list.add("hdf");
list.add("hdg");
list.add("hdh");
list.add("hdi");
list.add("hdj");
}
else {
list.add("/dev/xvdc");
list.add("/dev/xvde");
list.add("/dev/xvdf");
list.add("/dev/xvdg");
list.add("/dev/xvdh");
list.add("/dev/xvdi");
list.add("/dev/xvdj");
}
ids = Collections.unmodifiableList(list);
cache.put(getContext(), ids);
}
return ids;
}
@Override
public @Nonnull Iterable<VolumeFormat> listSupportedFormats() throws InternalException, CloudException {
return Collections.singletonList(VolumeFormat.BLOCK);
}
@Override
public @Nonnull Iterable<VolumeProduct> listVolumeProducts() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.listVolumeProducts");
try {
Cache<VolumeProduct> cache = Cache.getInstance(getProvider(), "volumeProducts", VolumeProduct.class, CacheLevel.REGION_ACCOUNT);
Iterable<VolumeProduct> products = cache.get(getContext());
if( products == null ) {
ArrayList<VolumeProduct> list = new ArrayList<VolumeProduct>();
for( DiskOffering offering : getDiskOfferings() ) {
VolumeProduct p = toProduct(offering);
if( p != null && (!provider.getServiceProvider().equals(CSServiceProvider.DEMOCLOUD) || "local".equals(offering.type)) ) {
list.add(p);
}
}
products = Collections.unmodifiableList(list);
cache.put(getContext(), products);
}
return products;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<ResourceStatus> listVolumeStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.listVolumeStatus");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("zoneId", ctx.getRegionId())), LIST_VOLUMES);
ArrayList<ResourceStatus> volumes = new ArrayList<ResourceStatus>();
NodeList matches = doc.getElementsByTagName("volume");
for( int i=0; i<matches.getLength(); i++ ) {
Node v = matches.item(i);
if( v != null ) {
ResourceStatus volume = toStatus(v);
if( volume != null ) {
volumes.add(volume);
}
}
}
return volumes;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<Volume> listVolumes() throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.listVolumes");
try {
return listVolumes(false);
}
finally {
APITrace.end();
}
}
private @Nonnull Collection<Volume> listVolumes(boolean rootOnly) throws InternalException, CloudException {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("zoneId", ctx.getRegionId())), LIST_VOLUMES);
ArrayList<Volume> volumes = new ArrayList<Volume>();
NodeList matches = doc.getElementsByTagName("volume");
for( int i=0; i<matches.getLength(); i++ ) {
Node v = matches.item(i);
if( v != null ) {
Volume volume = toVolume(v, rootOnly);
if( volume != null ) {
volumes.add(volume);
}
}
}
return volumes;
}
@Override
public void remove(@Nonnull String volumeId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.remove");
try {
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(DELETE_VOLUME, new Param("id", volumeId)), DELETE_VOLUME);
provider.waitForJob(doc, "Delete Volume");
}
finally {
APITrace.end();
}
}
private @Nonnull String toDeviceNumber(@Nonnull String deviceId) {
if( !deviceId.startsWith("/dev/") && !deviceId.startsWith("hd") ) {
deviceId = "/dev/" + deviceId;
}
if( deviceId.equals("/dev/xvda") ) { return "0"; }
else if( deviceId.equals("/dev/xvdb") ) { return "1"; }
else if( deviceId.equals("/dev/xvdc") ) { return "2"; }
else if( deviceId.equals("/dev/xvde") ) { return "4"; }
else if( deviceId.equals("/dev/xvdf") ) { return "5"; }
else if( deviceId.equals("/dev/xvdg") ) { return "6"; }
else if( deviceId.equals("/dev/xvdh") ) { return "7"; }
else if( deviceId.equals("/dev/xvdi") ) { return "8"; }
else if( deviceId.equals("/dev/xvdj") ) { return "9"; }
else if( deviceId.equals("hda") ) { return "0"; }
else if( deviceId.equals("hdb") ) { return "1"; }
else if( deviceId.equals("hdc") ) { return "2"; }
else if( deviceId.equals("hdd") ) { return "3"; }
else if( deviceId.equals("hde") ) { return "4"; }
else if( deviceId.equals("hdf") ) { return "5"; }
else if( deviceId.equals("hdg") ) { return "6"; }
else if( deviceId.equals("hdh") ) { return "7"; }
else if( deviceId.equals("hdi") ) { return "8"; }
else if( deviceId.equals("hdj") ) { return "9"; }
else { return "9"; }
}
private @Nonnull String toDeviceID(@Nonnull String deviceNumber, boolean isWindows) {
if (deviceNumber == null){
return null;
}
if (!isWindows){
if( deviceNumber.equals("0") ) { return "/dev/xvda"; }
else if( deviceNumber.equals("1") ) { return "/dev/xvdb"; }
else if( deviceNumber.equals("2") ) { return "/dev/xvdc"; }
else if( deviceNumber.equals("4") ) { return "/dev/xvde"; }
else if( deviceNumber.equals("5") ) { return "/dev/xvdf"; }
else if( deviceNumber.equals("6") ) { return "/dev/xvdg"; }
else if( deviceNumber.equals("7") ) { return "/dev/xvdh"; }
else if( deviceNumber.equals("8") ) { return "/dev/xvdi"; }
else if( deviceNumber.equals("9") ) { return "/dev/xvdj"; }
else { return "/dev/xvdj"; }
}
else{
if( deviceNumber.equals("0") ) { return "hda"; }
else if( deviceNumber.equals("1") ) { return "hdb"; }
else if( deviceNumber.equals("2") ) { return "hdc"; }
else if( deviceNumber.equals("3") ) { return "hdd"; }
else if( deviceNumber.equals("4") ) { return "hde"; }
else if( deviceNumber.equals("5") ) { return "hdf"; }
else if( deviceNumber.equals("6") ) { return "hdg"; }
else if( deviceNumber.equals("7") ) { return "hdh"; }
else if( deviceNumber.equals("8") ) { return "hdi"; }
else if( deviceNumber.equals("9") ) { return "hdj"; }
else { return "hdj"; }
}
}
private @Nullable VolumeProduct toProduct(@Nullable DiskOffering offering) throws InternalException, CloudException {
if( offering == null ) {
return null;
}
if( offering.diskSize < 1 ) {
return VolumeProduct.getInstance(offering.id, offering.name, offering.description, VolumeType.HDD);
}
else {
return VolumeProduct.getInstance(offering.id, offering.name, offering.description, VolumeType.HDD, new Storage<Gigabyte>(offering.diskSize, Storage.GIGABYTE));
}
}
private @Nullable ResourceStatus toStatus(@Nullable Node node) throws InternalException, CloudException {
if( node == null ) {
return null;
}
NodeList attributes = node.getChildNodes();
VolumeState volumeState = null;
String volumeId = null;
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
if( attribute != null ) {
String name = attribute.getNodeName();
if( name.equals("id") ) {
volumeId = attribute.getFirstChild().getNodeValue().trim();
}
else if( name.equals("state") && attribute.hasChildNodes() ) {
String state = attribute.getFirstChild().getNodeValue();
if( state == null ) {
volumeState = VolumeState.PENDING;
}
else if( state.equalsIgnoreCase("created") || state.equalsIgnoreCase("ready") || state.equalsIgnoreCase("allocated") ) {
volumeState = VolumeState.AVAILABLE;
}
else {
logger.warn("DEBUG: Unknown state for CloudStack volume: " + state);
volumeState = VolumeState.PENDING;
}
}
if( volumeId != null && volumeState != null ) {
break;
}
}
}
if( volumeId == null ) {
return null;
}
if( volumeState == null ) {
volumeState = VolumeState.PENDING;
}
return new ResourceStatus(volumeId, volumeState);
}
private @Nullable Volume toVolume(@Nullable Node node, boolean rootOnly) throws InternalException, CloudException {
if( node == null ) {
return null;
}
Volume volume = new Volume();
String offeringId = null;
NodeList attributes = node.getChildNodes();
String volumeName = null, description = null;
boolean root = false;
String deviceNumber = null;
volume.setFormat(VolumeFormat.BLOCK);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
if( attribute != null ) {
String name = attribute.getNodeName();
if( name.equals("id") ) {
volume.setProviderVolumeId(attribute.getFirstChild().getNodeValue().trim());
}
if( name.equals("zoneid") ) {
String zid = attribute.getFirstChild().getNodeValue().trim();
if( !provider.getContext().getRegionId().equals(zid) ) {
System.out.println("Zone mismatch: " + provider.getContext().getRegionId());
System.out.println(" " + zid);
return null;
}
}
else if( name.equals("type") && attribute.hasChildNodes() ) {
if( attribute.getFirstChild().getNodeValue().equalsIgnoreCase("root") ) {
root = true;
}
}
else if( name.equals("diskofferingid") && attribute.hasChildNodes() ) {
offeringId = attribute.getFirstChild().getNodeValue().trim();
}
else if( name.equals("name") && attribute.hasChildNodes() ) {
volumeName = attribute.getFirstChild().getNodeValue().trim();
}
else if ( name.equals("deviceid") && attribute.hasChildNodes()){
deviceNumber = attribute.getFirstChild().getNodeValue().trim();
}
else if( name.equalsIgnoreCase("virtualmachineid") && attribute.hasChildNodes() ) {
volume.setProviderVirtualMachineId(attribute.getFirstChild().getNodeValue());
}
else if( name.equals("displayname") && attribute.hasChildNodes() ) {
description = attribute.getFirstChild().getNodeValue().trim();
}
else if( name.equals("size") && attribute.hasChildNodes() ) {
long size = (Long.parseLong(attribute.getFirstChild().getNodeValue())/1024000000L);
volume.setSize(new Storage<Gigabyte>(size, Storage.GIGABYTE));
}
else if( name.equals("state") && attribute.hasChildNodes() ) {
String state = attribute.getFirstChild().getNodeValue();
if( state == null ) {
volume.setCurrentState(VolumeState.PENDING);
}
else if( state.equalsIgnoreCase("created") || state.equalsIgnoreCase("ready")
|| state.equalsIgnoreCase("allocated") || state.equalsIgnoreCase("uploaded")) {
volume.setCurrentState(VolumeState.AVAILABLE);
}
else {
logger.warn("DEBUG: Unknown state for CloudStack volume: " + state);
volume.setCurrentState(VolumeState.PENDING);
}
}
else if( name.equals("created") && attribute.hasChildNodes() ) {
String date = attribute.getFirstChild().getNodeValue();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
volume.setCreationTimestamp(df.parse(date).getTime());
}
catch( ParseException e ) {
volume.setCreationTimestamp(0L);
}
}
}
}
if( !root && rootOnly ) {
return null;
}
if( volume.getProviderVolumeId() == null ) {
return null;
}
if( volumeName == null ) {
volume.setName(volume.getProviderVolumeId());
}
else {
volume.setName(volumeName);
}
if( description == null ) {
volume.setDescription(volume.getName());
}
else {
volume.setDescription(description);
}
if( offeringId != null ) {
volume.setProviderProductId(offeringId);
}
volume.setProviderRegionId(provider.getContext().getRegionId());
volume.setProviderDataCenterId(provider.getContext().getRegionId());
if( volume.getProviderVirtualMachineId() != null ) {
VirtualMachine vm = null;
try {
vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(volume.getProviderVirtualMachineId());
if( vm == null ) {
logger.warn("Could not find Virtual machine " + volume.getProviderVirtualMachineId() + " for root volume " + volume.getProviderVolumeId() + " .");
}
else{
volume.setDeviceId(toDeviceID(deviceNumber, vm.getPlatform().isWindows()));
}
}
catch( Exception e ) {
if(logger.isDebugEnabled()){
logger.warn("Error trying to determine device id for a volume : " + e.getMessage(),e);
}
else{
logger.warn("Error trying to determine device id for a volume : " + e.getMessage());
}
}
}
volume.setRootVolume(root);
volume.setType(VolumeType.HDD);
if( root ) {
volume.setGuestOperatingSystem(Platform.guess(volume.getName() + " " + volume.getDescription()));
}
return volume;
}
}
| false | true | public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.createVolume");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was provided for this request");
}
if( options.getFormat().equals(VolumeFormat.NFS) ) {
throw new OperationNotSupportedException("NFS volumes are not currently supported in " + getProvider().getCloudName());
}
String snapshotId = options.getSnapshotId();
String productId = options.getVolumeProductId();
VolumeProduct product = null;
if( productId != null ) {
for( VolumeProduct prd : listVolumeProducts() ) {
if( productId.equals(prd.getProviderProductId()) ) {
product = prd;
break;
}
}
}
Storage<Gigabyte> size;
if( snapshotId == null ) {
if( product == null ) {
size = options.getVolumeSize();
if( size.intValue() < getMinimumVolumeSize().intValue() ) {
size = getMinimumVolumeSize();
}
Iterable<VolumeProduct> products = listVolumeProducts();
VolumeProduct best = null;
for( VolumeProduct p : products ) {
Storage<Gigabyte> s = p.getVolumeSize();
if( s == null || s.intValue() == 0 ) {
product = p;
break;
}
long currentSize = s.getQuantity().longValue();
s = (best == null ? null : best.getVolumeSize());
long bestSize = (s == null ? 0L : s.getQuantity().longValue());
if( size.longValue() > 0L && size.longValue() == currentSize ) {
product = p;
break;
}
if( best == null ) {
best = p;
}
else if( bestSize > 0L || currentSize > 0L ) {
if( size.longValue() > 0L ) {
if( bestSize < size.longValue() && bestSize >0L && currentSize > size.longValue() ) {
best = p;
}
else if( bestSize > size.longValue() && currentSize > size.longValue() && currentSize < bestSize ) {
best = p;
}
}
else if( currentSize > 0L && currentSize < bestSize ) {
best = p;
}
}
}
if( product == null ) {
product = best;
}
}
else {
size = product.getVolumeSize();
if( size == null || size.intValue() < 1 ) {
size = options.getVolumeSize();
}
}
if( product == null && size.longValue() < 1L ) {
throw new CloudException("No offering matching " + options.getVolumeProductId());
}
}
else {
Snapshot snapshot = provider.getComputeServices().getSnapshotSupport().getSnapshot(snapshotId);
if( snapshot == null ) {
throw new CloudException("No such snapshot: " + snapshotId);
}
int s = snapshot.getSizeInGb();
if( s < 1 || s < getMinimumVolumeSize().intValue() ) {
size = getMinimumVolumeSize();
}
else {
size = new Storage<Gigabyte>(s, Storage.GIGABYTE);
}
}
Param[] params;
if( product == null && snapshotId == null ) {
/*params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("size", String.valueOf(size.longValue()))
}; */
throw new CloudException("A suitable snapshot or disk offering could not be found to pass to CloudStack createVolume request");
}
else if( snapshotId != null ) {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("snapshotId", snapshotId),
new Param("size", String.valueOf(size.longValue()))
};
}
else {
Storage<Gigabyte> s = product.getVolumeSize();
if( s == null || s.intValue() < 1 ) {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("diskOfferingId", product.getProviderProductId()),
new Param("size", String.valueOf(size.longValue()))
};
}
else {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("diskOfferingId", product.getProviderProductId())
};
}
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(CREATE_VOLUME, params), CREATE_VOLUME);
NodeList matches = doc.getElementsByTagName("volumeid"); // v2.1
String volumeId = null;
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
if( volumeId == null ) {
matches = doc.getElementsByTagName("id"); // v2.2
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
}
if( volumeId == null ) {
matches = doc.getElementsByTagName("jobid"); // v4.1
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
}
if( volumeId == null ) {
throw new CloudException("Failed to create volume");
}
Document responseDoc = provider.waitForJob(doc, "Create Volume");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("volume");
if (nodeList.getLength() > 0) {
Node volume = nodeList.item(0);
NodeList attributes = volume.getChildNodes();
for (int i = 0; i<attributes.getLength(); i++) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if (name.equalsIgnoreCase("id")) {
volumeId = value;
break;
}
}
}
}
return volumeId;
}
| public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "Volume.createVolume");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was provided for this request");
}
if( options.getFormat().equals(VolumeFormat.NFS) ) {
throw new OperationNotSupportedException("NFS volumes are not currently supported in " + getProvider().getCloudName());
}
String snapshotId = options.getSnapshotId();
String productId = options.getVolumeProductId();
VolumeProduct product = null;
if( productId != null ) {
for( VolumeProduct prd : listVolumeProducts() ) {
if( productId.equals(prd.getProviderProductId()) ) {
product = prd;
break;
}
}
}
Storage<Gigabyte> size;
if( snapshotId == null ) {
if( product == null ) {
size = options.getVolumeSize();
if( size.intValue() < getMinimumVolumeSize().intValue() ) {
size = getMinimumVolumeSize();
}
Iterable<VolumeProduct> products = listVolumeProducts();
VolumeProduct best = null;
VolumeProduct custom = null;
for( VolumeProduct p : products ) {
Storage<Gigabyte> s = p.getVolumeSize();
if( s == null || s.intValue() == 0 ) {
if (custom == null) {
custom = p;
}
continue;
}
long currentSize = s.getQuantity().longValue();
s = (best == null ? null : best.getVolumeSize());
long bestSize = (s == null ? 0L : s.getQuantity().longValue());
if( size.longValue() > 0L && size.longValue() == currentSize ) {
product = p;
break;
}
if( best == null ) {
best = p;
}
else if( bestSize > 0L || currentSize > 0L ) {
if( size.longValue() > 0L ) {
if( bestSize < size.longValue() && bestSize >0L && currentSize > size.longValue() ) {
best = p;
}
else if( bestSize > size.longValue() && currentSize > size.longValue() && currentSize < bestSize ) {
best = p;
}
}
else if( currentSize > 0L && currentSize < bestSize ) {
best = p;
}
}
}
if( product == null ) {
if (custom != null) {
product = custom;
}
else {
product = best;
}
}
}
else {
size = product.getVolumeSize();
if( size == null || size.intValue() < 1 ) {
size = options.getVolumeSize();
}
}
if( product == null && size.longValue() < 1L ) {
throw new CloudException("No offering matching " + options.getVolumeProductId());
}
}
else {
Snapshot snapshot = provider.getComputeServices().getSnapshotSupport().getSnapshot(snapshotId);
if( snapshot == null ) {
throw new CloudException("No such snapshot: " + snapshotId);
}
int s = snapshot.getSizeInGb();
if( s < 1 || s < getMinimumVolumeSize().intValue() ) {
size = getMinimumVolumeSize();
}
else {
size = new Storage<Gigabyte>(s, Storage.GIGABYTE);
}
}
Param[] params;
if( product == null && snapshotId == null ) {
/*params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("size", String.valueOf(size.longValue()))
}; */
throw new CloudException("A suitable snapshot or disk offering could not be found to pass to CloudStack createVolume request");
}
else if( snapshotId != null ) {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("snapshotId", snapshotId),
new Param("size", String.valueOf(size.longValue()))
};
}
else {
Storage<Gigabyte> s = product.getVolumeSize();
if( s == null || s.intValue() < 1 ) {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("diskOfferingId", product.getProviderProductId()),
new Param("size", String.valueOf(size.longValue()))
};
}
else {
params = new Param[] {
new Param("name", options.getName()),
new Param("zoneId", ctx.getRegionId()),
new Param("diskOfferingId", product.getProviderProductId())
};
}
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(CREATE_VOLUME, params), CREATE_VOLUME);
NodeList matches = doc.getElementsByTagName("volumeid"); // v2.1
String volumeId = null;
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
if( volumeId == null ) {
matches = doc.getElementsByTagName("id"); // v2.2
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
}
if( volumeId == null ) {
matches = doc.getElementsByTagName("jobid"); // v4.1
if( matches.getLength() > 0 ) {
volumeId = matches.item(0).getFirstChild().getNodeValue();
}
}
if( volumeId == null ) {
throw new CloudException("Failed to create volume");
}
Document responseDoc = provider.waitForJob(doc, "Create Volume");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("volume");
if (nodeList.getLength() > 0) {
Node volume = nodeList.item(0);
NodeList attributes = volume.getChildNodes();
for (int i = 0; i<attributes.getLength(); i++) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if (name.equalsIgnoreCase("id")) {
volumeId = value;
break;
}
}
}
}
return volumeId;
}
|
diff --git a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterWindowImpl.java b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterWindowImpl.java
index 0fbcc41cd..20f1abbe8 100755
--- a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterWindowImpl.java
+++ b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterWindowImpl.java
@@ -1,375 +1,375 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.sdkuilib.internal.repository;
import com.android.sdklib.ISdkLog;
import com.android.sdklib.SdkConstants;
import com.android.sdklib.internal.repository.RepoSource;
import com.android.sdklib.internal.repository.RepoSources;
import com.android.sdklib.repository.SdkRepository;
import com.android.sdkuilib.internal.repository.icons.ImageFactory;
import com.android.sdkuilib.internal.tasks.ProgressTaskFactory;
import com.android.sdkuilib.repository.UpdaterWindow.ISdkListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
/**
* This is the private implementation of the UpdateWindow.
*/
public class UpdaterWindowImpl {
private final Shell mParentShell;
/** Internal data shared between the window and its pages. */
private final UpdaterData mUpdaterData;
/** The array of pages instances. Only one is visible at a time. */
private ArrayList<Composite> mPages = new ArrayList<Composite>();
/** Indicates a page change is due to an internal request. Prevents callbacks from looping. */
private boolean mInternalPageChange;
/** A list of extra pages to instantiate. Each entry is an object array with 2 elements:
* the string title and the Composite class to instantiate to create the page. */
private ArrayList<Object[]> mExtraPages;
/** A factory to create progress task dialogs. */
private ProgressTaskFactory mTaskFactory;
// --- UI members ---
protected Shell mAndroidSdkUpdater;
private SashForm mSashForm;
private List mPageList;
private Composite mPagesRootComposite;
private LocalPackagesPage mLocalPackagePage;
private RemotePackagesPage mRemotePackagesPage;
private AvdManagerPage mAvdManagerPage;
private StackLayout mStackLayout;
public UpdaterWindowImpl(Shell parentShell, ISdkLog sdkLog, String osSdkRoot,
boolean userCanChangeSdkRoot) {
mParentShell = parentShell;
mUpdaterData = new UpdaterData(osSdkRoot, sdkLog);
mUpdaterData.setUserCanChangeSdkRoot(userCanChangeSdkRoot);
}
/**
* Open the window.
* @wbp.parser.entryPoint
*/
public void open() {
if (mParentShell == null) {
Display.setAppName("Android"); //$hide$ (hide from SWT designer)
}
createContents();
mAndroidSdkUpdater.open();
mAndroidSdkUpdater.layout();
postCreate(); //$hide$ (hide from SWT designer)
Display display = Display.getDefault();
while (!mAndroidSdkUpdater.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
dispose(); //$hide$
}
/**
* Create contents of the window.
*/
protected void createContents() {
- mAndroidSdkUpdater = new Shell(mParentShell);
+ mAndroidSdkUpdater = new Shell(mParentShell, SWT.SHELL_TRIM);
mAndroidSdkUpdater.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
onAndroidSdkUpdaterDispose(); //$hide$ (hide from SWT designer)
}
});
FillLayout fl;
mAndroidSdkUpdater.setLayout(fl = new FillLayout(SWT.HORIZONTAL));
fl.marginHeight = fl.marginWidth = 5;
mAndroidSdkUpdater.setMinimumSize(new Point(200, 50));
mAndroidSdkUpdater.setSize(745, 433);
mAndroidSdkUpdater.setText("Android SDK");
mSashForm = new SashForm(mAndroidSdkUpdater, SWT.NONE);
mPageList = new List(mSashForm, SWT.BORDER);
mPageList.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onPageListSelected(); //$hide$ (hide from SWT designer)
}
});
mPagesRootComposite = new Composite(mSashForm, SWT.NONE);
mStackLayout = new StackLayout();
mPagesRootComposite.setLayout(mStackLayout);
mAvdManagerPage = new AvdManagerPage(mPagesRootComposite, mUpdaterData);
mLocalPackagePage = new LocalPackagesPage(mPagesRootComposite, mUpdaterData);
mRemotePackagesPage = new RemotePackagesPage(mPagesRootComposite, mUpdaterData);
mSashForm.setWeights(new int[] {150, 576});
}
// -- Start of internal part ----------
// Hide everything down-below from SWT designer
//$hide>>$
// --- UI Callbacks -----------
/**
* Registers an extra page for the updater window.
* <p/>
* Pages must derive from {@link Composite} and implement a constructor that takes
* a single parent {@link Composite} argument.
* <p/>
* All pages must be registered before the call to {@link #open()}.
*
* @param title The title of the page.
* @param pageClass The {@link Composite}-derived class that will implement the page.
*/
public void registerExtraPage(String title, Class<? extends Composite> pageClass) {
if (mExtraPages == null) {
mExtraPages = new ArrayList<Object[]>();
}
mExtraPages.add(new Object[]{ title, pageClass });
}
public void addListeners(ISdkListener listener) {
mUpdaterData.addListeners(listener);
}
public void removeListener(ISdkListener listener) {
mUpdaterData.removeListener(listener);
}
/**
* Helper to return the SWT shell.
*/
private Shell getShell() {
return mAndroidSdkUpdater;
}
/**
* Callback called when the window shell is disposed.
*/
private void onAndroidSdkUpdaterDispose() {
if (mUpdaterData != null) {
ImageFactory imgFactory = mUpdaterData.getImageFactory();
if (imgFactory != null) {
imgFactory.dispose();
}
}
}
/**
* Creates the icon of the window shell.
*/
private void setWindowImage(Shell androidSdkUpdater) {
String imageName = "android_icon_16.png"; //$NON-NLS-1$
if (SdkConstants.currentPlatform() == SdkConstants.PLATFORM_DARWIN) {
imageName = "android_icon_128.png"; //$NON-NLS-1$
}
if (mUpdaterData != null) {
ImageFactory imgFactory = mUpdaterData.getImageFactory();
if (imgFactory != null) {
mAndroidSdkUpdater.setImage(imgFactory.getImageByName(imageName));
}
}
}
/**
* Once the UI has been created, initializes the content.
* This creates the pages, selects the first one, setup sources and scan for local folders.
*/
private void postCreate() {
mUpdaterData.setWindowShell(getShell());
mTaskFactory = new ProgressTaskFactory(getShell());
mUpdaterData.setTaskFactory(mTaskFactory);
mUpdaterData.setImageFactory(new ImageFactory(getShell().getDisplay()));
setWindowImage(mAndroidSdkUpdater);
addPage(mAvdManagerPage, "Virtual Devices");
addPage(mLocalPackagePage, "Installed Packages");
addPage(mRemotePackagesPage, "Available Packages");
addExtraPages();
displayPage(0);
mPageList.setSelection(0);
setupSources();
initializeSettings();
mUpdaterData.notifyListeners();
}
/**
* Called by the main loop when the window has been disposed.
*/
private void dispose() {
mUpdaterData.getSources().saveUserSources(mUpdaterData.getSdkLog());
}
// --- page switching ---
/**
* Adds an instance of a page to the page list.
* <p/>
* Each page is a {@link Composite}. The title of the page is stored in the
* {@link Composite#getData()} field.
*/
private void addPage(Composite page, String title) {
page.setData(title);
mPages.add(page);
mPageList.add(title);
}
/**
* Adds all extra pages. For each page, instantiates an instance of the {@link Composite}
* using the constructor that takes a single {@link Composite} argument and then adds it
* to the page list.
*/
@SuppressWarnings("unchecked")
private void addExtraPages() {
if (mExtraPages == null) {
return;
}
for (Object[] extraPage : mExtraPages) {
String title = (String) extraPage[0];
Class<? extends Composite> clazz = (Class<? extends Composite>) extraPage[1];
// We want the constructor that takes a single Composite as parameter
Constructor<? extends Composite> cons;
try {
cons = clazz.getConstructor(new Class<?>[] { Composite.class });
Composite instance = cons.newInstance(new Object[] { mPagesRootComposite });
addPage(instance, title);
} catch (NoSuchMethodException e) {
// There is no such constructor.
mUpdaterData.getSdkLog().error(e,
"Failed to add extra page %1$s. Constructor args must be (Composite parent).", //$NON-NLS-1$
clazz.getSimpleName());
} catch (Exception e) {
// Log this instead of crashing the whole app.
mUpdaterData.getSdkLog().error(e,
"Failed to add extra page %1$s.", //$NON-NLS-1$
clazz.getSimpleName());
}
}
}
/**
* Callback invoked when an item is selected in the page list.
* If this is not an internal page change, displays the given page.
*/
private void onPageListSelected() {
if (mInternalPageChange == false) {
int index = mPageList.getSelectionIndex();
if (index >= 0) {
displayPage(index);
}
}
}
/**
* Displays the page at the given index.
*
* @param index An index between 0 and {@link #mPages}'s length - 1.
*/
private void displayPage(int index) {
Composite page = mPages.get(index);
if (page != null) {
mStackLayout.topControl = page;
mPagesRootComposite.layout(true);
if (!mInternalPageChange) {
mInternalPageChange = true;
mPageList.setSelection(index);
mInternalPageChange = false;
}
}
}
/**
* Used to initialize the sources.
*/
private void setupSources() {
RepoSources sources = mUpdaterData.getSources();
sources.add(new RepoSource(SdkRepository.URL_GOOGLE_SDK_REPO_SITE, false /*userSource*/));
String str = System.getenv("TEMP_SDK_URL"); // TODO STOPSHIP temporary remove before shipping
if (str != null) {
String[] urls = str.split(";");
for (String url : urls) {
sources.add(new RepoSource(url, false /*userSource*/));
}
}
// Load user sources
sources.loadUserSources(mUpdaterData.getSdkLog());
mRemotePackagesPage.onSdkChange();
}
/**
* Initializes settings.
* This must be called after addExtraPages(), which created a settings page.
* Iterate through all the pages to find the first (and supposedly unique) setting page,
* and use it to load and apply these settings.
*/
private void initializeSettings() {
SettingsController c = mUpdaterData.getSettingsController();
c.loadSettings();
c.applySettings();
for (Object page : mPages) {
if (page instanceof ISettingsPage) {
ISettingsPage settingsPage = (ISettingsPage) page;
c.setSettingsPage(settingsPage);
break;
}
}
}
// End of hiding from SWT Designer
//$hide<<$
}
| true | true | protected void createContents() {
mAndroidSdkUpdater = new Shell(mParentShell);
mAndroidSdkUpdater.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
onAndroidSdkUpdaterDispose(); //$hide$ (hide from SWT designer)
}
});
FillLayout fl;
mAndroidSdkUpdater.setLayout(fl = new FillLayout(SWT.HORIZONTAL));
fl.marginHeight = fl.marginWidth = 5;
mAndroidSdkUpdater.setMinimumSize(new Point(200, 50));
mAndroidSdkUpdater.setSize(745, 433);
mAndroidSdkUpdater.setText("Android SDK");
mSashForm = new SashForm(mAndroidSdkUpdater, SWT.NONE);
mPageList = new List(mSashForm, SWT.BORDER);
mPageList.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onPageListSelected(); //$hide$ (hide from SWT designer)
}
});
mPagesRootComposite = new Composite(mSashForm, SWT.NONE);
mStackLayout = new StackLayout();
mPagesRootComposite.setLayout(mStackLayout);
mAvdManagerPage = new AvdManagerPage(mPagesRootComposite, mUpdaterData);
mLocalPackagePage = new LocalPackagesPage(mPagesRootComposite, mUpdaterData);
mRemotePackagesPage = new RemotePackagesPage(mPagesRootComposite, mUpdaterData);
mSashForm.setWeights(new int[] {150, 576});
}
| protected void createContents() {
mAndroidSdkUpdater = new Shell(mParentShell, SWT.SHELL_TRIM);
mAndroidSdkUpdater.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
onAndroidSdkUpdaterDispose(); //$hide$ (hide from SWT designer)
}
});
FillLayout fl;
mAndroidSdkUpdater.setLayout(fl = new FillLayout(SWT.HORIZONTAL));
fl.marginHeight = fl.marginWidth = 5;
mAndroidSdkUpdater.setMinimumSize(new Point(200, 50));
mAndroidSdkUpdater.setSize(745, 433);
mAndroidSdkUpdater.setText("Android SDK");
mSashForm = new SashForm(mAndroidSdkUpdater, SWT.NONE);
mPageList = new List(mSashForm, SWT.BORDER);
mPageList.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onPageListSelected(); //$hide$ (hide from SWT designer)
}
});
mPagesRootComposite = new Composite(mSashForm, SWT.NONE);
mStackLayout = new StackLayout();
mPagesRootComposite.setLayout(mStackLayout);
mAvdManagerPage = new AvdManagerPage(mPagesRootComposite, mUpdaterData);
mLocalPackagePage = new LocalPackagesPage(mPagesRootComposite, mUpdaterData);
mRemotePackagesPage = new RemotePackagesPage(mPagesRootComposite, mUpdaterData);
mSashForm.setWeights(new int[] {150, 576});
}
|
diff --git a/src/share/classes/java/net/Inet6Address.java b/src/share/classes/java/net/Inet6Address.java
index 25d45a34..f5c3774c 100644
--- a/src/share/classes/java/net/Inet6Address.java
+++ b/src/share/classes/java/net/Inet6Address.java
@@ -1,584 +1,585 @@
/*
* @(#)Inet6Address.java 1.28 06/10/10
*
* Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package java.net;
import java.security.AccessController;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.InvalidObjectException;
import sun.security.action.*;
/**
* This class represents an Internet Protocol version 6 (IPv6) address.
* Defined by <a href="http://www.ietf.org/rfc/rfc2373.txt">
* <i>RFC 2373: IP Version 6 Addressing Architecture</i></a>.
*
* <h4> <A NAME="format">Textual representation of IP addresses<a> </h4>
*
* Textual representation of IPv6 address used as input to methods
* takes one of the following forms:
*
* <ol>
* <li><p> <A NAME="lform">The preferred form<a> is x:x:x:x:x:x:x:x, where the 'x's are
* the hexadecimal values of the eight 16-bit pieces of the
* address. This is the full form. For example,
*
* <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
* <tr><td><tt>1080:0:0:0:8:800:200C:417A</tt><td></tr>
* </table></blockquote>
*
* <p> Note that it is not necessary to write the leading zeros in
* an individual field. However, there must be at least one numeral
* in every field, except as described below.</li>
*
* <li><p> Due to some methods of allocating certain styles of IPv6
* addresses, it will be common for addresses to contain long
* strings of zero bits. In order to make writing addresses
* containing zero bits easier, a special syntax is available to
* compress the zeros. The use of "::" indicates multiple groups
* of 16-bits of zeros. The "::" can only appear once in an address.
* The "::" can also be used to compress the leading and/or trailing
* zeros in an address. For example,
*
* <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
* <tr><td><tt>1080::8:800:200C:417A</tt><td></tr>
* </table></blockquote>
*
* <li><p> An alternative form that is sometimes more convenient
* when dealing with a mixed environment of IPv4 and IPv6 nodes is
* x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values
* of the six high-order 16-bit pieces of the address, and the 'd's
* are the decimal values of the four low-order 8-bit pieces of the
* standard IPv4 representation address, for example,
*
* <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
* <tr><td><tt>::FFFF:129.144.52.38</tt><td></tr>
* <tr><td><tt>::129.144.52.38</tt><td></tr>
* </table></blockquote>
*
* <p> where "::FFFF:d.d.d.d" and "::d.d.d.d" are, respectively, the
* general forms of an IPv4-mapped IPv6 address and an
* IPv4-compatible IPv6 address. Note that the IPv4 portion must be
* in the "d.d.d.d" form. The following forms are invalid:
*
* <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
* <tr><td><tt>::FFFF:d.d.d</tt><td></tr>
* <tr><td><tt>::FFFF:d.d</tt><td></tr>
* <tr><td><tt>::d.d.d</tt><td></tr>
* <tr><td><tt>::d.d</tt><td></tr>
* </table></blockquote>
*
* <p> The following form:
*
* <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
* <tr><td><tt>::FFFF:d</tt><td></tr>
* </table></blockquote>
*
* <p> is valid, however it is an unconventional representation of
* the IPv4-compatible IPv6 address,
*
* <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
* <tr><td><tt>::255.255.0.d</tt><td></tr>
* </table></blockquote>
*
* <p> while "::d" corresponds to the general IPv6 address
* "0:0:0:0:0:0:0:d".</li>
* </ol>
*
* <p> For methods that return a textual representation as output
* value, the full form is used. Inet6Address will return the full
* form because it is unambiguous when used in combination with other
* textual data.
*
* <h4> Special IPv6 address </h4>
*
* <blockquote>
* <table cellspacing=2 summary="Description of IPv4-mapped address"> <tr><th valign=top><i>IPv4-mapped address</i></th>
* <td>Of the form::ffff:w.x.y.z, this IPv6 address is used to
* represent an IPv4 address. It allows the native program to
* use the same address data structure and also the same
* socket when communicating with both IPv4 and IPv6 nodes.
*
* <p>In InetAddress and Inet6Address, it is used for internal
* representation; it has no functional role. Java will never
* return an IPv4-mapped address. These classes can take an
* IPv4-mapped address as input, both in byte array and text
* representation. However, it will be converted into an IPv4
* address.</td></tr>
* </table></blockquote>
*/
public final
class Inet6Address extends InetAddress {
final static int INADDRSZ = 16;
/*
* cached scope_id - for link-local address use only.
*/
private transient int cached_scope_id = 0;
/**
* Holds a 128-bit (16 bytes) IPv6 address.
*
* @serial
*/
byte[] ipaddress;
private static final long serialVersionUID = 6880410070516793377L;
/*
* Perform initializations.
*/
static {
init();
}
Inet6Address() {
super();
hostName = null;
ipaddress = new byte[INADDRSZ];
family = IPv6;
}
Inet6Address(String hostName, byte addr[]) {
this.hostName = hostName;
if (addr.length == INADDRSZ) { // normal IPv6 address
family = IPv6;
ipaddress = (byte[])addr.clone();
}
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
ipaddress = (byte[])ipaddress.clone();
// Check that our invariants are satisfied
if (ipaddress.length != INADDRSZ) {
throw new InvalidObjectException("invalid address length: "+
ipaddress.length);
}
if (family != IPv6) {
throw new InvalidObjectException("invalid address family type");
}
}
/**
* Utility routine to check if the InetAddress is an IP multicast
* address. 11111111 at the start of the address identifies the
* address as being a multicast address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* an IP multicast address
* @since JDK1.1
*/
public boolean isMulticastAddress() {
return ((ipaddress[0] & 0xff) == 0xff);
}
/**
* Utility routine to check if the InetAddress in a wildcard address.
* @return a <code>boolean</code> indicating if the Inetaddress is
* a wildcard address.
* @since 1.4
*/
public boolean isAnyLocalAddress() {
byte test = 0x00;
for (int i = 0; i < INADDRSZ; i++) {
test |= ipaddress[i];
}
return (test == 0x00);
}
/**
* Utility routine to check if the InetAddress is a loopback address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* a loopback address; or false otherwise.
* @since 1.4
*/
public boolean isLoopbackAddress() {
byte test = 0x00;
for (int i = 0; i < 15; i++) {
test |= ipaddress[i];
}
return (test == 0x00) && (ipaddress[15] == 0x01);
}
/**
* Utility routine to check if the InetAddress is an link local address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* a link local address; or false if address is not a link local unicast address.
* @since 1.4
*/
public boolean isLinkLocalAddress() {
return ((ipaddress[0] & 0xff) == 0xfe
&& (ipaddress[1] & 0xc0) == 0x80);
}
/**
* Utility routine to check if the InetAddress is a site local address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* a site local address; or false if address is not a site local unicast address.
* @since 1.4
*/
public boolean isSiteLocalAddress() {
return ((ipaddress[0] & 0xff) == 0xfe
&& (ipaddress[1] & 0xc0) == 0xc0);
}
/**
* Utility routine to check if the multicast address has global scope.
*
* @return a <code>boolean</code> indicating if the address has
* is a multicast address of global scope, false if it is not
* of global scope or it is not a multicast address
* @since 1.4
*/
public boolean isMCGlobal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x0e);
}
/**
* Utility routine to check if the multicast address has node scope.
*
* @return a <code>boolean</code> indicating if the address has
* is a multicast address of node-local scope, false if it is not
* of node-local scope or it is not a multicast address
* @since 1.4
*/
public boolean isMCNodeLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x01);
}
/**
* Utility routine to check if the multicast address has link scope.
*
* @return a <code>boolean</code> indicating if the address has
* is a multicast address of link-local scope, false if it is not
* of link-local scope or it is not a multicast address
* @since 1.4
*/
public boolean isMCLinkLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x02);
}
/**
* Utility routine to check if the multicast address has site scope.
*
* @return a <code>boolean</code> indicating if the address has
* is a multicast address of site-local scope, false if it is not
* of site-local scope or it is not a multicast address
* @since 1.4
*/
public boolean isMCSiteLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x05);
}
/**
* Utility routine to check if the multicast address has organization scope.
*
* @return a <code>boolean</code> indicating if the address has
* is a multicast address of organization-local scope,
* false if it is not of organization-local scope
* or it is not a multicast address
* @since 1.4
*/
public boolean isMCOrgLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x08);
}
/**
* Returns the raw IP address of this <code>InetAddress</code>
* object. The result is in network byte order: the highest order
* byte of the address is in <code>getAddress()[0]</code>.
*
* @return the raw IP address of this object.
*/
public byte[] getAddress() {
return (byte[])ipaddress.clone();
}
/**
* Returns the IP address string in textual presentation.
*
* @return the raw IP address in a string format.
*/
public String getHostAddress() {
return numericToTextFormat(ipaddress);
}
/**
* Returns a hashcode for this IP address.
*
* @return a hash code value for this IP address.
*/
public int hashCode() {
if (ipaddress != null) {
int hash = 0;
int i=0;
while (i<INADDRSZ) {
int j=0;
int component=0;
while (j<4 && i<INADDRSZ) {
component = (component << 8) + ipaddress[i];
j++;
i++;
}
hash += component;
}
return hash;
} else {
return 0;
}
}
/**
* Compares this object against the specified object.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and it represents the same IP address as
* this object.
* <p>
* Two instances of <code>InetAddress</code> represent the same IP
* address if the length of the byte arrays returned by
* <code>getAddress</code> is the same for both, and each of the
* array components is the same for the byte arrays.
*
* @param obj the object to compare against.
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
* @see java.net.InetAddress#getAddress()
*/
public boolean equals(Object obj) {
if (obj == null ||
!(obj instanceof Inet6Address))
return false;
Inet6Address inetAddr = (Inet6Address)obj;
for (int i = 0; i < INADDRSZ; i++) {
if (ipaddress[i] != inetAddr.ipaddress[i])
return false;
}
return true;
}
/**
* Utility routine to check if the InetAddress is an
* IPv4 mapped IPv6 address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* an IPv4 mapped IPv6 address; or false if address is IPv4 address.
*/
static boolean isIPv4MappedAddress(byte[] addr) {
if (addr.length < INADDRSZ) {
return false;
}
if ((addr[0] == 0x00) && (addr[1] == 0x00) &&
(addr[2] == 0x00) && (addr[3] == 0x00) &&
(addr[4] == 0x00) && (addr[5] == 0x00) &&
(addr[6] == 0x00) && (addr[7] == 0x00) &&
(addr[8] == 0x00) && (addr[9] == 0x00) &&
(addr[10] == (byte)0xff) &&
(addr[11] == (byte)0xff)) {
return true;
}
return false;
}
static byte[] convertFromIPv4MappedAddress(byte[] addr) {
if (isIPv4MappedAddress(addr)) {
byte[] newAddr = new byte[Inet4Address.INADDRSZ];
System.arraycopy(addr, 12, newAddr, 0, Inet4Address.INADDRSZ);
return newAddr;
}
return null;
}
/**
* Utility routine to check if the InetAddress is an
* IPv4 compatible IPv6 address.
*
* @return a <code>boolean</code> indicating if the InetAddress is
* an IPv4 compatible IPv6 address; or false if address is IPv4 address.
* @since 1.4
*/
public boolean isIPv4CompatibleAddress() {
if ((ipaddress[0] == 0x00) && (ipaddress[1] == 0x00) &&
(ipaddress[2] == 0x00) && (ipaddress[3] == 0x00) &&
(ipaddress[4] == 0x00) && (ipaddress[5] == 0x00) &&
(ipaddress[6] == 0x00) && (ipaddress[7] == 0x00) &&
(ipaddress[8] == 0x00) && (ipaddress[9] == 0x00) &&
(ipaddress[10] == 0x00) && (ipaddress[11] == 0x00)) {
return true;
}
return false;
}
// Utilities
private final static int INT16SZ = 2;
/*
* Convert IPv6 binary address into presentation (printable) format.
*
* @param src a byte array representing the IPv6 numeric address
* @return a String representing an IPv6 address in
* textual representation format
* @since 1.4
*/
static String numericToTextFormat(byte[] src)
{
StringBuffer sb = new StringBuffer(39);
for (int i = 0; i < (INADDRSZ / INT16SZ); i++) {
sb.append(Integer.toHexString(((src[i<<1]<<8) & 0xff00)
| (src[(i<<1)+1] & 0xff)));
if (i < (INADDRSZ / INT16SZ) -1 ) {
sb.append(":");
}
}
return sb.toString();
}
/*
* Convert IPv6 presentation level address to network order binary form.
* credit:
* Converted from C code from Solaris 8 (inet_pton)
*
* @param src a String representing an IPv6 address in textual format
* @return a byte array representing the IPv6 numeric address
* @since 1.4
*/
static byte[] textToNumericFormat(String src)
{
- if (src.length() == 0) {
+ // Shortest valid string is "::", hence at least 2 chars
+ if (src.length() < 2) {
return null;
}
int colonp;
char ch;
boolean saw_xdigit;
int val;
char[] srcb = src.toCharArray();
byte[] dst = new byte[INADDRSZ];
colonp = -1;
int i = 0, j = 0;
/* Leading :: requires some special handling. */
if (srcb[i] == ':')
if (srcb[++i] != ':')
return null;
int curtok = i;
saw_xdigit = false;
val = 0;
while (i < srcb.length) {
ch = srcb[i++];
int chval = Character.digit(ch, 16);
if (chval != -1) {
val <<= 4;
val |= chval;
if (val > 0xffff)
return null;
saw_xdigit = true;
continue;
}
if (ch == ':') {
curtok = i;
if (!saw_xdigit) {
if (colonp != -1)
return null;
colonp = j;
continue;
} else if (i == srcb.length) {
return null;
}
if (j + INT16SZ > INADDRSZ)
return null;
dst[j++] = (byte) ((val >> 8) & 0xff);
dst[j++] = (byte) (val & 0xff);
saw_xdigit = false;
val = 0;
continue;
}
if (ch == '.' && ((j + Inet4Address.INADDRSZ) <= INADDRSZ)) {
byte[] v4addr = Inet4Address.textToNumericFormat(src.substring(curtok));
if (v4addr == null) {
return null;
}
for (int k = 0; k < Inet4Address.INADDRSZ; k++) {
dst[j++] = v4addr[k];
}
saw_xdigit = false;
break; /* '\0' was seen by inet_pton4(). */
}
return null;
}
if (saw_xdigit) {
if (j + INT16SZ > INADDRSZ)
return null;
dst[j++] = (byte) ((val >> 8) & 0xff);
dst[j++] = (byte) (val & 0xff);
}
if (colonp != -1) {
int n = j - colonp;
if (j == INADDRSZ)
return null;
for (i = 1; i <= n; i++) {
dst[INADDRSZ - i] = dst[colonp + n - i];
dst[colonp + n - i] = 0;
}
j = INADDRSZ;
}
if (j != INADDRSZ)
return null;
byte[] newdst = convertFromIPv4MappedAddress(dst);
if (newdst != null) {
return newdst;
} else {
return dst;
}
}
/**
* Perform class load-time initializations.
*/
private static native void init();
}
| true | true | static byte[] textToNumericFormat(String src)
{
if (src.length() == 0) {
return null;
}
int colonp;
char ch;
boolean saw_xdigit;
int val;
char[] srcb = src.toCharArray();
byte[] dst = new byte[INADDRSZ];
colonp = -1;
int i = 0, j = 0;
/* Leading :: requires some special handling. */
if (srcb[i] == ':')
if (srcb[++i] != ':')
return null;
int curtok = i;
saw_xdigit = false;
val = 0;
while (i < srcb.length) {
ch = srcb[i++];
int chval = Character.digit(ch, 16);
if (chval != -1) {
val <<= 4;
val |= chval;
if (val > 0xffff)
return null;
saw_xdigit = true;
continue;
}
if (ch == ':') {
curtok = i;
if (!saw_xdigit) {
if (colonp != -1)
return null;
colonp = j;
continue;
} else if (i == srcb.length) {
return null;
}
if (j + INT16SZ > INADDRSZ)
return null;
dst[j++] = (byte) ((val >> 8) & 0xff);
dst[j++] = (byte) (val & 0xff);
saw_xdigit = false;
val = 0;
continue;
}
if (ch == '.' && ((j + Inet4Address.INADDRSZ) <= INADDRSZ)) {
byte[] v4addr = Inet4Address.textToNumericFormat(src.substring(curtok));
if (v4addr == null) {
return null;
}
for (int k = 0; k < Inet4Address.INADDRSZ; k++) {
dst[j++] = v4addr[k];
}
saw_xdigit = false;
break; /* '\0' was seen by inet_pton4(). */
}
return null;
}
if (saw_xdigit) {
if (j + INT16SZ > INADDRSZ)
return null;
dst[j++] = (byte) ((val >> 8) & 0xff);
dst[j++] = (byte) (val & 0xff);
}
if (colonp != -1) {
int n = j - colonp;
if (j == INADDRSZ)
return null;
for (i = 1; i <= n; i++) {
dst[INADDRSZ - i] = dst[colonp + n - i];
dst[colonp + n - i] = 0;
}
j = INADDRSZ;
}
if (j != INADDRSZ)
return null;
byte[] newdst = convertFromIPv4MappedAddress(dst);
if (newdst != null) {
return newdst;
} else {
return dst;
}
}
| static byte[] textToNumericFormat(String src)
{
// Shortest valid string is "::", hence at least 2 chars
if (src.length() < 2) {
return null;
}
int colonp;
char ch;
boolean saw_xdigit;
int val;
char[] srcb = src.toCharArray();
byte[] dst = new byte[INADDRSZ];
colonp = -1;
int i = 0, j = 0;
/* Leading :: requires some special handling. */
if (srcb[i] == ':')
if (srcb[++i] != ':')
return null;
int curtok = i;
saw_xdigit = false;
val = 0;
while (i < srcb.length) {
ch = srcb[i++];
int chval = Character.digit(ch, 16);
if (chval != -1) {
val <<= 4;
val |= chval;
if (val > 0xffff)
return null;
saw_xdigit = true;
continue;
}
if (ch == ':') {
curtok = i;
if (!saw_xdigit) {
if (colonp != -1)
return null;
colonp = j;
continue;
} else if (i == srcb.length) {
return null;
}
if (j + INT16SZ > INADDRSZ)
return null;
dst[j++] = (byte) ((val >> 8) & 0xff);
dst[j++] = (byte) (val & 0xff);
saw_xdigit = false;
val = 0;
continue;
}
if (ch == '.' && ((j + Inet4Address.INADDRSZ) <= INADDRSZ)) {
byte[] v4addr = Inet4Address.textToNumericFormat(src.substring(curtok));
if (v4addr == null) {
return null;
}
for (int k = 0; k < Inet4Address.INADDRSZ; k++) {
dst[j++] = v4addr[k];
}
saw_xdigit = false;
break; /* '\0' was seen by inet_pton4(). */
}
return null;
}
if (saw_xdigit) {
if (j + INT16SZ > INADDRSZ)
return null;
dst[j++] = (byte) ((val >> 8) & 0xff);
dst[j++] = (byte) (val & 0xff);
}
if (colonp != -1) {
int n = j - colonp;
if (j == INADDRSZ)
return null;
for (i = 1; i <= n; i++) {
dst[INADDRSZ - i] = dst[colonp + n - i];
dst[colonp + n - i] = 0;
}
j = INADDRSZ;
}
if (j != INADDRSZ)
return null;
byte[] newdst = convertFromIPv4MappedAddress(dst);
if (newdst != null) {
return newdst;
} else {
return dst;
}
}
|
diff --git a/src/com/stuffwithstuff/magpie/parser/DoParser.java b/src/com/stuffwithstuff/magpie/parser/DoParser.java
index 38a8cad9..83b22f69 100644
--- a/src/com/stuffwithstuff/magpie/parser/DoParser.java
+++ b/src/com/stuffwithstuff/magpie/parser/DoParser.java
@@ -1,11 +1,11 @@
package com.stuffwithstuff.magpie.parser;
import com.stuffwithstuff.magpie.ast.Expr;
public class DoParser implements PrefixParser {
@Override
public Expr parse(MagpieParser parser, Token token) {
- Expr body = parser.parseExpression();
+ Expr body = parser.parseEndBlock();
return Expr.scope(body);
}
}
| true | true | public Expr parse(MagpieParser parser, Token token) {
Expr body = parser.parseExpression();
return Expr.scope(body);
}
| public Expr parse(MagpieParser parser, Token token) {
Expr body = parser.parseEndBlock();
return Expr.scope(body);
}
|
diff --git a/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java b/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java
index 0a8c6b26..c623154c 100644
--- a/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java
+++ b/atlassian-plugins-refimpl/src/main/java/com/atlassian/plugin/refimpl/ContainerManager.java
@@ -1,187 +1,192 @@
package com.atlassian.plugin.refimpl;
import com.atlassian.plugin.*;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.event.impl.DefaultPluginEventManager;
import com.atlassian.plugin.loaders.DirectoryPluginLoader;
import com.atlassian.plugin.loaders.PluginLoader;
import com.atlassian.plugin.osgi.container.OsgiContainerManager;
import com.atlassian.plugin.osgi.container.PackageScannerConfiguration;
import com.atlassian.plugin.osgi.container.felix.FelixOsgiContainerManager;
import com.atlassian.plugin.osgi.container.impl.DefaultPackageScannerConfiguration;
import com.atlassian.plugin.osgi.factory.OsgiBundleFactory;
import com.atlassian.plugin.osgi.factory.OsgiPluginFactory;
import com.atlassian.plugin.osgi.hostcomponents.ComponentRegistrar;
import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider;
import com.atlassian.plugin.refimpl.servlet.*;
import com.atlassian.plugin.refimpl.webresource.SimpleWebResourceIntegration;
import com.atlassian.plugin.repositories.FilePluginInstaller;
import com.atlassian.plugin.servlet.*;
import com.atlassian.plugin.servlet.descriptors.ServletContextParamModuleDescriptor;
import com.atlassian.plugin.store.MemoryPluginStateStore;
import com.atlassian.plugin.webresource.WebResourceManager;
import com.atlassian.plugin.webresource.WebResourceManagerImpl;
import com.atlassian.plugin.webresource.WebResourceModuleDescriptor;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.*;
/**
* A simple class that behaves like Spring's ContianerManager class.
*/
public class ContainerManager
{
private final ServletModuleManager servletModuleManager;
private final WebResourceManager webResourceManager;
private final OsgiContainerManager osgiContainerManager;
private final DefaultPluginManager pluginManager;
private final PluginEventManager pluginEventManager;
private final HostComponentProvider hostComponentProvider;
private final DefaultModuleDescriptorFactory moduleDescriptorFactory;
private final Map<Class,Object> publicContainer;
private static ContainerManager instance;
private List<DownloadStrategy> downloadStrategies;
public ContainerManager(ServletContext servletContext)
{
instance = this;
pluginEventManager = new DefaultPluginEventManager();
servletModuleManager = new DefaultServletModuleManager(pluginEventManager);
webResourceManager = new WebResourceManagerImpl(new SimpleWebResourceIntegration(servletContext));
DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration();
List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes());
packageIncludes.add("org.bouncycastle*");
scannerConfig.setPackageIncludes(packageIncludes);
publicContainer = new HashMap<Class,Object>();
hostComponentProvider = new SimpleHostComponentProvider();
osgiContainerManager = new FelixOsgiContainerManager(
new File(servletContext.getRealPath("/WEB-INF/framework-bundles")),
scannerConfig, hostComponentProvider, pluginEventManager);
OsgiPluginFactory osgiPluginDeployer = new OsgiPluginFactory(PluginManager.PLUGIN_DESCRIPTOR_FILENAME,
osgiContainerManager);
OsgiBundleFactory osgiBundleDeployer = new OsgiBundleFactory(osgiContainerManager);
DirectoryPluginLoader directoryPluginLoader = new DirectoryPluginLoader(
new File(servletContext.getRealPath("/WEB-INF/plugins")),
Arrays.asList(osgiPluginDeployer, osgiBundleDeployer),
pluginEventManager);
/*BundledPluginLoader bundledPluginLoader = new BundledPluginLoader(
getClass().getResource("/atlassian-bundled-plugins.zip"),
new File(servletContext.getRealPath("/WEB-INF/bundled-plugins")),
Arrays.asList(osgiPluginDeployer, osgiBundleDeployer),
pluginEventManager);
*/
moduleDescriptorFactory = new DefaultModuleDescriptorFactory();
moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class);
pluginManager = new DefaultPluginManager(new MemoryPluginStateStore(), Arrays.<PluginLoader>asList(/*bundledPluginLoader, */directoryPluginLoader),
moduleDescriptorFactory, pluginEventManager);
- pluginManager.setPluginInstaller(new FilePluginInstaller(new File(servletContext.getRealPath("/WEB-INF/plugins"))));
+ File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins"));
+ if (!pluginDir.exists())
+ {
+ pluginDir.mkdirs();
+ }
+ pluginManager.setPluginInstaller(new FilePluginInstaller(pluginDir));
publicContainer.put(PluginController.class, pluginManager);
publicContainer.put(PluginAccessor.class, pluginManager);
publicContainer.put(PluginEventManager.class, pluginEventManager);
publicContainer.put(Map.class, publicContainer);
try {
pluginManager.init();
}
catch (PluginParseException e)
{
e.printStackTrace();
}
downloadStrategies = new ArrayList<DownloadStrategy>();
PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload();
pluginDownloadStrategy.setPluginManager(pluginManager);
pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver());
pluginDownloadStrategy.setCharacterEncoding("UTF-8");
downloadStrategies.add(pluginDownloadStrategy);
}
public static synchronized void setInstance(ContainerManager mgr)
{
instance = mgr;
}
public static synchronized ContainerManager getInstance()
{
return instance;
}
public ServletModuleManager getServletModuleManager()
{
return servletModuleManager;
}
public OsgiContainerManager getOsgiContainerManager()
{
return osgiContainerManager;
}
public PluginManager getPluginManager()
{
return pluginManager;
}
public HostComponentProvider getHostComponentProvider()
{
return hostComponentProvider;
}
public ModuleDescriptorFactory getModuleDescriptorFactory()
{
return moduleDescriptorFactory;
}
public List<DownloadStrategy> getDownloadStrategies()
{
return downloadStrategies;
}
/**
* A simple content type resolver that can identify css and js resources.
*/
private class SimpleContentTypeResolver implements ContentTypeResolver
{
private final Map<String, String> mimeTypes;
SimpleContentTypeResolver()
{
Map<String, String> types = new HashMap<String, String>();
types.put("js", "application/x-javascript");
types.put("css", "text/css");
mimeTypes = Collections.unmodifiableMap(types);
}
public String getContentType(String requestUrl)
{
String extension = requestUrl.substring(requestUrl.lastIndexOf('.'));
return mimeTypes.get(extension);
}
}
private class SimpleHostComponentProvider implements HostComponentProvider
{
public void provide(ComponentRegistrar componentRegistrar) {
for (Map.Entry<Class,Object> entry : publicContainer.entrySet())
{
String name = entry.getKey().getSimpleName();
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
componentRegistrar.register(entry.getKey()).forInstance(entry.getValue()).withName(name);
}
componentRegistrar.register(WebResourceManager.class).forInstance(webResourceManager).withName("webResourceManager");
}
}
}
| true | true | public ContainerManager(ServletContext servletContext)
{
instance = this;
pluginEventManager = new DefaultPluginEventManager();
servletModuleManager = new DefaultServletModuleManager(pluginEventManager);
webResourceManager = new WebResourceManagerImpl(new SimpleWebResourceIntegration(servletContext));
DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration();
List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes());
packageIncludes.add("org.bouncycastle*");
scannerConfig.setPackageIncludes(packageIncludes);
publicContainer = new HashMap<Class,Object>();
hostComponentProvider = new SimpleHostComponentProvider();
osgiContainerManager = new FelixOsgiContainerManager(
new File(servletContext.getRealPath("/WEB-INF/framework-bundles")),
scannerConfig, hostComponentProvider, pluginEventManager);
OsgiPluginFactory osgiPluginDeployer = new OsgiPluginFactory(PluginManager.PLUGIN_DESCRIPTOR_FILENAME,
osgiContainerManager);
OsgiBundleFactory osgiBundleDeployer = new OsgiBundleFactory(osgiContainerManager);
DirectoryPluginLoader directoryPluginLoader = new DirectoryPluginLoader(
new File(servletContext.getRealPath("/WEB-INF/plugins")),
Arrays.asList(osgiPluginDeployer, osgiBundleDeployer),
pluginEventManager);
/*BundledPluginLoader bundledPluginLoader = new BundledPluginLoader(
getClass().getResource("/atlassian-bundled-plugins.zip"),
new File(servletContext.getRealPath("/WEB-INF/bundled-plugins")),
Arrays.asList(osgiPluginDeployer, osgiBundleDeployer),
pluginEventManager);
*/
moduleDescriptorFactory = new DefaultModuleDescriptorFactory();
moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class);
pluginManager = new DefaultPluginManager(new MemoryPluginStateStore(), Arrays.<PluginLoader>asList(/*bundledPluginLoader, */directoryPluginLoader),
moduleDescriptorFactory, pluginEventManager);
pluginManager.setPluginInstaller(new FilePluginInstaller(new File(servletContext.getRealPath("/WEB-INF/plugins"))));
publicContainer.put(PluginController.class, pluginManager);
publicContainer.put(PluginAccessor.class, pluginManager);
publicContainer.put(PluginEventManager.class, pluginEventManager);
publicContainer.put(Map.class, publicContainer);
try {
pluginManager.init();
}
catch (PluginParseException e)
{
e.printStackTrace();
}
downloadStrategies = new ArrayList<DownloadStrategy>();
PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload();
pluginDownloadStrategy.setPluginManager(pluginManager);
pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver());
pluginDownloadStrategy.setCharacterEncoding("UTF-8");
downloadStrategies.add(pluginDownloadStrategy);
}
| public ContainerManager(ServletContext servletContext)
{
instance = this;
pluginEventManager = new DefaultPluginEventManager();
servletModuleManager = new DefaultServletModuleManager(pluginEventManager);
webResourceManager = new WebResourceManagerImpl(new SimpleWebResourceIntegration(servletContext));
DefaultPackageScannerConfiguration scannerConfig = new DefaultPackageScannerConfiguration();
List<String> packageIncludes = new ArrayList<String>(scannerConfig.getPackageIncludes());
packageIncludes.add("org.bouncycastle*");
scannerConfig.setPackageIncludes(packageIncludes);
publicContainer = new HashMap<Class,Object>();
hostComponentProvider = new SimpleHostComponentProvider();
osgiContainerManager = new FelixOsgiContainerManager(
new File(servletContext.getRealPath("/WEB-INF/framework-bundles")),
scannerConfig, hostComponentProvider, pluginEventManager);
OsgiPluginFactory osgiPluginDeployer = new OsgiPluginFactory(PluginManager.PLUGIN_DESCRIPTOR_FILENAME,
osgiContainerManager);
OsgiBundleFactory osgiBundleDeployer = new OsgiBundleFactory(osgiContainerManager);
DirectoryPluginLoader directoryPluginLoader = new DirectoryPluginLoader(
new File(servletContext.getRealPath("/WEB-INF/plugins")),
Arrays.asList(osgiPluginDeployer, osgiBundleDeployer),
pluginEventManager);
/*BundledPluginLoader bundledPluginLoader = new BundledPluginLoader(
getClass().getResource("/atlassian-bundled-plugins.zip"),
new File(servletContext.getRealPath("/WEB-INF/bundled-plugins")),
Arrays.asList(osgiPluginDeployer, osgiBundleDeployer),
pluginEventManager);
*/
moduleDescriptorFactory = new DefaultModuleDescriptorFactory();
moduleDescriptorFactory.addModuleDescriptor("servlet", SimpleServletModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-filter", SimpleFilterModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-param", ServletContextParamModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("servlet-context-listener", SimpleContextListenerModuleDescriptor.class);
moduleDescriptorFactory.addModuleDescriptor("web-resource", WebResourceModuleDescriptor.class);
pluginManager = new DefaultPluginManager(new MemoryPluginStateStore(), Arrays.<PluginLoader>asList(/*bundledPluginLoader, */directoryPluginLoader),
moduleDescriptorFactory, pluginEventManager);
File pluginDir = new File(servletContext.getRealPath("/WEB-INF/plugins"));
if (!pluginDir.exists())
{
pluginDir.mkdirs();
}
pluginManager.setPluginInstaller(new FilePluginInstaller(pluginDir));
publicContainer.put(PluginController.class, pluginManager);
publicContainer.put(PluginAccessor.class, pluginManager);
publicContainer.put(PluginEventManager.class, pluginEventManager);
publicContainer.put(Map.class, publicContainer);
try {
pluginManager.init();
}
catch (PluginParseException e)
{
e.printStackTrace();
}
downloadStrategies = new ArrayList<DownloadStrategy>();
PluginResourceDownload pluginDownloadStrategy = new PluginResourceDownload();
pluginDownloadStrategy.setPluginManager(pluginManager);
pluginDownloadStrategy.setContentTypeResolver(new SimpleContentTypeResolver());
pluginDownloadStrategy.setCharacterEncoding("UTF-8");
downloadStrategies.add(pluginDownloadStrategy);
}
|
diff --git a/src/main/java/org/odlabs/wiquery/ui/datepicker/InlineDatePicker.java b/src/main/java/org/odlabs/wiquery/ui/datepicker/InlineDatePicker.java
index e142159f..913368b3 100644
--- a/src/main/java/org/odlabs/wiquery/ui/datepicker/InlineDatePicker.java
+++ b/src/main/java/org/odlabs/wiquery/ui/datepicker/InlineDatePicker.java
@@ -1,1130 +1,1129 @@
/*
* Copyright (c) 2009 WiQuery team
*
* 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 org.odlabs.wiquery.ui.datepicker;
import java.util.Locale;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.odlabs.wiquery.core.commons.IWiQueryPlugin;
import org.odlabs.wiquery.core.commons.WiQueryResourceManager;
import org.odlabs.wiquery.core.javascript.JsQuery;
import org.odlabs.wiquery.core.javascript.JsScope;
import org.odlabs.wiquery.core.javascript.JsStatement;
import org.odlabs.wiquery.core.options.ListItemOptions;
import org.odlabs.wiquery.core.options.LiteralOption;
import org.odlabs.wiquery.core.options.Options;
import org.odlabs.wiquery.ui.commons.WiQueryUIPlugin;
import org.odlabs.wiquery.ui.core.JsScopeUiEvent;
import org.odlabs.wiquery.ui.datepicker.DatePicker.ShowOnEnum;
import org.odlabs.wiquery.ui.datepicker.scope.JsScopeUiDatePickerDateTextEvent;
import org.odlabs.wiquery.ui.datepicker.scope.JsScopeUiDatePickerEvent;
import org.odlabs.wiquery.ui.datepicker.scope.JsScopeUiDatePickerOnChangeEvent;
/**
* $Id$
* <p>
* An inline DatePicker as described in
* <a href="http://jqueryui.com/demos/datepicker/#inline">here</a>.
* </p>
*
*
*
* @author Lionel Armanet
* @author Ernesto Reinaldo Barreiro
* @since 1.0.2
*/
@WiQueryUIPlugin
public class InlineDatePicker<T> extends WebMarkupContainer implements IWiQueryPlugin {
// Constants
/** Constant of serialization */
private static final long serialVersionUID = 2L;
// Properties
private DatePickerOptions options;
/**Constructor
* @param id Markup identifiant
*/
public InlineDatePicker(String id) {
super(id);
setOutputMarkupId(true);
options = new DatePickerOptions(this);
}
/*
* (non-Javadoc)
* @see org.apache.wicket.Component#detachModel()
*/
@Override
protected void detachModel() {
super.detachModel();
options.detach();
}
/* (non-Javadoc)
* @see org.odlabs.wiquery.core.commons.IWiQueryPlugin#contribute(org.odlabs.wiquery.core.commons.WiQueryResourceManager)
*/
public void contribute(WiQueryResourceManager wiQueryResourceManager) {
wiQueryResourceManager.addJavaScriptResource(DatePickerJavaScriptResourceReference.get());
Locale locale = getLocale();
- if(locale != null && !Locale.ENGLISH.getLanguage().equals(locale.getLanguage())){ // #issue 24
+ if (locale != null && !getLocale().equals(Locale.US))
wiQueryResourceManager
.addJavaScriptResource(new DatePickerLanguageResourceReference(
locale));
- }
}
/* (non-Javadoc)
* @see org.odlabs.wiquery.core.commons.IWiQueryPlugin#statement()
*/
public JsStatement statement() {
return new JsQuery(this).$().chain("datepicker",
options.getOptions().getJavaScriptOptions());
}
/**Method retrieving the options of the component
* @return the options
*/
protected Options getOptions() {
return options.getOptions();
}
/*---- Options section ---*/
/**The jQuery selector for another field that is to be updated with the
* selected date from the datepicker. Use the altFormat setting below to
* change the format of the date within this field. Leave as blank for no
* alternate field.
* @param altField
* @return instance of the current component
*/
public InlineDatePicker<T> setAltField(String altField) {
this.options.setAltField(altField);
return this;
}
/**
* @return the altField option value
*/
public String getAltField() {
return this.options.getAltField();
}
/**The dateFormat to be used for the altField option. This allows one date
* format to be shown to the user for selection purposes, while a different
* format is actually sent behind the scenes.
*
* The format can be combinations of the following:
* <ul>
* <li>d - day of month (no leading zero)</li>
* <li>dd - day of month (two digit)</li>
* <li>o - day of the year (no leading zeros)</li>
* <li>oo - day of the year (three digit)</li>
* <li>D - day name short</li>
* <li>DD - day name long</li>
* <li>m - month of year (no leading zero)</li>
* <li>mm - month of year (two digit)</li>
* <li>M - month name short</li>
* <li>MM - month name long</li>
* <li>y - year (two digit)</li>
* <li>yy - year (four digit)</li>
* <li>@ - Unix timestamp (ms since 01/01/1970)</li>
* <li>'...' - literal text</li>
* <li>'' - single quote</li>
* <li>anything else - literal text</li>
* </ul>
*
* @param altFormat
* @return instance of the current component
*/
public InlineDatePicker<T> setAltFormat(String altFormat) {
this.options.setAltFormat(altFormat);
return this;
}
/**
* @return the altFormat option value
*/
public String getAltFormat() {
return this.options.getAltFormat();
}
/**Set's the text to display after each date field, e.g. to show the required format.
* @param appendText
* @return instance of the current component
*/
public InlineDatePicker<T> setAppendText(String appendText) {
this.options.setAppendText(appendText);
return this;
}
/**
* @return the appendText option value
*/
public String getAppendText() {
return this.options.getAppendText();
}
/**
* Set to true to automatically resize the input field to accomodate dates
* in the current dateFormat.
* @return instance of the current component
*/
public InlineDatePicker<T> setAutoSize(boolean autoSize) {
options.setAutoSize(autoSize);
return this;
}
/**
* @return the autoSize option
*/
public boolean isAutoSize() {
return options.isAutoSize();
}
/**Set's URL for the popup button image. If set, button text becomes the alt
* value and is not directly displayed.
* @param buttonImage
* @return instance of the current component
*/
public InlineDatePicker<T> setButtonImage(String buttonImage) {
this.options.setButtonImage(buttonImage);
return this;
}
/**
* @return the buttonImage option value
*/
public String getButtonImage() {
return this.options.getButtonImage();
}
/**Set to true to place an image after the field to use as the trigger
* without it appearing on a button.
* @param buttonImageOnly
* @return instance of the current component
*/
public InlineDatePicker<T> setButtonImageOnly(boolean buttonImageOnly) {
options.setButtonImageOnly(buttonImageOnly);
return this;
}
/**
* @return the buttonImageOnly option value
*/
public boolean isButtonImageOnly() {
return this.options.isButtonImageOnly();
}
/**Set's the text to display on the trigger button. Use in conjunction with
* showOn equal to 'button' or 'both'.
* @param buttonText
* @return instance of the current component
*/
public InlineDatePicker<T> setButtonText(String buttonText) {
this.options.setButtonText(buttonText);
return this;
}
/**
* @return the buttonText option value
*/
public String getButtonText() {
return this.options.getButtonText();
}
/**A function to calculate the week of the year for a given date. The default
* implementation uses the ISO 8601 definition: weeks start on a Monday;
* the first week of the year contains the first Thursday of the year.
*
* Default: $.datepicker.iso8601Week
*
* @param calculateWeek
* @return instance of the current component
*/
public InlineDatePicker<T> setCalculateWeek(JsScope calculateWeek) {
this.options.setCalculateWeek(calculateWeek);
return this;
}
/**
* Sets if the date's month is selectable in a drop down list or not.
* @return instance of the current component
*/
public InlineDatePicker<T> setChangeMonth(boolean changeMonth) {
options.setChangeMonth(changeMonth);
return this;
}
/**
* Returns true if the date's month is selectable in a drop down list,
* returns false otherwise.
*/
public boolean isChangeMonth() {
return this.options.isChangeMonth();
}
/**The text to display for the week of the year column heading. This attribute
* is one of the regionalisation attributes. Use showWeek to display this column.
* @param weekHeader
* @return instance of the current component
*/
public InlineDatePicker<T> setWeekHeader(String weekHeader) {
this.options.setWeekHeader(weekHeader);
return this;
}
/**
* @return the weekHeader option value
*/
public String getWeekHeader() {
return options.getWeekHeader();
}
/**
* Sets the selectable year range. This range can either be defined by a
* start year and an end year (like 2001 to 2010), or it can be defined
* relatively to the today's date (like current-10 to current+10).
*
* @param yearRange
* @return instance of the current component
*/
public InlineDatePicker<T> setYearRange(DatePickerYearRange yearRange) {
options.setYearRange(yearRange);
return this;
}
/**
* @return the year range valu option
*/
public DatePickerYearRange getYearRange() {
return this.options.getYearRange();
}
/**Additional text to display after the year in the month headers. This
* attribute is one of the regionalisation attributes.
* @param yearSuffix
* @return instance of the current component
*/
public InlineDatePicker<T> setYearSuffix(String yearSuffix) {
this.options.setYearSuffix(yearSuffix);
return this;
}
/**
* @return the yearSuffix option value
*/
public String getYearSuffix() {
return options.getYearSuffix();
}
/**
* Sets if the date's year is selectable in a drop down list or not.
* @return instance of the current component
*/
public InlineDatePicker<T> setChangeYear(boolean changeYear) {
options.setChangeYear(changeYear);
return this;
}
/**
* Returns true if the date's year is selectable in a drop down list,
* returns false otherwise.
*/
public boolean isChangeYear() {
return this.options.isChangeYear();
}
/**Set's the text to display for the close link. This attribute is one of
* the regionalisation attributes. Use the showButtonPanel to display this button.
* @param closeText
* @return instance of the current component
*/
public InlineDatePicker<T> setCloseText(String closeText) {
this.options.setCloseText(closeText);
return this;
}
/**
* @return the closeText option value
*/
public String getCloseText() {
return this.options.getCloseText();
}
/**True if the input field is constrained to the current date format.
* @param constrainInput
* @return instance of the current component
*/
public InlineDatePicker<T> setConstrainInput(boolean constrainInput) {
options.setConstrainInput(constrainInput);
return this;
}
/**
* @return the buttonImageOnly option value
*/
public boolean isConstrainInput() {
return this.options.isConstrainInput();
}
/**Set's the text to display for the current day link. This attribute is one
* of the regionalisation attributes. Use the showButtonPanel to display
* this button.
* @param currentText
* @return instance of the current component
*/
public InlineDatePicker<T> setCurrentText(String currentText) {
this.options.setCurrentText(currentText);
return this;
}
/**
* @return the currentText option value
*/
public String getCurrentText() {
return this.options.getCurrentText();
}
/**
* Sets the calendar's starting day. 0 is for sunday, 1 for monday ...
*
* @param firstDay
* @return instance of the current component
*/
public InlineDatePicker<T> setFirstDay(short firstDay) {
options.setFirstDay(firstDay);
return this;
}
/**
* Returns the calendar's starting day.
*/
public short getFirstDay() {
return this.options.getFirstDay();
}
/**If true, the current day link moves to the currently selected date instead of today.
* @param gotoCurrent
* @return instance of the current component
*/
public InlineDatePicker<T> setGotoCurrent(boolean gotoCurrent) {
options.setGotoCurrent(gotoCurrent);
return this;
}
/**
* @return the gotoCurrent option value
*/
public boolean isGotoCurrent() {
return this.options.isGotoCurrent();
}
/**Normally the previous and next links are disabled when not applicable
* (see minDate/maxDate). You can hide them altogether by setting this
* attribute to true.
* @param hideIfNoPrevNext
* @return instance of the current component
*/
public InlineDatePicker<T> setHideIfNoPrevNext(boolean hideIfNoPrevNext) {
options.setHideIfNoPrevNext(hideIfNoPrevNext);
return this;
}
/**
* @return the hideIfNoPrevNext option value
*/
public boolean isHideIfNoPrevNext() {
return this.options.isHideIfNoPrevNext();
}
/**True if the current language is drawn from right to left. This attribute
* is one of the regionalisation attributes.
* @param isRTL
* @return instance of the current component
*/
public InlineDatePicker<T> setIsRTL(boolean isRTL) {
options.setIsRTL(isRTL);
return this;
}
/**
* @return the isRTL option value
*/
public boolean isIsRTL() {
return this.options.isIsRTL();
}
/**Set a maximum selectable date via a Date object, or a number of days from
* today (e.g. +7) or a string of values and periods ('y' for years, 'm' for
* months, 'w' for weeks, 'd' for days, e.g. '+1m +1w'), or null for no limit.
* @param maxDate
* @return instance of the current component
*/
public InlineDatePicker<T> setMaxDate(DateOption maxDate) {
options.setMaxDate(maxDate);
return this;
}
/**
* @return the maxDate option value
*/
public DateOption getMaxDate() {
return this.options.getMaxDate();
}
/**Set a minimum selectable date via a Date object, or a number of days from
* today (e.g. +7) or a string of values and periods ('y' for years, 'm' for
* months, 'w' for weeks, 'd' for days, e.g. '+1m +1w'), or null for no limit.
* @param minDate
* @return instance of the current component
*/
public InlineDatePicker<T> setMinDate(DateOption minDate) {
options.setMinDate(minDate);
return this;
}
/**
* @return the minDate option value
*/
public DateOption getMinDate() {
return this.options.getMinDate();
}
/**Set's the list of full month names, as used in the month header on each
* datepicker and as requested via the dateFormat setting. This attribute is
* one of the regionalisation attributes.
* @param monthNames
* @return instance of the current component
*/
public InlineDatePicker<T> setMonthNames(ArrayOfMonthNames monthNames) {
options.setMonthNames(monthNames);
return this;
}
/**
* @return the monthNames option value
*/
public ArrayOfMonthNames getMonthNames() {
return this.options.getMonthNames();
}
/**Set's the list of abbreviated month names, for use as requested via the
* dateFormat setting. This attribute is one of the regionalisation attributes.
* @param monthNamesShort
* @return instance of the current component
*/
public InlineDatePicker<T> setMonthNamesShort(ArrayOfMonthNames monthNamesShort) {
options.setMonthNamesShort(monthNamesShort);
return this;
}
/**
* @return the monthNames option value
*/
public ArrayOfMonthNames getMonthNamesShort() {
return options.getMonthNamesShort();
}
/**When true the formatDate function is applied to the prevText, nextText,
* and currentText values before display, allowing them to display the
* target month names for example.
* @param navigationAsDateFormat
* @return instance of the current component
*/
public InlineDatePicker<T> setNavigationAsDateFormat(boolean navigationAsDateFormat) {
options.setNavigationAsDateFormat(navigationAsDateFormat);
return this;
}
/**
* @return the navigationAsDateFormat option value
*/
public boolean isNavigationAsDateFormat() {
return this.options.isNavigationAsDateFormat();
}
/**Set's the text to display for the next month link. This attribute is one
* of the regionalisation attributes. With the standard ThemeRoller styling,
* this value is replaced by an icon.
* @param nextText
* @return instance of the current component
*/
public InlineDatePicker<T> setNextText(String nextText) {
this.options.setNextText(nextText);
return this;
}
/**
* @return the nextText option value
*/
public String getNextText() {
return this.options.getNextText();
}
/**
* Sets if the next/previous months are showed in the calendar.
* @return instance of the current component
*/
public InlineDatePicker<T> setShowOtherMonths(boolean showOtherMonths) {
this.options.setShowOtherMonths(showOtherMonths);
return this;
}
/**
* @deprecated will be removed in 1.2
* Returns if the next/previous months are showed in the calendar.
*/
public boolean getShowOtherMonths() {
return options.getShowOtherMonths();
}
/**
* Returns if the next/previous months are showed in the calendar.
*/
public boolean isShowOtherMonths() {
return options.isShowOtherMonths();
}
/**
* Sets the number of months displayed on the date picker.
* @return instance of the current component
*/
public InlineDatePicker<T> setNumberOfMonths(DatePickerNumberOfMonths numberOfMonths) {
this.options.setNumberOfMonths(numberOfMonths);
return this;
}
/**
* Returns the number of months displayed on the date picker.
*/
public DatePickerNumberOfMonths getNumberOfMonths() {
return this.options.getNumberOfMonths();
}
/**Set's the text to display for the previous month link. This attribute is one
* of the regionalisation attributes. With the standard ThemeRoller styling,
* this value is replaced by an icon.
* @param prevText
* @return instance of the current component
*/
public InlineDatePicker<T> setPrevText(String prevText) {
this.options.setPrevText(prevText);
return this;
}
/**
* @return the prevText option value
*/
public String getPrevText() {
return this.options.getPrevText();
}
/**When true days in other months shown before or after the current month
* are selectable. This only applies if showOtherMonths is also true.
* @param selectOtherMonths
* @return instance of the current behavior
*/
public InlineDatePicker<T> setSelectOtherMonths(boolean selectOtherMonths) {
this.options.setSelectOtherMonths(selectOtherMonths);
return this;
}
/**
* @return the selectOtherMonths option
*/
public boolean isSelectOtherMonths() {
return options.isSelectOtherMonths();
}
/**Set the cutoff year for determining the century for a date
* @param shortYearCutoff
* @return instance of the current component
*/
public InlineDatePicker<T> setShortYearCutoff(DatePickerShortYearCutOff shortYearCutoff) {
options.setShortYearCutoff(shortYearCutoff);
return this;
}
/**
* Returns the shortYearCutoff option value.
*/
public DatePickerShortYearCutOff getShortYearCutoff() {
return this.options.getShortYearCutoff();
}
/**Set the name of the animation used to show/hide the datepicker. Use
* 'show' (the default), 'slideDown', 'fadeIn', or any of the show/hide
* jQuery UI effects
* @param showAnim
* @return instance of the current component
*/
public InlineDatePicker<T> setShowAnim(String showAnim) {
this.options.setShowAnim(showAnim);
return this;
}
/**
* @return the showAnim option value
*/
public String getShowAnim() {
return this.options.getShowAnim();
}
/**Whether to show the button panel.
* @param showButtonPanel
* @return instance of the current component
*/
public InlineDatePicker<T> setShowButtonPanel(boolean showButtonPanel) {
options.setShowButtonPanel(showButtonPanel);
return this;
}
/**
* @return the showButtonPanel option value
*/
public boolean isShowButtonPanel() {
return this.options.isShowButtonPanel();
}
/**Specify where in a multi-month display the current month shows, starting
* from 0 at the top/left.
* @param showCurrentAtPos
* @return instance of the current component
*/
public InlineDatePicker<T> setShowCurrentAtPos(short showCurrentAtPos) {
options.setShowCurrentAtPos(showCurrentAtPos);
return this;
}
/**
* @return the showCurrentAtPos option value
*/
public short getShowCurrentAtPos() {
return this.options.getShowCurrentAtPos();
}
/**Whether to show the month after the year in the header.
* @param showMonthAfterYear
* @return instance of the current component
*/
public InlineDatePicker<T> setShowMonthAfterYear(boolean showMonthAfterYear) {
options.setShowMonthAfterYear(showMonthAfterYear);
return this;
}
/**
* @return the showMonthAfterYear option value
*/
public boolean isShowMonthAfterYear() {
return this.options.isShowMonthAfterYear();
}
/**Have the datepicker appear automatically when the field receives focus
* ('focus'), appear only when a button is clicked ('button'), or appear
* when either event takes place ('both').
* @param showOn
* @return instance of the current component
*/
public InlineDatePicker<T> setShowOn(ShowOnEnum showOn) {
options.setShowOn(showOn);
return this;
}
/**
* @return the showOn option value
*/
public ShowOnEnum getShowOn() {
return this.options.getShowOn();
}
/**If using one of the jQuery UI effects for showAnim, you can provide
* additional settings for that animation via this option.
* @param showOptions
* @return instance of the current component
*/
public InlineDatePicker<T> setShowOptions(ListItemOptions<LiteralOption> showOptions) {
options.setShowOptions(showOptions);
return this;
}
/**
* @return the showOptions option value
*/
public ListItemOptions<LiteralOption> getShowOptions() {
return this.options.getShowOptions();
}
/**
* When true a column is added to show the week of the year. The calculateWeek
* option determines how the week of the year is calculated. You may also
* want to change the firstDay option.
* @return instance of the current component
*/
public InlineDatePicker<T> setShowWeek(boolean showWeek) {
options.setShowWeek(showWeek);
return this;
}
/**
* @return the showWeek option
*/
public boolean isShowWeek() {
return options.isShowWeek();
}
/**
* Sets the number of months stepped when the next/previous button are hit.
* @return instance of the current component
*/
public InlineDatePicker<T> setStepMonths(short stepMonths) {
options.setStepMonths(stepMonths);
return this;
}
/**
* Returns the number of months stepped when the next/previous button are
* hit.
*/
public short getStepMonths() {
return this.options.getStepMonths();
}
/**
* Sets the ISO date format to use.
*
* The format can be combinations of the following:
* <ul>
* <li>d - day of month (no leading zero)</li>
* <li>dd - day of month (two digit)</li>
* <li>o - day of the year (no leading zeros)</li>
* <li>oo - day of the year (three digit)</li>
* <li>D - day name short</li>
* <li>DD - day name long</li>
* <li>m - month of year (no leading zero)</li>
* <li>mm - month of year (two digit)</li>
* <li>M - month name short</li>
* <li>MM - month name long</li>
* <li>y - year (two digit)</li>
* <li>yy - year (four digit)</li>
* <li>@ - Unix timestamp (ms since 01/01/1970)</li>
* <li>'...' - literal text</li>
* <li>'' - single quote</li>
* <li>anything else - literal text</li>
* </ul>
* @return instance of the current component
*/
public InlineDatePicker<T> setDateFormat(String dateFormat) {
options.setDateFormat(dateFormat);
return this;
}
/**
* Returns the ISO date format to use.
*/
public String getDateFormat() {
return this.options.getDateFormat();
}
/**Set's the list of long day names, starting from Sunday, for use as
* requested via the dateFormat setting. They also appear as popup hints
* when hovering over the corresponding column headings. This attribute is
* one of the regionalisation attributes.
* @param dayNames
* @return instance of the current component
*/
public InlineDatePicker<T> setDayNames(ArrayOfDayNames dayNames) {
options.setDayNames(dayNames);
return this;
}
/**
* @return the dayNames option value
*/
public ArrayOfDayNames getDayNames() {
return this.options.getDayNames();
}
/**Set's the list of minimised day names, starting from Sunday, for use as
* column headers within the datepicker. This attribute is one of the
* regionalisation attributes.
* @param dayNamesMin
* @return instance of the current component
*/
public InlineDatePicker<T> setDayNamesMin(ArrayOfDayNames dayNamesMin) {
this.options.setDayNamesMin(dayNamesMin);
return this;
}
/**
* @return the dayNamesMin option value
*/
public ArrayOfDayNames getDayNamesMin() {
return this.options.getDayNamesMin();
}
/**Set's the list of abbreviated day names, starting from Sunday, for use as
* requested via the dateFormat setting. This attribute is one of the
* regionalisation attributes.
* @param dayNamesShort
* @return instance of the current component
*/
public InlineDatePicker<T> setDayNamesShort(ArrayOfDayNames dayNamesShort) {
options.setDayNamesShort(dayNamesShort);
return this;
}
/**
* @return the dayNamesShort option value
*/
public ArrayOfDayNames getDayNamesShort() {
return this.options.getDayNamesShort();
}
/**Set the date to highlight on first opening if the field is blank. Specify
* either an actual date via a Date object, or a number of days from today
* (e.g. +7) or a string of values and periods ('y' for years, 'm' for months,
* 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.
* @param defaultDate
* @return instance of the current component
*/
public InlineDatePicker<T> setDefaultDate(DateOption defaultDate) {
this.options.setDefaultDate(defaultDate);
return this;
}
/**
* @return the defaultDate option value
*/
public DateOption getDefaultDate() {
return this.options.getDefaultDate();
}
/**Disables (true) or enables (false) the datepicker. Can be set when
* initialising (first creating) the datepicker.
* @param disabled
* @return instance of the current behavior
*/
public InlineDatePicker<T> setDisabled(boolean disabled) {
this.options.setDisabled(disabled);
return this;
}
/**
* @return the disabled option
*/
public boolean isDisabled() {
return options.isDisabled();
}
/**Control the speed at which the datepicker appears, it may be a time in
* milliseconds, a string representing one of the three predefined speeds
* ("slow", "normal", "fast"), or '' for immediately.
* @param duration
* @return instance of the current component
*/
public InlineDatePicker<T> setDuration(DatePickerDuration duration) {
this.options.setDuration(duration);
return this;
}
/**
* @return the duration option value
*/
public DatePickerDuration getDuration() {
return this.options.getDuration();
}
/*---- Events section ---*/
/**Set's the callback before the datepicker is displayed.
* @param beforeShow
* @return instance of the current component
*/
public InlineDatePicker<T> setBeforeShowEvent(JsScopeUiEvent beforeShow) {
this.options.setBeforeShowEvent(beforeShow);
return this;
}
/**The function takes a date as a parameter and must return an array with [0]
* equal to true/false indicating whether or not this date is selectable, [1]
* equal to a CSS class name(s) or '' for the default presentation and [2]
* an optional popup tooltip for this date. It is called for each day in
* the datepicker before is it displayed.
* @param beforeShowDay
* @return instance of the current component
*/
public InlineDatePicker<T> setBeforeShowDayEvent(JsScopeUiDatePickerEvent beforeShowDay) {
this.options.setBeforeShowDayEvent(beforeShowDay);
return this;
}
/**Allows you to define your own event when the datepicker moves to a new
* month and/or year. The function receives the selected year, month (1-12),
* and the datepicker instance as parameters. this refers to the associated
* input field.
* @param onChangeMonthYear
* @return instance of the current component
*/
public InlineDatePicker<T> setOnChangeMonthYearEvent(JsScopeUiDatePickerOnChangeEvent onChangeMonthYear) {
this.options.setOnChangeMonthYearEvent(onChangeMonthYear);
return this;
}
/**Allows you to define your own event when the datepicker is closed, whether
* or not a date is selected. The function receives the selected date as text
* and the datepicker instance as parameters. this refers to the associated
* input field.
* @param onClose
* @return instance of the current component
*/
public InlineDatePicker<T> setOnCloseEvent(JsScopeUiDatePickerDateTextEvent onClose) {
this.options.setOnCloseEvent(onClose);
return this;
}
/**Allows you to define your own event when the datepicker is selected. The
* function receives the selected date as text and the datepicker instance
* as parameters. this refers to the associated input field.
* @param onSelect
* @return instance of the current component
*/
public InlineDatePicker<T> setOnSelectEvent(JsScopeUiDatePickerDateTextEvent onSelect) {
this.options.setOnSelectEvent(onSelect);
return this;
}
/*---- Methods section ---*/
/**Method to destroy the datepicker
* This will return the element back to its pre-init state.
* @return the associated JsStatement
*/
public JsStatement destroy() {
return new JsQuery(this).$().chain("datepicker", "'destroy'");
}
/**Method to destroy the datepicker within the ajax request
* @param ajaxRequestTarget
*/
public void destroy(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.appendJavascript(this.destroy().render().toString());
}
/**Method to disable the datepicker
* @return the associated JsStatement
*/
public JsStatement disable() {
return new JsQuery(this).$().chain("datepicker", "'disable'");
}
/**Method to disable the datepicker within the ajax request
* @param ajaxRequestTarget
*/
public void disable(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.appendJavascript(this.disable().render().toString());
}
/**Method to enable the datepicker
* @return the associated JsStatement
*/
public JsStatement enable() {
return new JsQuery(this).$().chain("datepicker", "'enable'");
}
/**Method to enable the datepicker within the ajax request
* @param ajaxRequestTarget
*/
public void enable(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.appendJavascript(this.enable().render().toString());
}
/**Method returning the current date for the datepicker
* @return the associated JsStatement
*/
public JsStatement getDate() {
return new JsQuery(this).$().chain("datepicker", "'getDate'");
}
/**Method to hide the datepicker
* @param speed The speed at which to close the date picker.
* @return the associated JsStatement
*/
public JsStatement hide(short speed) {
return new JsQuery(this).$().chain("datepicker", "'hide'", Short.toString(speed));
}
/**Method to hide the datepicker within the ajax request
* @param ajaxRequestTarget
* @param speed The speed at which to close the date picker.
*/
public void hide(AjaxRequestTarget ajaxRequestTarget, short speed) {
ajaxRequestTarget.appendJavascript(this.hide(speed).render().toString());
}
/**Method to hide the datepicker
* @return the associated JsStatement
*/
public JsStatement hide() {
return new JsQuery(this).$().chain("datepicker", "'hide'");
}
/**Method to hide the datepicker within the ajax request
* @param ajaxRequestTarget
*/
public void hide(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.appendJavascript(this.hide().render().toString());
}
/**Method to set the date of the datepicker
* @param dateOption Date to set
* @return the associated JsStatement
*/
public JsStatement setDate(DateOption dateOption) {
return new JsQuery(this).$().chain("datepicker", "'setDate'",
dateOption.getJavascriptOption());
}
/**Method to set the date of the datepicker within the ajax request
* @param ajaxRequestTarget
* @param dateOption Date to set
*/
public void setDate(AjaxRequestTarget ajaxRequestTarget, DateOption dateOption) {
ajaxRequestTarget.appendJavascript(this.setDate(dateOption).render().toString());
}
/**Method to show the datepicker
* @return the associated JsStatement
*/
public JsStatement show() {
return new JsQuery(this).$().chain("datepicker", "'show'");
}
/**Method to show the datepicker within the ajax request
* @param ajaxRequestTarget
*/
public void show(AjaxRequestTarget ajaxRequestTarget) {
ajaxRequestTarget.appendJavascript(this.show().render().toString());
}
}
| false | true | public void contribute(WiQueryResourceManager wiQueryResourceManager) {
wiQueryResourceManager.addJavaScriptResource(DatePickerJavaScriptResourceReference.get());
Locale locale = getLocale();
if(locale != null && !Locale.ENGLISH.getLanguage().equals(locale.getLanguage())){ // #issue 24
wiQueryResourceManager
.addJavaScriptResource(new DatePickerLanguageResourceReference(
locale));
}
}
| public void contribute(WiQueryResourceManager wiQueryResourceManager) {
wiQueryResourceManager.addJavaScriptResource(DatePickerJavaScriptResourceReference.get());
Locale locale = getLocale();
if (locale != null && !getLocale().equals(Locale.US))
wiQueryResourceManager
.addJavaScriptResource(new DatePickerLanguageResourceReference(
locale));
}
|
diff --git a/src/org/ebookdroid/core/settings/SettingsActivity.java b/src/org/ebookdroid/core/settings/SettingsActivity.java
index cc7f6967..e4607201 100644
--- a/src/org/ebookdroid/core/settings/SettingsActivity.java
+++ b/src/org/ebookdroid/core/settings/SettingsActivity.java
@@ -1,41 +1,43 @@
package org.ebookdroid.core.settings;
import org.ebookdroid.R;
import org.ebookdroid.core.settings.SettingsManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
addPreferencesFromResource(R.xml.preferences);
} catch (final ClassCastException e) {
Log.e("VuDroidSettings", "Shared preferences are corrupt! Resetting to default values.");
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
addPreferencesFromResource(R.xml.preferences);
}
if (SettingsManager.getInstance(this).getBookSettings() == null) {
- Preference somePreference = findPreference("book_render");
- PreferenceScreen preferenceScreen = getPreferenceScreen();
- preferenceScreen.removePreference(somePreference);
+ Preference bookPrefs = findPreference("book_prefs");
+ if (bookPrefs != null) {
+ PreferenceScreen preferenceScreen = getPreferenceScreen();
+ preferenceScreen.removePreference(bookPrefs);
+ }
}
}
}
| true | true | protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
addPreferencesFromResource(R.xml.preferences);
} catch (final ClassCastException e) {
Log.e("VuDroidSettings", "Shared preferences are corrupt! Resetting to default values.");
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
addPreferencesFromResource(R.xml.preferences);
}
if (SettingsManager.getInstance(this).getBookSettings() == null) {
Preference somePreference = findPreference("book_render");
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(somePreference);
}
}
| protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
addPreferencesFromResource(R.xml.preferences);
} catch (final ClassCastException e) {
Log.e("VuDroidSettings", "Shared preferences are corrupt! Resetting to default values.");
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
addPreferencesFromResource(R.xml.preferences);
}
if (SettingsManager.getInstance(this).getBookSettings() == null) {
Preference bookPrefs = findPreference("book_prefs");
if (bookPrefs != null) {
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(bookPrefs);
}
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java
index 3a82b1121..2592b8f40 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/layout/LayoutUtil.java
@@ -1,173 +1,177 @@
package org.eclipse.birt.report.engine.emitter.excel.layout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IListContent;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.emitter.excel.ExcelUtil;
import org.eclipse.birt.report.engine.ir.DimensionType;
public class LayoutUtil
{
public static int[] getColumnWidth( TableInfo table, int width )
{
int[] col = new int[table.getColumnCount( )];
int tmp = 0;
int nullNumber = 0;
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
int colwidth = table.getColumnWidth( i );
// record columns which is not set column's width in report design.
if ( colwidth == 0 )
{
nullNumber++;
col[i] = -1;
}
else
{
col[i] = colwidth;
tmp += col[i];
}
}
// If columns are not set width, set the average width to them.
if ( nullNumber != 0 )
{
int aveWidth = ( width - tmp ) / nullNumber;
tmp = 0;
for ( int i = 0; i < col.length; i++ )
{
if ( col[i] == -1 )
{
col[i] = aveWidth;
}
tmp += col[i];
}
}
// Set the left width to the last column.
col[col.length - 1] += width - tmp;
return col;
}
public static TableInfo createTable(int col, int width)
{
return new DefaultTableInfo(col, width);
}
public static TableInfo createTable(IListContent list, int width)
{
width = getElementWidth(list, width);
int[] column = new int[] {width};
return new DefaultTableInfo(column);
}
private static int getElementWidth(IContent content, int width)
{
DimensionType value = content.getWidth( );
if(value != null)
{
try
{
width = Math.min( ExcelUtil.covertDimensionType( value, width ),
width );
}
catch(Exception e)
{
}
}
return width;
}
public static TableInfo createTable(ITableContent table, int width)
{
width = getElementWidth(table, width);
int colcount = table.getColumnCount( );
if ( colcount == 0 )
{
return null;
}
int[] index = new int[colcount];
int know = 0;
List unmount = new ArrayList();
for(int i = 0; i < colcount; i++)
{
DimensionType value = table.getColumn( i ).getWidth( );
if( value == null)
{
unmount.add( new Integer(i) );
}
else
{
try {
index[i] = ExcelUtil.covertDimensionType( value, width );
know += index[i];
}
catch(IllegalArgumentException ex)
{
unmount.add( new Integer(i) );
}
}
}
int left = width - know;
if(left > 0 && unmount.size( ) == 0)
{
index[index.length - 1] = index[index.length - 1] + left;
return new DefaultTableInfo(index);
}
+ else if(left < 0 )
+ {
+ return new DefaultTableInfo(split(width, colcount));
+ }
else if(left > 0 && unmount.size( ) > 0)
{
int[] size = split(left, unmount.size());
Iterator iter = unmount.iterator( );
int i = 0;
while(iter.hasNext( ))
{
int pos = ((Integer) iter.next()).intValue( );
index[pos] = size[i];
i++;
}
return new DefaultTableInfo(index);
}
else
{
return new DefaultTableInfo(index);
}
}
public static int[] split(int width, int count)
{
int[] size = new int[count];
int per = (int) width / count;
for(int i = 0; i < count - 1; i++)
{
size[i] = per;
}
size[count - 1] = width - per * (count - 1);
return size;
}
}
| true | true | public static TableInfo createTable(ITableContent table, int width)
{
width = getElementWidth(table, width);
int colcount = table.getColumnCount( );
if ( colcount == 0 )
{
return null;
}
int[] index = new int[colcount];
int know = 0;
List unmount = new ArrayList();
for(int i = 0; i < colcount; i++)
{
DimensionType value = table.getColumn( i ).getWidth( );
if( value == null)
{
unmount.add( new Integer(i) );
}
else
{
try {
index[i] = ExcelUtil.covertDimensionType( value, width );
know += index[i];
}
catch(IllegalArgumentException ex)
{
unmount.add( new Integer(i) );
}
}
}
int left = width - know;
if(left > 0 && unmount.size( ) == 0)
{
index[index.length - 1] = index[index.length - 1] + left;
return new DefaultTableInfo(index);
}
else if(left > 0 && unmount.size( ) > 0)
{
int[] size = split(left, unmount.size());
Iterator iter = unmount.iterator( );
int i = 0;
while(iter.hasNext( ))
{
int pos = ((Integer) iter.next()).intValue( );
index[pos] = size[i];
i++;
}
return new DefaultTableInfo(index);
}
else
{
return new DefaultTableInfo(index);
}
}
| public static TableInfo createTable(ITableContent table, int width)
{
width = getElementWidth(table, width);
int colcount = table.getColumnCount( );
if ( colcount == 0 )
{
return null;
}
int[] index = new int[colcount];
int know = 0;
List unmount = new ArrayList();
for(int i = 0; i < colcount; i++)
{
DimensionType value = table.getColumn( i ).getWidth( );
if( value == null)
{
unmount.add( new Integer(i) );
}
else
{
try {
index[i] = ExcelUtil.covertDimensionType( value, width );
know += index[i];
}
catch(IllegalArgumentException ex)
{
unmount.add( new Integer(i) );
}
}
}
int left = width - know;
if(left > 0 && unmount.size( ) == 0)
{
index[index.length - 1] = index[index.length - 1] + left;
return new DefaultTableInfo(index);
}
else if(left < 0 )
{
return new DefaultTableInfo(split(width, colcount));
}
else if(left > 0 && unmount.size( ) > 0)
{
int[] size = split(left, unmount.size());
Iterator iter = unmount.iterator( );
int i = 0;
while(iter.hasNext( ))
{
int pos = ((Integer) iter.next()).intValue( );
index[pos] = size[i];
i++;
}
return new DefaultTableInfo(index);
}
else
{
return new DefaultTableInfo(index);
}
}
|
diff --git a/src/net/sf/gogui/gtpstatistics/GtpStatistics.java b/src/net/sf/gogui/gtpstatistics/GtpStatistics.java
index 9be6025e..9f306071 100644
--- a/src/net/sf/gogui/gtpstatistics/GtpStatistics.java
+++ b/src/net/sf/gogui/gtpstatistics/GtpStatistics.java
@@ -1,466 +1,466 @@
//----------------------------------------------------------------------------
// $Id$
// $Source$
//----------------------------------------------------------------------------
package net.sf.gogui.gtpstatistics;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import net.sf.gogui.game.GameInformation;
import net.sf.gogui.game.GameTree;
import net.sf.gogui.game.Node;
import net.sf.gogui.game.NodeUtils;
import net.sf.gogui.go.GoColor;
import net.sf.gogui.go.GoPoint;
import net.sf.gogui.go.Move;
import net.sf.gogui.gtp.GtpClient;
import net.sf.gogui.gtp.GtpError;
import net.sf.gogui.sgf.SgfReader;
import net.sf.gogui.utils.ErrorMessage;
import net.sf.gogui.utils.Platform;
import net.sf.gogui.utils.StringUtils;
import net.sf.gogui.utils.Table;
//----------------------------------------------------------------------------
/** Run commands of a GTP engine on all positions in a game collection. */
public class GtpStatistics
{
public GtpStatistics(String program, ArrayList sgfFiles, File output,
int size, ArrayList commands,
ArrayList beginCommands, ArrayList finalCommands,
boolean verbose, boolean force, boolean allowSetup,
int min, int max, boolean backward)
throws Exception
{
if (output.exists() && ! force)
throw new ErrorMessage("File " + output + " already exists");
new FileCheck(sgfFiles, size, allowSetup);
m_size = size;
m_result = false;
m_allowSetup = allowSetup;
m_min = min;
m_max = max;
m_backward = backward;
initCommands(commands, beginCommands, finalCommands);
ArrayList columnHeaders = new ArrayList();
columnHeaders.add("File");
columnHeaders.add("Move");
for (int i = 0; i < m_commands.size(); ++i)
columnHeaders.add(getCommand(i).m_columnTitle);
m_table = new Table(columnHeaders);
m_table.setProperty("Size", Integer.toString(size));
m_gtp = new GtpClient(program, verbose, null);
m_gtp.queryProtocolVersion();
m_table.setProperty("Program", program);
try
{
m_table.setProperty("Name", m_gtp.send("name"));
}
catch (GtpError e)
{
m_table.setProperty("Name", "");
if (m_gtp.isProgramDead())
throw e;
}
try
{
m_table.setProperty("Version", m_gtp.send("version"));
}
catch (GtpError e)
{
m_table.setProperty("Version", "");
}
String host = Platform.getHostInfo();
m_table.setProperty("Host", host);
m_table.setProperty("Date", StringUtils.getDate());
for (int i = 0; i < sgfFiles.size(); ++i)
handleFile((String)sgfFiles.get(i));
m_table.setProperty("Games", Integer.toString(m_numberGames));
- m_table.setProperty("Backward", backward ? "no" : "yes");
+ m_table.setProperty("Backward", backward ? "yes" : "no");
FileWriter writer = new FileWriter(output);
m_table.save(writer);
writer.close();
}
public boolean getResult()
{
return m_result;
}
private static class Command
{
public boolean m_begin;
public boolean m_final;
public String m_command;
public String m_columnTitle;
}
private final boolean m_allowSetup;
private final boolean m_backward;
private boolean m_result;
private int m_max;
private int m_min;
private int m_numberGames;
private final int m_size;
private double m_lastCpuTime = 0;
private GtpClient m_gtp;
private final NumberFormat m_format1 = StringUtils.getNumberFormat(1);
private final NumberFormat m_format2 = StringUtils.getNumberFormat(2);
private Table m_table;
private ArrayList m_commands;
private void addCommand(String commandLine, boolean isBegin,
boolean isFinal) throws ErrorMessage
{
commandLine = commandLine.trim();
if (commandLine.equals(""))
throw new ErrorMessage("Empty command not allowed");
Command command = new Command();
command.m_command = commandLine;
command.m_begin = isBegin;
command.m_final = isFinal;
int numberSame = 0;
Command firstSame = null;
for (int i = 0; i < m_commands.size(); ++i)
if (getCommand(i).m_command.equals(commandLine))
{
firstSame = getCommand(i);
++numberSame;
}
if (numberSame == 0)
command.m_columnTitle = commandLine;
else
{
if (numberSame == 1)
firstSame.m_columnTitle = firstSame.m_columnTitle + " (1)";
command.m_columnTitle = commandLine + " ("
+ (numberSame + 1) + ")";
}
m_commands.add(command);
}
private void addCommands(ArrayList commands, boolean isBegin,
boolean isFinal) throws ErrorMessage
{
for (int i = 0; i < commands.size(); ++i)
addCommand((String)commands.get(i), isBegin, isFinal);
}
private void checkGame(GameTree tree, String name) throws ErrorMessage
{
GameInformation info = tree.getGameInformation();
int size = info.m_boardSize;
if (size != m_size)
throw new ErrorMessage(name + " has not size " + m_size);
Node root = tree.getRoot();
GoColor toMove = GoColor.BLACK;
for (Node node = root; node != null; node = node.getChild())
{
if (node.getNumberAddWhite() + node.getNumberAddBlack() > 0)
{
if (m_allowSetup)
{
if (node == root)
toMove = GoColor.EMPTY;
else
throw new ErrorMessage(name + " contains setup stones"
+ " in non-root position");
}
else
throw new ErrorMessage(name + " contains setup stones");
}
Move move = node.getMove();
if (move != null)
{
if (toMove == GoColor.EMPTY)
toMove = move.getColor();
if (move.getColor() != toMove)
throw new ErrorMessage(name
+ "has non-alternating moves");
toMove = toMove.otherColor();
}
}
}
private String convertCommand(String command, GoColor toMove)
{
if (command.equals("reg_genmove"))
return command + ' ' + toMove;
return command;
}
private String convertResponse(String command, String response,
GoColor toMove, Move move) throws GtpError
{
if (command.equals("cputime"))
{
try
{
double cpuTime = Double.parseDouble(response);
double diff = cpuTime - m_lastCpuTime;
m_lastCpuTime = cpuTime;
return m_format2.format(diff);
}
catch (NumberFormatException e)
{
return response;
}
}
else if (command.equals("estimate_score"))
{
String arg[] = StringUtils.splitArguments(response);
if (arg.length == 0)
return response;
return convertScore(arg[0]);
}
else if (command.equals("final_score"))
{
return convertScore(response);
}
else if (command.equals("reg_genmove"))
{
if (move == null)
return "";
try
{
GoPoint point = GoPoint.parsePoint(response, m_size);
return Move.get(point, toMove) == move ? "1" : "0";
}
catch (GoPoint.InvalidPoint e)
{
throw new GtpError("Program sent invalid move: " + response);
}
}
return response;
}
/** Tries to convert score into number.
@return Score string or original string, if conversion fails.
*/
private String convertScore(String string)
{
String score = string.trim();
double sign = 1;
if (score.startsWith("W+"))
{
score = score.substring(2);
sign = -1;
}
else if (score.startsWith("B+"))
score = score.substring(2);
try
{
return m_format1.format(sign * Double.parseDouble(score));
}
catch (NumberFormatException e)
{
return string;
}
}
private void initCommands(ArrayList commands, ArrayList beginCommands,
ArrayList finalCommands) throws ErrorMessage
{
m_commands = new ArrayList();
if (beginCommands != null)
addCommands(beginCommands, true, false);
if (commands != null)
addCommands(commands, false, false);
if (finalCommands != null)
addCommands(finalCommands, false, true);
if (m_commands.size() == 0)
throw new ErrorMessage("No commands defined");
}
private Command getCommand(int index)
{
return (Command)m_commands.get(index);
}
private void handleFile(String name)
throws ErrorMessage, FileNotFoundException, GtpError,
SgfReader.SgfError
{
InputStream in = new FileInputStream(new File(name));
SgfReader reader = new SgfReader(in, name, null, 0);
++m_numberGames;
GameTree tree = reader.getGameTree();
checkGame(tree, name);
GameInformation info = tree.getGameInformation();
int size = info.m_boardSize;
m_gtp.sendBoardsize(size);
m_gtp.sendClearBoard(size);
Node root = tree.getRoot();
if (m_backward)
iteratePositionsBackward(root, name);
else
iteratePositions(root, name);
}
private void handlePosition(String name, GoColor toMove, Move move,
int number, boolean beginCommands,
boolean regularCommands,
boolean finalCommands)
throws GtpError
{
System.err.println(name + ":" + number);
m_table.startRow();
m_table.set("File", name);
m_table.set("Move", number);
for (int i = 0; i < m_commands.size(); ++i)
{
Command command = getCommand(i);
if (command.m_begin && beginCommands)
{
String response = send(command.m_command, toMove, move);
m_table.set(command.m_columnTitle, response);
}
}
for (int i = 0; i < m_commands.size(); ++i)
{
Command command = getCommand(i);
if (! command.m_begin && ! command.m_final && regularCommands)
{
String response = send(command.m_command, toMove, move);
m_table.set(command.m_columnTitle, response);
}
}
for (int i = 0; i < m_commands.size(); ++i)
{
Command command = getCommand(i);
if (command.m_final && finalCommands)
{
String response = send(command.m_command, toMove, move);
m_table.set(command.m_columnTitle, response);
}
}
}
private void iteratePositions(Node root, String name) throws GtpError
{
int number = 0;
GoColor toMove = GoColor.BLACK;
for (Node node = root; node != null; node = node.getChild())
{
if (node.getNumberAddWhite() + node.getNumberAddBlack() > 0)
{
assert(m_allowSetup && node != root); // checked in checkGame
toMove = sendSetup(node);
}
Move move = node.getMove();
if (move != null)
{
++number;
boolean beginCommands = (number == 1);
boolean regularCommands =
(number >= m_min && number <= m_max);
if (beginCommands || regularCommands)
handlePosition(name, toMove, move, number, beginCommands,
regularCommands, false);
m_gtp.sendPlay(move);
toMove = toMove.otherColor();
}
}
++number;
boolean beginCommands = (number == 1);
boolean regularCommands = (number >= m_min && number <= m_max);
handlePosition(name, toMove, null, number, beginCommands,
regularCommands, true);
}
private void iteratePositionsBackward(Node root, String name)
throws GtpError
{
Node node = root;
GoColor toMove = GoColor.BLACK;
while (true)
{
if (node.getNumberAddWhite() + node.getNumberAddBlack() > 0)
{
assert(m_allowSetup && node != root); // checked in checkGame
toMove = sendSetup(node);
}
Move move = node.getMove();
if (move != null)
{
m_gtp.sendPlay(move);
toMove = toMove.otherColor();
}
Node child = node.getChild();
if (child == null)
break;
node = child;
}
int number = 1;
boolean finalCommands = (node == root);
boolean regularCommands = (number >= m_min && number <= m_max);
handlePosition(name, toMove, null, number, true, regularCommands,
finalCommands);
for ( ; node != root; node = node.getFather())
{
// checked in checkGame
assert(node.getNumberAddWhite() + node.getNumberAddBlack() == 0);
Move move = node.getMove();
if (move != null)
{
m_gtp.send("undo");
++number;
finalCommands = (node.getFather() == root);
regularCommands = (number >= m_min && number <= m_max);
if (finalCommands || regularCommands)
handlePosition(name, toMove, move, number, false,
regularCommands, finalCommands);
toMove = toMove.otherColor();
}
}
}
private String send(String command, GoColor toMove, Move move)
throws GtpError
{
String cmd = convertCommand(command, toMove);
String response = m_gtp.send(cmd);
return convertResponse(command, response, toMove, move);
}
/** Send setup stones as moves.
@return New color to move.
*/
private GoColor sendSetup(Node node) throws GtpError
{
ArrayList moves = NodeUtils.getAllAsMoves(node);
assert(moves.size() > 0);
GoColor toMove = null;
for (int i = 0; i < moves.size(); ++i)
{
Move move = (Move)moves.get(i);
m_gtp.sendPlay(move);
toMove = move.getColor().otherColor();
}
return toMove;
}
}
//----------------------------------------------------------------------------
| true | true | public GtpStatistics(String program, ArrayList sgfFiles, File output,
int size, ArrayList commands,
ArrayList beginCommands, ArrayList finalCommands,
boolean verbose, boolean force, boolean allowSetup,
int min, int max, boolean backward)
throws Exception
{
if (output.exists() && ! force)
throw new ErrorMessage("File " + output + " already exists");
new FileCheck(sgfFiles, size, allowSetup);
m_size = size;
m_result = false;
m_allowSetup = allowSetup;
m_min = min;
m_max = max;
m_backward = backward;
initCommands(commands, beginCommands, finalCommands);
ArrayList columnHeaders = new ArrayList();
columnHeaders.add("File");
columnHeaders.add("Move");
for (int i = 0; i < m_commands.size(); ++i)
columnHeaders.add(getCommand(i).m_columnTitle);
m_table = new Table(columnHeaders);
m_table.setProperty("Size", Integer.toString(size));
m_gtp = new GtpClient(program, verbose, null);
m_gtp.queryProtocolVersion();
m_table.setProperty("Program", program);
try
{
m_table.setProperty("Name", m_gtp.send("name"));
}
catch (GtpError e)
{
m_table.setProperty("Name", "");
if (m_gtp.isProgramDead())
throw e;
}
try
{
m_table.setProperty("Version", m_gtp.send("version"));
}
catch (GtpError e)
{
m_table.setProperty("Version", "");
}
String host = Platform.getHostInfo();
m_table.setProperty("Host", host);
m_table.setProperty("Date", StringUtils.getDate());
for (int i = 0; i < sgfFiles.size(); ++i)
handleFile((String)sgfFiles.get(i));
m_table.setProperty("Games", Integer.toString(m_numberGames));
m_table.setProperty("Backward", backward ? "no" : "yes");
FileWriter writer = new FileWriter(output);
m_table.save(writer);
writer.close();
}
| public GtpStatistics(String program, ArrayList sgfFiles, File output,
int size, ArrayList commands,
ArrayList beginCommands, ArrayList finalCommands,
boolean verbose, boolean force, boolean allowSetup,
int min, int max, boolean backward)
throws Exception
{
if (output.exists() && ! force)
throw new ErrorMessage("File " + output + " already exists");
new FileCheck(sgfFiles, size, allowSetup);
m_size = size;
m_result = false;
m_allowSetup = allowSetup;
m_min = min;
m_max = max;
m_backward = backward;
initCommands(commands, beginCommands, finalCommands);
ArrayList columnHeaders = new ArrayList();
columnHeaders.add("File");
columnHeaders.add("Move");
for (int i = 0; i < m_commands.size(); ++i)
columnHeaders.add(getCommand(i).m_columnTitle);
m_table = new Table(columnHeaders);
m_table.setProperty("Size", Integer.toString(size));
m_gtp = new GtpClient(program, verbose, null);
m_gtp.queryProtocolVersion();
m_table.setProperty("Program", program);
try
{
m_table.setProperty("Name", m_gtp.send("name"));
}
catch (GtpError e)
{
m_table.setProperty("Name", "");
if (m_gtp.isProgramDead())
throw e;
}
try
{
m_table.setProperty("Version", m_gtp.send("version"));
}
catch (GtpError e)
{
m_table.setProperty("Version", "");
}
String host = Platform.getHostInfo();
m_table.setProperty("Host", host);
m_table.setProperty("Date", StringUtils.getDate());
for (int i = 0; i < sgfFiles.size(); ++i)
handleFile((String)sgfFiles.get(i));
m_table.setProperty("Games", Integer.toString(m_numberGames));
m_table.setProperty("Backward", backward ? "yes" : "no");
FileWriter writer = new FileWriter(output);
m_table.save(writer);
writer.close();
}
|
diff --git a/cache-library/src/main/java/com/vandalsoftware/io/IoUtils.java b/cache-library/src/main/java/com/vandalsoftware/io/IoUtils.java
index c8a2587..fc74db2 100644
--- a/cache-library/src/main/java/com/vandalsoftware/io/IoUtils.java
+++ b/cache-library/src/main/java/com/vandalsoftware/io/IoUtils.java
@@ -1,128 +1,130 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.vandalsoftware.io;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
public final class IoUtils {
public static final String UTF_8 = "UTF-8";
private IoUtils() {
}
/**
* Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
*/
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignored) {
}
}
}
/**
* Closes 'socket', ignoring any exceptions. Does nothing if 'socket' is null.
*/
public static void closeQuietly(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (Exception ignored) {
}
}
}
/**
* Returns the contents of 'path' as a byte array.
*/
public static byte[] readFileAsByteArray(String path) throws IOException {
return readFileAsBytes(path).toByteArray();
}
/**
* Returns the contents of 'path' as a string. The contents are assumed to be UTF-8.
*/
public static String readFileAsString(String path) throws IOException {
return readFileAsBytes(path).toString(UTF_8);
}
private static UnsafeByteSequence readFileAsBytes(String path) throws IOException {
RandomAccessFile f = null;
try {
f = new RandomAccessFile(path, "r");
UnsafeByteSequence bytes = new UnsafeByteSequence((int) f.length());
byte[] buffer = new byte[8192];
while (true) {
int byteCount = f.read(buffer);
if (byteCount == -1) {
return bytes;
}
bytes.write(buffer, 0, byteCount);
}
} finally {
IoUtils.closeQuietly(f);
}
}
/**
* Recursively delete everything in {@code dir}.
*/
public static void deleteContents(File dir) throws IOException {
if (!dir.isDirectory()) {
throw new IllegalArgumentException("not a directory: " + dir);
}
final LinkedList<File> dirs = new LinkedList<File>();
dirs.add(dir);
final ArrayList<File> emptyDirs = new ArrayList<File>();
while (!dirs.isEmpty()) {
final File d = dirs.remove();
final File[] fs = d.listFiles();
- for (File f : fs) {
- if (f.isDirectory()) {
- dirs.add(f);
- } else {
- deleteFileOrThrow(f);
+ if (fs != null) {
+ for (File f : fs) {
+ if (f.isDirectory()) {
+ dirs.add(f);
+ } else {
+ deleteFileOrThrow(f);
+ }
}
}
emptyDirs.add(d);
}
for (int i = emptyDirs.size() - 1; i >= 0; i--) {
final File d = emptyDirs.get(i);
deleteFileOrThrow(d);
}
}
public static void deleteFileOrThrow(File f) throws IOException {
if (f.exists() && !f.delete()) {
throw new IOException("failed to delete file: " + f);
}
}
public static void renameFileOrThrow(File src, File dst) throws IOException {
if (!src.renameTo(dst)) {
throw new IOException("file not renamed " + src + " " + dst);
}
}
}
| true | true | public static void deleteContents(File dir) throws IOException {
if (!dir.isDirectory()) {
throw new IllegalArgumentException("not a directory: " + dir);
}
final LinkedList<File> dirs = new LinkedList<File>();
dirs.add(dir);
final ArrayList<File> emptyDirs = new ArrayList<File>();
while (!dirs.isEmpty()) {
final File d = dirs.remove();
final File[] fs = d.listFiles();
for (File f : fs) {
if (f.isDirectory()) {
dirs.add(f);
} else {
deleteFileOrThrow(f);
}
}
emptyDirs.add(d);
}
for (int i = emptyDirs.size() - 1; i >= 0; i--) {
final File d = emptyDirs.get(i);
deleteFileOrThrow(d);
}
}
| public static void deleteContents(File dir) throws IOException {
if (!dir.isDirectory()) {
throw new IllegalArgumentException("not a directory: " + dir);
}
final LinkedList<File> dirs = new LinkedList<File>();
dirs.add(dir);
final ArrayList<File> emptyDirs = new ArrayList<File>();
while (!dirs.isEmpty()) {
final File d = dirs.remove();
final File[] fs = d.listFiles();
if (fs != null) {
for (File f : fs) {
if (f.isDirectory()) {
dirs.add(f);
} else {
deleteFileOrThrow(f);
}
}
}
emptyDirs.add(d);
}
for (int i = emptyDirs.size() - 1; i >= 0; i--) {
final File d = emptyDirs.get(i);
deleteFileOrThrow(d);
}
}
|
diff --git a/src/com/dedaulus/cinematty/framework/SearchSuggestionsProvider.java b/src/com/dedaulus/cinematty/framework/SearchSuggestionsProvider.java
index 2b91351..7946dee 100644
--- a/src/com/dedaulus/cinematty/framework/SearchSuggestionsProvider.java
+++ b/src/com/dedaulus/cinematty/framework/SearchSuggestionsProvider.java
@@ -1,126 +1,126 @@
package com.dedaulus.cinematty.framework;
import android.app.Application;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dedaulus.cinematty.CinemattyApplication;
import com.dedaulus.cinematty.R;
import com.dedaulus.cinematty.framework.tools.Constants;
import com.dedaulus.cinematty.framework.tools.DataConverter;
import java.util.Map;
/**
* User: Dedaulus
* Date: 27.02.12
* Time: 19:53
*/
public class SearchSuggestionsProvider extends ContentProvider {
private static final UriMatcher uriMatcher;
public static final String AUTHORITY = "com.dedaulus.cinematty.provider";
private static final String TABLE_NAME = "search_suggestions";
private static final int SS = 1;
private CinemattyApplication app;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, TABLE_NAME, SS);
}
@Override
public boolean onCreate() {
Application app = (Application)getContext();
if (app == null) return false;
this.app = (CinemattyApplication)app;
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
MatrixCursor cursor = new MatrixCursor(new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_ICON_1
});
if (selectionArgs[0].length() > 1) {
String searchString = selectionArgs[0];
- String pattern = new StringBuilder().append("(?i).* [\"«„”‘]*").append(searchString).append(".*|(?i)^[\"«„”‘]*").append(searchString).append(".*").toString();
+ String pattern = new StringBuilder().append("(?i).* [\"«„”‘]*").append(searchString).append(".*|(?i)^[\"«„”‘]*").append(searchString).append(".*").append("|(?i).*-").append(searchString).append(".*").toString();
int i = 0;
Map<String, Cinema> cinemas = app.getSettings().getCinemas();
for (String caption : cinemas.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.CINEMA_TYPE_ID);
row.add(caption);
row.add(cinemas.get(caption).getAddress());
row.add(R.drawable.ic_search_cinema);
++i;
}
}
Map<String, Movie> movies = app.getSettings().getMovies();
for (String caption : movies.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.MOVIE_TYPE_ID);
row.add(caption);
row.add(DataConverter.genresToString(movies.get(caption).getGenres().values()));
row.add(R.drawable.ic_search_movie);
++i;
}
}
Map<String, MovieActor> actors = app.getSettings().getActors();
for (String caption : actors.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.ACTOR_TYPE_ID);
row.add(caption);
row.add(null);
row.add(R.drawable.ic_search_actor);
++i;
}
}
}
return cursor;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
return null;
}
@Override
public int delete(Uri uri, String s, String[] strings) {
return 0;
}
@Override
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
}
| true | true | public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
MatrixCursor cursor = new MatrixCursor(new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_ICON_1
});
if (selectionArgs[0].length() > 1) {
String searchString = selectionArgs[0];
String pattern = new StringBuilder().append("(?i).* [\"«„”‘]*").append(searchString).append(".*|(?i)^[\"«„”‘]*").append(searchString).append(".*").toString();
int i = 0;
Map<String, Cinema> cinemas = app.getSettings().getCinemas();
for (String caption : cinemas.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.CINEMA_TYPE_ID);
row.add(caption);
row.add(cinemas.get(caption).getAddress());
row.add(R.drawable.ic_search_cinema);
++i;
}
}
Map<String, Movie> movies = app.getSettings().getMovies();
for (String caption : movies.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.MOVIE_TYPE_ID);
row.add(caption);
row.add(DataConverter.genresToString(movies.get(caption).getGenres().values()));
row.add(R.drawable.ic_search_movie);
++i;
}
}
Map<String, MovieActor> actors = app.getSettings().getActors();
for (String caption : actors.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.ACTOR_TYPE_ID);
row.add(caption);
row.add(null);
row.add(R.drawable.ic_search_actor);
++i;
}
}
}
return cursor;
}
| public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
MatrixCursor cursor = new MatrixCursor(new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_ICON_1
});
if (selectionArgs[0].length() > 1) {
String searchString = selectionArgs[0];
String pattern = new StringBuilder().append("(?i).* [\"«„”‘]*").append(searchString).append(".*|(?i)^[\"«„”‘]*").append(searchString).append(".*").append("|(?i).*-").append(searchString).append(".*").toString();
int i = 0;
Map<String, Cinema> cinemas = app.getSettings().getCinemas();
for (String caption : cinemas.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.CINEMA_TYPE_ID);
row.add(caption);
row.add(cinemas.get(caption).getAddress());
row.add(R.drawable.ic_search_cinema);
++i;
}
}
Map<String, Movie> movies = app.getSettings().getMovies();
for (String caption : movies.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.MOVIE_TYPE_ID);
row.add(caption);
row.add(DataConverter.genresToString(movies.get(caption).getGenres().values()));
row.add(R.drawable.ic_search_movie);
++i;
}
}
Map<String, MovieActor> actors = app.getSettings().getActors();
for (String caption : actors.keySet()) {
if (caption.matches(pattern)) {
MatrixCursor.RowBuilder row = cursor.newRow();
row.add(i);
row.add(caption);
row.add(Constants.ACTOR_TYPE_ID);
row.add(caption);
row.add(null);
row.add(R.drawable.ic_search_actor);
++i;
}
}
}
return cursor;
}
|
diff --git a/kiji-mapreduce/src/main/java/org/kiji/mapreduce/bulkimport/AvroBulkImporter.java b/kiji-mapreduce/src/main/java/org/kiji/mapreduce/bulkimport/AvroBulkImporter.java
index 99b702c..d332988 100644
--- a/kiji-mapreduce/src/main/java/org/kiji/mapreduce/bulkimport/AvroBulkImporter.java
+++ b/kiji-mapreduce/src/main/java/org/kiji/mapreduce/bulkimport/AvroBulkImporter.java
@@ -1,80 +1,80 @@
/**
* (c) Copyright 2012 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kiji.mapreduce.bulkimport;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.mapred.AvroKey;
import org.apache.hadoop.io.NullWritable;
import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.Inheritance;
import org.kiji.mapreduce.KijiTableContext;
import org.kiji.mapreduce.avro.AvroKeyReader;
/**
* Base class for Kiji bulk importers that process Avro container
* files. You may extend this class to be used as the --importer flag
* when you have specified an --input flag of
* <code>avro:<filename></code> in your <code>kiji
* bulk-import</code> command.
*
* @param <T> The type of the Avro data to be processed.
*/
@ApiAudience.Public
@Inheritance.Extensible
public abstract class AvroBulkImporter<T> extends KijiBulkImporter<AvroKey<T>, NullWritable>
implements AvroKeyReader {
@Override
- public void produce(AvroKey<T> key, NullWritable ignore,
+ public final void produce(AvroKey<T> key, NullWritable ignore,
KijiTableContext context)
throws IOException {
produce(key.datum(), context);
}
/**
* Process an Avro datum from the input container file to produce
* Kiji output.
*
* @param datum An Avro datum from the input file.
* @param context A context which can be used to write Kiji data.
* data should not be written for this input record.
* @throws IOException If there is an error.
*/
protected abstract void produce(T datum, KijiTableContext context)
throws IOException;
/**
* Specifies the expected reader schema for the input data. By default, this
* returns null, meaning that it will accept as input any writer schema
* encountered in the input. Clients expecting homogenous input elements
* (e.g., those using Avro specific record classes) should specify their
* schema here.
*
* @throws IOException If there is an error determining the schema.
* @return The input avro schema.
*/
@Override
public Schema getAvroKeyReaderSchema() throws IOException {
return null;
}
}
| true | true | public void produce(AvroKey<T> key, NullWritable ignore,
KijiTableContext context)
throws IOException {
produce(key.datum(), context);
}
| public final void produce(AvroKey<T> key, NullWritable ignore,
KijiTableContext context)
throws IOException {
produce(key.datum(), context);
}
|
diff --git a/maqetta.core.server/src/maqetta/core/server/DavinciReviewServlet.java b/maqetta.core.server/src/maqetta/core/server/DavinciReviewServlet.java
index a94cd4d77..41011145a 100644
--- a/maqetta.core.server/src/maqetta/core/server/DavinciReviewServlet.java
+++ b/maqetta.core.server/src/maqetta/core/server/DavinciReviewServlet.java
@@ -1,222 +1,229 @@
package maqetta.core.server;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import maqetta.core.server.DavinciPageServlet;
import maqetta.core.server.user.ReviewManager;
import org.davinci.server.internal.Activator;
import org.davinci.server.review.Constants;
import org.davinci.server.review.ReviewObject;
import org.davinci.server.review.Version;
import org.davinci.server.review.cache.ReviewCacheManager;
import org.davinci.server.review.user.IDesignerUser;
import org.davinci.server.user.IUser;
import org.davinci.server.util.JSONWriter;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.maqetta.server.IDavinciServerConstants;
import org.maqetta.server.IVResource;
import org.maqetta.server.ServerManager;
import org.maqetta.server.VURL;
@SuppressWarnings("serial")
public class DavinciReviewServlet extends DavinciPageServlet {
private ReviewManager reviewManager;
protected String revieweeName;
protected String noView;
@Override
public void initialize() {
super.initialize();
reviewManager = ReviewManager.getReviewManager();
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.service(req, resp);
if ( !ReviewCacheManager.$.isAlive() )
ReviewCacheManager.$.start();
}
public String getLoginUrl(HttpServletRequest req) {
String loginUrl = serverManager.getDavinciProperty("loginUrl");
String params = "";
if ( null == loginUrl ) {
loginUrl = req.getContextPath();
} // Ensure loginUrl is not null
String pseparator = loginUrl.indexOf("?") > 0 ? "&" : "?";
if ( revieweeName != null ) {
params = pseparator + "revieweeuser=" + revieweeName;
}
return loginUrl + params;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if ( serverManager == null ) {
initialize();
}
revieweeName = req.getParameter("revieweeuser");
noView = req.getParameter("noview");
String contextString = req.getContextPath();
String pathInfo = req.getPathInfo();
IUser user = (IUser) req.getSession().getAttribute(IDavinciServerConstants.SESSION_USER);
if ( ServerManager.DEBUG_IO_TO_CONSOLE ) {
System.out.println("Review Servlet request: " + pathInfo + ", logged in= " + (user != null ? user.getUserName() : "guest"));
}
if ( user == null ) {
req.getSession().setAttribute(IDavinciServerConstants.REDIRECT_TO, req.getRequestURL().toString());
+ String requestVersion = req.getParameter("version");
+ if(requestVersion!=null && !requestVersion.equals("")){
+ Cookie versionCookie = new Cookie(Constants.REVIEW_VERSION, requestVersion);
+ /* have to set the path to delete it later from the client */
+ versionCookie.setPath("/");
+ resp.addCookie(versionCookie);
+ }
resp.sendRedirect(this.getLoginUrl(req));
return;
}
if ( pathInfo == null || pathInfo.equals("") ) {
ReviewObject reviewObject = (ReviewObject) req.getSession().getAttribute(Constants.REVIEW_INFO);
if ( reviewObject == null ) {
// Because the requested URL is /review the empty review object
// means we do not have a designer name: Error.
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER, reviewObject.getDesignerName()));
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER_EMAIL, reviewObject.getDesignerEmail()));
if ( reviewObject.getCommentId() != null ) {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_CMTID, reviewObject.getCommentId()));
}
if ( reviewObject.getVersion() != null ) {
Cookie versionCookie = new Cookie(Constants.REVIEW_VERSION, reviewObject.getVersion());
/* have to set the path to delete it later from the client */
versionCookie.setPath("/maqetta/");
resp.addCookie(versionCookie);
}
// writeReviewPage(req, resp, "review.html");
// writeMainPage(req, resp);
resp.sendRedirect("/maqetta/");
}
} else {
IPath path = new Path(pathInfo);
String prefix = path.segment(0);
if ( prefix == null ) {
resp.sendRedirect(contextString + "/review");
return;
}
if ( prefix.equals(IDavinciServerConstants.APP_URL.substring(1))
|| prefix.equals(Constants.CMD_URL.substring(1)) ) {
// Forward to DavinciPageServlet such as "/app/img/1.jpg" or "cmd/getUserInfo"
req.getRequestDispatcher(pathInfo).forward(req, resp);
return;
}
if ( handleReviewRequest(req, resp, path) || handleLibraryRequest(req, resp, path, user) ) {
return;
}
// Check if it is a valid user name.
// If it is a valid user name, do login
// Else, error.
IUser designer = userManager.getUser(prefix);
if ( designer == null ) {
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
ReviewObject reviewObject = new ReviewObject(prefix);
reviewObject.setDesignerEmail(designer.getPerson().getEmail());
if ( path.segmentCount() > 2 ) {
// Token = 20100101/project1/folder1/sample1.html/default
String commentId = path.segment(path.segmentCount() - 1);
String fileName = path.removeLastSegments(1).removeFirstSegments(1).toPortableString();
reviewObject.setCommentId(commentId);
}
reviewObject.setVersion(req.getParameter("version"));
req.getSession().setAttribute(Constants.REVIEW_INFO, reviewObject);
resp.sendRedirect(contextString + "/review");
return;
}
}
}
@Override
protected boolean handleLibraryRequest(HttpServletRequest req, HttpServletResponse resp,
IPath path, IUser user) throws ServletException, IOException {
// Remove the following URL prefix
// /user/heguyi/ws/workspace/.review/snapshot/20100101/project1/lib/dojo/dojo.js
// to
// project1/lib/dojo/dojo.js
String version = null;
String ownerId = null;
String projectName = null;
if ( isValidReviewPath(path) ) {
ownerId = path.segment(1);
version = path.segment(6);
projectName = path.segment(7);
path = path.removeFirstSegments(7);
// So that each snapshot can be mapped to its virtual lib path correctly.
path = ReviewManager.adjustPath(path, ownerId, version, projectName);
}
return super.handleLibraryRequest(req, resp, path, user);
}
protected boolean handleReviewRequest(HttpServletRequest req, HttpServletResponse resp,
IPath path) throws ServletException, IOException {
// Get the requested resources from the designer's folder
// Remove the following URL prefix
// /user/heguyi/ws/workspace/.review/snapshot/20100101/project1/folder1/sample1.html
// to
// /.review/snapshot/20100101/project1/folder1/sample1.html
if ( isValidReviewPath(path) ) {
String designerName = path.segment(1);
path = path.removeFirstSegments(4);
IVResource vr = reviewManager.getDesignerUser(designerName).getResource(path);
if ( vr != null ) {
writePage(req, resp, vr, true);
return true;
}
}
return false;
}
protected void writeReviewPage(HttpServletRequest req, HttpServletResponse resp, String path)
throws ServletException, IOException {
URL resourceURL = Activator.getActivator().getOtherBundle("maqetta.core.client").getEntry("/WebContent/" + path);
VURL v = new VURL(resourceURL);
writePage(req, resp, v, false);
}
private boolean isValidReviewPath(IPath path) {
String designerName = path.segment(1);
// Verify the user
if ( designerName == null ) {
return false;
}
IUser user = userManager.getUser(designerName);
return user != null && path.segmentCount() > 8 && path.segment(4).equals(".review")
&& path.segment(5).equals("snapshot") && path.segment(0).equals("user")
&& path.segment(2).equals("ws") && path.segment(3).equals("workspace");
}
@Override
public void destroy() {
ReviewCacheManager.$.markStop();
ReviewCacheManager.$.destroyAllReview();
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if ( serverManager == null ) {
initialize();
}
revieweeName = req.getParameter("revieweeuser");
noView = req.getParameter("noview");
String contextString = req.getContextPath();
String pathInfo = req.getPathInfo();
IUser user = (IUser) req.getSession().getAttribute(IDavinciServerConstants.SESSION_USER);
if ( ServerManager.DEBUG_IO_TO_CONSOLE ) {
System.out.println("Review Servlet request: " + pathInfo + ", logged in= " + (user != null ? user.getUserName() : "guest"));
}
if ( user == null ) {
req.getSession().setAttribute(IDavinciServerConstants.REDIRECT_TO, req.getRequestURL().toString());
resp.sendRedirect(this.getLoginUrl(req));
return;
}
if ( pathInfo == null || pathInfo.equals("") ) {
ReviewObject reviewObject = (ReviewObject) req.getSession().getAttribute(Constants.REVIEW_INFO);
if ( reviewObject == null ) {
// Because the requested URL is /review the empty review object
// means we do not have a designer name: Error.
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER, reviewObject.getDesignerName()));
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER_EMAIL, reviewObject.getDesignerEmail()));
if ( reviewObject.getCommentId() != null ) {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_CMTID, reviewObject.getCommentId()));
}
if ( reviewObject.getVersion() != null ) {
Cookie versionCookie = new Cookie(Constants.REVIEW_VERSION, reviewObject.getVersion());
/* have to set the path to delete it later from the client */
versionCookie.setPath("/maqetta/");
resp.addCookie(versionCookie);
}
// writeReviewPage(req, resp, "review.html");
// writeMainPage(req, resp);
resp.sendRedirect("/maqetta/");
}
} else {
IPath path = new Path(pathInfo);
String prefix = path.segment(0);
if ( prefix == null ) {
resp.sendRedirect(contextString + "/review");
return;
}
if ( prefix.equals(IDavinciServerConstants.APP_URL.substring(1))
|| prefix.equals(Constants.CMD_URL.substring(1)) ) {
// Forward to DavinciPageServlet such as "/app/img/1.jpg" or "cmd/getUserInfo"
req.getRequestDispatcher(pathInfo).forward(req, resp);
return;
}
if ( handleReviewRequest(req, resp, path) || handleLibraryRequest(req, resp, path, user) ) {
return;
}
// Check if it is a valid user name.
// If it is a valid user name, do login
// Else, error.
IUser designer = userManager.getUser(prefix);
if ( designer == null ) {
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
ReviewObject reviewObject = new ReviewObject(prefix);
reviewObject.setDesignerEmail(designer.getPerson().getEmail());
if ( path.segmentCount() > 2 ) {
// Token = 20100101/project1/folder1/sample1.html/default
String commentId = path.segment(path.segmentCount() - 1);
String fileName = path.removeLastSegments(1).removeFirstSegments(1).toPortableString();
reviewObject.setCommentId(commentId);
}
reviewObject.setVersion(req.getParameter("version"));
req.getSession().setAttribute(Constants.REVIEW_INFO, reviewObject);
resp.sendRedirect(contextString + "/review");
return;
}
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if ( serverManager == null ) {
initialize();
}
revieweeName = req.getParameter("revieweeuser");
noView = req.getParameter("noview");
String contextString = req.getContextPath();
String pathInfo = req.getPathInfo();
IUser user = (IUser) req.getSession().getAttribute(IDavinciServerConstants.SESSION_USER);
if ( ServerManager.DEBUG_IO_TO_CONSOLE ) {
System.out.println("Review Servlet request: " + pathInfo + ", logged in= " + (user != null ? user.getUserName() : "guest"));
}
if ( user == null ) {
req.getSession().setAttribute(IDavinciServerConstants.REDIRECT_TO, req.getRequestURL().toString());
String requestVersion = req.getParameter("version");
if(requestVersion!=null && !requestVersion.equals("")){
Cookie versionCookie = new Cookie(Constants.REVIEW_VERSION, requestVersion);
/* have to set the path to delete it later from the client */
versionCookie.setPath("/");
resp.addCookie(versionCookie);
}
resp.sendRedirect(this.getLoginUrl(req));
return;
}
if ( pathInfo == null || pathInfo.equals("") ) {
ReviewObject reviewObject = (ReviewObject) req.getSession().getAttribute(Constants.REVIEW_INFO);
if ( reviewObject == null ) {
// Because the requested URL is /review the empty review object
// means we do not have a designer name: Error.
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER, reviewObject.getDesignerName()));
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_DESIGNER_EMAIL, reviewObject.getDesignerEmail()));
if ( reviewObject.getCommentId() != null ) {
resp.addCookie(new Cookie(Constants.REVIEW_COOKIE_CMTID, reviewObject.getCommentId()));
}
if ( reviewObject.getVersion() != null ) {
Cookie versionCookie = new Cookie(Constants.REVIEW_VERSION, reviewObject.getVersion());
/* have to set the path to delete it later from the client */
versionCookie.setPath("/maqetta/");
resp.addCookie(versionCookie);
}
// writeReviewPage(req, resp, "review.html");
// writeMainPage(req, resp);
resp.sendRedirect("/maqetta/");
}
} else {
IPath path = new Path(pathInfo);
String prefix = path.segment(0);
if ( prefix == null ) {
resp.sendRedirect(contextString + "/review");
return;
}
if ( prefix.equals(IDavinciServerConstants.APP_URL.substring(1))
|| prefix.equals(Constants.CMD_URL.substring(1)) ) {
// Forward to DavinciPageServlet such as "/app/img/1.jpg" or "cmd/getUserInfo"
req.getRequestDispatcher(pathInfo).forward(req, resp);
return;
}
if ( handleReviewRequest(req, resp, path) || handleLibraryRequest(req, resp, path, user) ) {
return;
}
// Check if it is a valid user name.
// If it is a valid user name, do login
// Else, error.
IUser designer = userManager.getUser(prefix);
if ( designer == null ) {
resp.sendRedirect(this.getLoginUrl(req));
return;
} else {
ReviewObject reviewObject = new ReviewObject(prefix);
reviewObject.setDesignerEmail(designer.getPerson().getEmail());
if ( path.segmentCount() > 2 ) {
// Token = 20100101/project1/folder1/sample1.html/default
String commentId = path.segment(path.segmentCount() - 1);
String fileName = path.removeLastSegments(1).removeFirstSegments(1).toPortableString();
reviewObject.setCommentId(commentId);
}
reviewObject.setVersion(req.getParameter("version"));
req.getSession().setAttribute(Constants.REVIEW_INFO, reviewObject);
resp.sendRedirect(contextString + "/review");
return;
}
}
}
|
diff --git a/tests/org/gridlab/gridsphere/portletcontainer/descriptor/PortletDescriptorTest.java b/tests/org/gridlab/gridsphere/portletcontainer/descriptor/PortletDescriptorTest.java
index df0d64e6c..dc8c227cc 100644
--- a/tests/org/gridlab/gridsphere/portletcontainer/descriptor/PortletDescriptorTest.java
+++ b/tests/org/gridlab/gridsphere/portletcontainer/descriptor/PortletDescriptorTest.java
@@ -1,228 +1,228 @@
/*
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.portletcontainer.descriptor;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.Test;
import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory;
import org.gridlab.gridsphere.portlet.impl.SportletLog;
import org.gridlab.gridsphere.portlet.PortletLog;
import org.gridlab.gridsphere.portletcontainer.descriptor.*;
import org.gridlab.gridsphere.portletcontainer.GridSphereConfig;
import org.gridlab.gridsphere.portletcontainer.GridSphereConfigProperties;
import org.gridlab.gridsphere.core.persistence.castor.descriptor.DescriptorException;
import org.gridlab.gridsphere.core.persistence.castor.descriptor.ConfigParam;
import org.exolab.castor.types.AnyNode;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
/**
* This is the base fixture for service testing. Provides a service factory and the
* properties file.
*/
public class PortletDescriptorTest extends TestCase {
public PortletDescriptorTest(String name) {
super(name);
}
public static void main (String[] args) throws Exception{
junit.textui.TestRunner.run(suite());
}
public static Test suite ( ) {
return new TestSuite(PortletDescriptorTest.class);
}
public void testDescriptor() {
PortletDeploymentDescriptor pdd = null;
String portletFile = "webapps/gridsphere/WEB-INF/conf/test/portlet-test.xml";
String mappingFile = "webapps/gridsphere/WEB-INF/conf/mapping/portlet-mapping.xml";
try {
pdd = new PortletDeploymentDescriptor(portletFile, mappingFile);
} catch (IOException e) {
fail("IO error unmarshalling " + portletFile + " using " + mappingFile + " : " + e.getMessage());
} catch (DescriptorException e) {
fail("Unable to unmarshall " + portletFile + " using " + mappingFile + " : " + e.getMessage());
}
- Vector defs = pdd.getPortletDef();
+ List defs = pdd.getPortletDef();
// assertEquals(expected, actual)
// we have one app descriptions
assertEquals(1, defs.size());
PortletDefinition def = (PortletDefinition)defs.get(0);
PortletApp portletApp = def.getPortletApp();
- Vector concreteApps = def.getConcreteApps();
+ List concreteApps = def.getConcreteApps();
// we have two concrete portlet apps
assertEquals(concreteApps.size(), 2);
ConcretePortletApplication concreteOne = (ConcretePortletApplication)concreteApps.get(0);
ConcretePortletApplication concreteTwo = (ConcretePortletApplication)concreteApps.get(1);
assertEquals("org.gridlab.gridsphere.portlets.core.HelloWorld.666", portletApp.getID());
assertEquals("Hello World", portletApp.getPortletName());
assertEquals("hello", portletApp.getServletName());
CacheInfo c = portletApp.getCacheInfo();
assertEquals(120, c.getExpires());
assertEquals("true", c.getShared());
AllowsWindowStates winstatelist = portletApp.getAllowsWindowStates();
List winstates = winstatelist.getWindowStatesAsStrings();
assertEquals(2, winstates.size());
assertEquals("maximized", (String)winstates.get(0));
assertEquals("minimized", (String)winstates.get(1));
SupportsModes smodes = portletApp.getSupportsModes();
List mlist = smodes.getMarkupList();
assertEquals(2, mlist.size());
Markup m = (Markup)mlist.get(0);
assertEquals("html", m.getName());
List modes = m.getPortletModes();
assertEquals(4, modes.size());
AnyNode mod = (AnyNode)modes.get(0);
assertEquals("view", mod.getLocalName());
m = (Markup)mlist.get(1);
assertEquals("wml", m.getName());
// Check concrete one portal data
assertEquals("org.gridlab.gridsphere.portlets.core.HelloWorld.666.2", concreteOne.getID());
List contextList = concreteOne.getContextParamList();
assertEquals(contextList.size(), 2);
ConfigParam one = (ConfigParam)contextList.get(0);
ConfigParam two = (ConfigParam)contextList.get(1);
assertEquals("buzzle", one.getParamName());
assertEquals("yea", one.getParamValue());
assertEquals("beezle", two.getParamName());
assertEquals("yo", two.getParamValue());
ConcretePortletInfo onePI = concreteOne.getConcretePortletInfo();
assertEquals("Hello World 1", onePI.getName());
assertEquals("en", onePI.getDefaultLocale());
List langList = onePI.getLanguageList();
assertEquals(langList.size(), 2);
LanguageInfo langOne = (LanguageInfo)langList.get(0);
LanguageInfo langTwo = (LanguageInfo)langList.get(1);
assertEquals("Here is a simple portlet", langOne.getDescription());
assertEquals("portlet hello world", langOne.getKeywords());
assertEquals("en_US", langOne.getLocale());
assertEquals("Hello World - Sample Portlet #1", langOne.getTitle());
assertEquals("Hello World", langOne.getTitleShort());
assertEquals("Hier ist ein gleicht portlet", langTwo.getDescription());
assertEquals("portlet hallo welt", langTwo.getKeywords());
assertEquals("en_DE", langTwo.getLocale());
assertEquals("Hallo Welt - Sample Portlet #1", langTwo.getTitle());
assertEquals("Hallo Welt", langTwo.getTitleShort());
Owner o = onePI.getOwner();
assertEquals(o.getRoleName(), "SUPER");
List groups = onePI.getGroupList();
assertEquals(groups.size(), 1);
Group g = (Group)groups.get(0);
assertEquals("ANY", g.getGroupName());
List roles = onePI.getRoleList();
assertEquals(groups.size(), 1);
Role r = (Role)roles.get(0);
assertEquals("GUEST", r.getRoleName());
List configList = onePI.getConfigParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals("Portlet Mistress", one.getParamName());
assertEquals("[email protected]", one.getParamValue());
// Check concrete two portal data
assertEquals(concreteTwo.getID(), "org.gridlab.gridsphere.portlets.core.HelloWorld.666.4");
configList = concreteTwo.getContextParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals(one.getParamName(), "Portlet Master");
assertEquals(one.getParamValue(), "[email protected]");
onePI = concreteTwo.getConcretePortletInfo();
assertEquals(onePI.getName(), "Hello World 2");
assertEquals(onePI.getDefaultLocale(), "en");
langList = onePI.getLanguageList();
assertEquals(langList.size(), 1);
langOne = (LanguageInfo)langList.get(0);
assertEquals(langOne.getDescription(), "Here is another simple portlet");
assertEquals(langOne.getKeywords(), "portlet hello world");
assertEquals(langOne.getLocale(), "en_US");
assertEquals(langOne.getTitle(), "Hello World - Sample Portlet #2");
assertEquals(langOne.getTitleShort(), "Hello World");
Owner ow = onePI.getOwner();
assertEquals(ow.getRoleName(), "ADMIN");
assertEquals(ow.getGroupName(), "CACTUS");
List groupsList = onePI.getGroupList();
assertEquals(groups.size(), 1);
Group gr = (Group)groupsList.get(0);
assertEquals("CACTUS", gr.getGroupName());
List rolez = onePI.getRoleList();
assertEquals(groups.size(), 1);
Role rol = (Role)rolez.get(0);
assertEquals("USER", rol.getRoleName());
configList = onePI.getConfigParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals("Portlet Master", one.getParamName());
assertEquals("[email protected]", one.getParamValue());
// demonstrate saving
/*
Hashtable store = new Hashtable();
store.put("beezle", "yo");
store.put("buzzle", "yea");
Enumeration enum = store.keys();
Vector list = new Vector();
while (enum.hasMoreElements()) {
String k = (String)enum.nextElement();
System.err.println(k);
String value = (String)store.get(k);
ConfigParam parms = new ConfigParam(k, value);
list.add(parms);
}
concreteOne.setID("whose your daddy?");
concreteOne.setContextParamList(list);
portletApp.setPortletName("yo dude");
pdd.setPortletAppDescriptor(portletApp);
pdd.setConcretePortletApplication(concreteOne);
try {
pdd.save("/tmp/portlet.xml", "webapps/gridsphere/WEB-INF/conf/mapping/portlet-mapping.xml");
} catch (Exception e) {
System.err.println("Unable to save SportletApplicationSettings: " + e.getMessage());
}
*/
}
}
| false | true | public void testDescriptor() {
PortletDeploymentDescriptor pdd = null;
String portletFile = "webapps/gridsphere/WEB-INF/conf/test/portlet-test.xml";
String mappingFile = "webapps/gridsphere/WEB-INF/conf/mapping/portlet-mapping.xml";
try {
pdd = new PortletDeploymentDescriptor(portletFile, mappingFile);
} catch (IOException e) {
fail("IO error unmarshalling " + portletFile + " using " + mappingFile + " : " + e.getMessage());
} catch (DescriptorException e) {
fail("Unable to unmarshall " + portletFile + " using " + mappingFile + " : " + e.getMessage());
}
Vector defs = pdd.getPortletDef();
// assertEquals(expected, actual)
// we have one app descriptions
assertEquals(1, defs.size());
PortletDefinition def = (PortletDefinition)defs.get(0);
PortletApp portletApp = def.getPortletApp();
Vector concreteApps = def.getConcreteApps();
// we have two concrete portlet apps
assertEquals(concreteApps.size(), 2);
ConcretePortletApplication concreteOne = (ConcretePortletApplication)concreteApps.get(0);
ConcretePortletApplication concreteTwo = (ConcretePortletApplication)concreteApps.get(1);
assertEquals("org.gridlab.gridsphere.portlets.core.HelloWorld.666", portletApp.getID());
assertEquals("Hello World", portletApp.getPortletName());
assertEquals("hello", portletApp.getServletName());
CacheInfo c = portletApp.getCacheInfo();
assertEquals(120, c.getExpires());
assertEquals("true", c.getShared());
AllowsWindowStates winstatelist = portletApp.getAllowsWindowStates();
List winstates = winstatelist.getWindowStatesAsStrings();
assertEquals(2, winstates.size());
assertEquals("maximized", (String)winstates.get(0));
assertEquals("minimized", (String)winstates.get(1));
SupportsModes smodes = portletApp.getSupportsModes();
List mlist = smodes.getMarkupList();
assertEquals(2, mlist.size());
Markup m = (Markup)mlist.get(0);
assertEquals("html", m.getName());
List modes = m.getPortletModes();
assertEquals(4, modes.size());
AnyNode mod = (AnyNode)modes.get(0);
assertEquals("view", mod.getLocalName());
m = (Markup)mlist.get(1);
assertEquals("wml", m.getName());
// Check concrete one portal data
assertEquals("org.gridlab.gridsphere.portlets.core.HelloWorld.666.2", concreteOne.getID());
List contextList = concreteOne.getContextParamList();
assertEquals(contextList.size(), 2);
ConfigParam one = (ConfigParam)contextList.get(0);
ConfigParam two = (ConfigParam)contextList.get(1);
assertEquals("buzzle", one.getParamName());
assertEquals("yea", one.getParamValue());
assertEquals("beezle", two.getParamName());
assertEquals("yo", two.getParamValue());
ConcretePortletInfo onePI = concreteOne.getConcretePortletInfo();
assertEquals("Hello World 1", onePI.getName());
assertEquals("en", onePI.getDefaultLocale());
List langList = onePI.getLanguageList();
assertEquals(langList.size(), 2);
LanguageInfo langOne = (LanguageInfo)langList.get(0);
LanguageInfo langTwo = (LanguageInfo)langList.get(1);
assertEquals("Here is a simple portlet", langOne.getDescription());
assertEquals("portlet hello world", langOne.getKeywords());
assertEquals("en_US", langOne.getLocale());
assertEquals("Hello World - Sample Portlet #1", langOne.getTitle());
assertEquals("Hello World", langOne.getTitleShort());
assertEquals("Hier ist ein gleicht portlet", langTwo.getDescription());
assertEquals("portlet hallo welt", langTwo.getKeywords());
assertEquals("en_DE", langTwo.getLocale());
assertEquals("Hallo Welt - Sample Portlet #1", langTwo.getTitle());
assertEquals("Hallo Welt", langTwo.getTitleShort());
Owner o = onePI.getOwner();
assertEquals(o.getRoleName(), "SUPER");
List groups = onePI.getGroupList();
assertEquals(groups.size(), 1);
Group g = (Group)groups.get(0);
assertEquals("ANY", g.getGroupName());
List roles = onePI.getRoleList();
assertEquals(groups.size(), 1);
Role r = (Role)roles.get(0);
assertEquals("GUEST", r.getRoleName());
List configList = onePI.getConfigParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals("Portlet Mistress", one.getParamName());
assertEquals("[email protected]", one.getParamValue());
// Check concrete two portal data
assertEquals(concreteTwo.getID(), "org.gridlab.gridsphere.portlets.core.HelloWorld.666.4");
configList = concreteTwo.getContextParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals(one.getParamName(), "Portlet Master");
assertEquals(one.getParamValue(), "[email protected]");
onePI = concreteTwo.getConcretePortletInfo();
assertEquals(onePI.getName(), "Hello World 2");
assertEquals(onePI.getDefaultLocale(), "en");
langList = onePI.getLanguageList();
assertEquals(langList.size(), 1);
langOne = (LanguageInfo)langList.get(0);
assertEquals(langOne.getDescription(), "Here is another simple portlet");
assertEquals(langOne.getKeywords(), "portlet hello world");
assertEquals(langOne.getLocale(), "en_US");
assertEquals(langOne.getTitle(), "Hello World - Sample Portlet #2");
assertEquals(langOne.getTitleShort(), "Hello World");
Owner ow = onePI.getOwner();
assertEquals(ow.getRoleName(), "ADMIN");
assertEquals(ow.getGroupName(), "CACTUS");
List groupsList = onePI.getGroupList();
assertEquals(groups.size(), 1);
Group gr = (Group)groupsList.get(0);
assertEquals("CACTUS", gr.getGroupName());
List rolez = onePI.getRoleList();
assertEquals(groups.size(), 1);
Role rol = (Role)rolez.get(0);
assertEquals("USER", rol.getRoleName());
configList = onePI.getConfigParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals("Portlet Master", one.getParamName());
assertEquals("[email protected]", one.getParamValue());
// demonstrate saving
/*
Hashtable store = new Hashtable();
store.put("beezle", "yo");
store.put("buzzle", "yea");
Enumeration enum = store.keys();
Vector list = new Vector();
while (enum.hasMoreElements()) {
String k = (String)enum.nextElement();
System.err.println(k);
String value = (String)store.get(k);
ConfigParam parms = new ConfigParam(k, value);
list.add(parms);
}
concreteOne.setID("whose your daddy?");
concreteOne.setContextParamList(list);
portletApp.setPortletName("yo dude");
pdd.setPortletAppDescriptor(portletApp);
pdd.setConcretePortletApplication(concreteOne);
try {
pdd.save("/tmp/portlet.xml", "webapps/gridsphere/WEB-INF/conf/mapping/portlet-mapping.xml");
} catch (Exception e) {
System.err.println("Unable to save SportletApplicationSettings: " + e.getMessage());
}
*/
}
| public void testDescriptor() {
PortletDeploymentDescriptor pdd = null;
String portletFile = "webapps/gridsphere/WEB-INF/conf/test/portlet-test.xml";
String mappingFile = "webapps/gridsphere/WEB-INF/conf/mapping/portlet-mapping.xml";
try {
pdd = new PortletDeploymentDescriptor(portletFile, mappingFile);
} catch (IOException e) {
fail("IO error unmarshalling " + portletFile + " using " + mappingFile + " : " + e.getMessage());
} catch (DescriptorException e) {
fail("Unable to unmarshall " + portletFile + " using " + mappingFile + " : " + e.getMessage());
}
List defs = pdd.getPortletDef();
// assertEquals(expected, actual)
// we have one app descriptions
assertEquals(1, defs.size());
PortletDefinition def = (PortletDefinition)defs.get(0);
PortletApp portletApp = def.getPortletApp();
List concreteApps = def.getConcreteApps();
// we have two concrete portlet apps
assertEquals(concreteApps.size(), 2);
ConcretePortletApplication concreteOne = (ConcretePortletApplication)concreteApps.get(0);
ConcretePortletApplication concreteTwo = (ConcretePortletApplication)concreteApps.get(1);
assertEquals("org.gridlab.gridsphere.portlets.core.HelloWorld.666", portletApp.getID());
assertEquals("Hello World", portletApp.getPortletName());
assertEquals("hello", portletApp.getServletName());
CacheInfo c = portletApp.getCacheInfo();
assertEquals(120, c.getExpires());
assertEquals("true", c.getShared());
AllowsWindowStates winstatelist = portletApp.getAllowsWindowStates();
List winstates = winstatelist.getWindowStatesAsStrings();
assertEquals(2, winstates.size());
assertEquals("maximized", (String)winstates.get(0));
assertEquals("minimized", (String)winstates.get(1));
SupportsModes smodes = portletApp.getSupportsModes();
List mlist = smodes.getMarkupList();
assertEquals(2, mlist.size());
Markup m = (Markup)mlist.get(0);
assertEquals("html", m.getName());
List modes = m.getPortletModes();
assertEquals(4, modes.size());
AnyNode mod = (AnyNode)modes.get(0);
assertEquals("view", mod.getLocalName());
m = (Markup)mlist.get(1);
assertEquals("wml", m.getName());
// Check concrete one portal data
assertEquals("org.gridlab.gridsphere.portlets.core.HelloWorld.666.2", concreteOne.getID());
List contextList = concreteOne.getContextParamList();
assertEquals(contextList.size(), 2);
ConfigParam one = (ConfigParam)contextList.get(0);
ConfigParam two = (ConfigParam)contextList.get(1);
assertEquals("buzzle", one.getParamName());
assertEquals("yea", one.getParamValue());
assertEquals("beezle", two.getParamName());
assertEquals("yo", two.getParamValue());
ConcretePortletInfo onePI = concreteOne.getConcretePortletInfo();
assertEquals("Hello World 1", onePI.getName());
assertEquals("en", onePI.getDefaultLocale());
List langList = onePI.getLanguageList();
assertEquals(langList.size(), 2);
LanguageInfo langOne = (LanguageInfo)langList.get(0);
LanguageInfo langTwo = (LanguageInfo)langList.get(1);
assertEquals("Here is a simple portlet", langOne.getDescription());
assertEquals("portlet hello world", langOne.getKeywords());
assertEquals("en_US", langOne.getLocale());
assertEquals("Hello World - Sample Portlet #1", langOne.getTitle());
assertEquals("Hello World", langOne.getTitleShort());
assertEquals("Hier ist ein gleicht portlet", langTwo.getDescription());
assertEquals("portlet hallo welt", langTwo.getKeywords());
assertEquals("en_DE", langTwo.getLocale());
assertEquals("Hallo Welt - Sample Portlet #1", langTwo.getTitle());
assertEquals("Hallo Welt", langTwo.getTitleShort());
Owner o = onePI.getOwner();
assertEquals(o.getRoleName(), "SUPER");
List groups = onePI.getGroupList();
assertEquals(groups.size(), 1);
Group g = (Group)groups.get(0);
assertEquals("ANY", g.getGroupName());
List roles = onePI.getRoleList();
assertEquals(groups.size(), 1);
Role r = (Role)roles.get(0);
assertEquals("GUEST", r.getRoleName());
List configList = onePI.getConfigParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals("Portlet Mistress", one.getParamName());
assertEquals("[email protected]", one.getParamValue());
// Check concrete two portal data
assertEquals(concreteTwo.getID(), "org.gridlab.gridsphere.portlets.core.HelloWorld.666.4");
configList = concreteTwo.getContextParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals(one.getParamName(), "Portlet Master");
assertEquals(one.getParamValue(), "[email protected]");
onePI = concreteTwo.getConcretePortletInfo();
assertEquals(onePI.getName(), "Hello World 2");
assertEquals(onePI.getDefaultLocale(), "en");
langList = onePI.getLanguageList();
assertEquals(langList.size(), 1);
langOne = (LanguageInfo)langList.get(0);
assertEquals(langOne.getDescription(), "Here is another simple portlet");
assertEquals(langOne.getKeywords(), "portlet hello world");
assertEquals(langOne.getLocale(), "en_US");
assertEquals(langOne.getTitle(), "Hello World - Sample Portlet #2");
assertEquals(langOne.getTitleShort(), "Hello World");
Owner ow = onePI.getOwner();
assertEquals(ow.getRoleName(), "ADMIN");
assertEquals(ow.getGroupName(), "CACTUS");
List groupsList = onePI.getGroupList();
assertEquals(groups.size(), 1);
Group gr = (Group)groupsList.get(0);
assertEquals("CACTUS", gr.getGroupName());
List rolez = onePI.getRoleList();
assertEquals(groups.size(), 1);
Role rol = (Role)rolez.get(0);
assertEquals("USER", rol.getRoleName());
configList = onePI.getConfigParamList();
assertEquals(configList.size(), 1);
one = (ConfigParam)configList.get(0);
assertEquals("Portlet Master", one.getParamName());
assertEquals("[email protected]", one.getParamValue());
// demonstrate saving
/*
Hashtable store = new Hashtable();
store.put("beezle", "yo");
store.put("buzzle", "yea");
Enumeration enum = store.keys();
Vector list = new Vector();
while (enum.hasMoreElements()) {
String k = (String)enum.nextElement();
System.err.println(k);
String value = (String)store.get(k);
ConfigParam parms = new ConfigParam(k, value);
list.add(parms);
}
concreteOne.setID("whose your daddy?");
concreteOne.setContextParamList(list);
portletApp.setPortletName("yo dude");
pdd.setPortletAppDescriptor(portletApp);
pdd.setConcretePortletApplication(concreteOne);
try {
pdd.save("/tmp/portlet.xml", "webapps/gridsphere/WEB-INF/conf/mapping/portlet-mapping.xml");
} catch (Exception e) {
System.err.println("Unable to save SportletApplicationSettings: " + e.getMessage());
}
*/
}
|
diff --git a/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/functionalactions/FunctionalTalk.java b/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/functionalactions/FunctionalTalk.java
index 9a62988c..ff326cf0 100644
--- a/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/functionalactions/FunctionalTalk.java
+++ b/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/functionalactions/FunctionalTalk.java
@@ -1,172 +1,180 @@
/*******************************************************************************
* <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM>
* research group.
*
* Copyright 2005-2010 <e-UCM> research group.
*
* You can access a list of all the contributors to <e-Adventure> at:
* http://e-adventure.e-ucm.es/contributors
*
* <e-UCM> is a research group of the Department of Software Engineering
* and Artificial Intelligence at the Complutense University of Madrid
* (School of Computer Science).
*
* C Profesor Jose Garcia Santesmases sn,
* 28040 Madrid (Madrid), Spain.
*
* For more info please visit: <http://e-adventure.e-ucm.es> or
* <http://www.e-ucm.es>
*
* ****************************************************************************
*
* This file is part of <e-Adventure>, version 1.2.
*
* <e-Adventure> 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 3 of the License, or
* (at your option) any later version.
*
* <e-Adventure> 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 <e-Adventure>. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.eucm.eadventure.engine.core.control.functionaldata.functionalactions;
import java.util.List;
import es.eucm.eadventure.common.data.chapter.Action;
import es.eucm.eadventure.engine.core.control.ActionManager;
import es.eucm.eadventure.engine.core.control.DebugLog;
import es.eucm.eadventure.engine.core.control.Game;
import es.eucm.eadventure.engine.core.control.animations.AnimationState;
import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalConditions;
import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalElement;
import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalNPC;
import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalPlayer;
import es.eucm.eadventure.engine.core.control.functionaldata.functionaleffects.FunctionalEffects;
import es.eucm.eadventure.engine.core.data.GameText;
/**
* The action to talk with an npc
*
* @author Eugenio Marchiori
*/
public class FunctionalTalk extends FunctionalAction {
/**
* The default distance to keep between player and npc
*/
public static final int DEFAULT_DISTANCE_TO_KEEP = 35;
/**
* The functional npc to speak with
*/
FunctionalNPC npc;
/**
* True if there is a conversation
*/
private boolean anyConversation;
/**
* Constructor using a default action and the npc with which to talk
*
* @param action
* The original action
* @param npc
* The npc with which to talk
*/
public FunctionalTalk( Action action, FunctionalElement npc ) {
super( action );
this.npc = (FunctionalNPC) npc;
this.type = ActionManager.ACTION_TALK;
if( functionalPlayer != null )
keepDistance = this.functionalPlayer.getWidth( ) / 2;
else
keepDistance = DEFAULT_DISTANCE_TO_KEEP;
keepDistance += npc.getWidth( ) / 2;
List<Action> actions = this.npc.getNPC( ).getActions( );
+ Action originalAction = null;
anyConversation = false;
for( int i = 0; i < actions.size( ) && !anyConversation; i++ )
- if( actions.get( i ).getType( ) == Action.TALK_TO && new FunctionalConditions( actions.get( i ).getConditions( ) ).allConditionsOk( ) )
+ if( actions.get( i ).getType( ) == Action.TALK_TO && new FunctionalConditions( actions.get( i ).getConditions( ) ).allConditionsOk( ) ) {
+ originalAction = actions.get( i );
anyConversation = true;
+ }
if( anyConversation ) {
needsGoTo = true;
+ if (originalAction != null) {
+ needsGoTo = originalAction.isNeedsGoTo( );
+ //Better leave the distance automatically calculated.
+ //keepDistance = originalAction.getKeepDistance( );
+ }
}
else {
needsGoTo = false;
}
}
@Override
public void drawAditionalElements( ) {
}
@Override
public void setAnotherElement( FunctionalElement element ) {
}
@Override
public void start( FunctionalPlayer functionalPlayer ) {
this.functionalPlayer = functionalPlayer;
if( anyConversation ) {
if( npc != null ) {
if( npc.getX( ) > functionalPlayer.getX( ) )
functionalPlayer.setDirection( AnimationState.EAST );
else
functionalPlayer.setDirection( AnimationState.WEST );
}
finished = false;
}
else {
if( functionalPlayer.isAlwaysSynthesizer( ) )
functionalPlayer.speakWithFreeTTS( GameText.getTextTalkCannot( ), functionalPlayer.getPlayerVoice( ) );
else
functionalPlayer.speak( GameText.getTextTalkCannot( ), Game.getInstance().getGameDescriptor( ).isKeepShowing( ) );
finished = true;
}
DebugLog.player( "Start talk : " + npc.getNPC( ).getId( ) );
}
@Override
public void stop( ) {
finished = true;
}
@Override
public void update( long elapsedTime ) {
List<Action> actions = npc.getNPC( ).getActions( );
boolean triggeredConversation = false;
for( int i = 0; i < actions.size( ) && !triggeredConversation; i++ ) {
if( actions.get( i ).getType( ) == Action.TALK_TO && new FunctionalConditions( actions.get( i ).getConditions( ) ).allConditionsOk( ) ) {
Game.getInstance( ).setCurrentNPC( npc );
FunctionalEffects.storeAllEffects( actions.get( i ).getEffects( ) );
triggeredConversation = true;
}
}
if( !triggeredConversation ) {
if( functionalPlayer.isAlwaysSynthesizer( ) )
functionalPlayer.speakWithFreeTTS( GameText.getTextTalkCannot( ), functionalPlayer.getPlayerVoice( ) );
else
functionalPlayer.speak( GameText.getTextTalkCannot( ), Game.getInstance().getGameDescriptor( ).isKeepShowing( ) );
}
finished = true;
}
}
| false | true | public FunctionalTalk( Action action, FunctionalElement npc ) {
super( action );
this.npc = (FunctionalNPC) npc;
this.type = ActionManager.ACTION_TALK;
if( functionalPlayer != null )
keepDistance = this.functionalPlayer.getWidth( ) / 2;
else
keepDistance = DEFAULT_DISTANCE_TO_KEEP;
keepDistance += npc.getWidth( ) / 2;
List<Action> actions = this.npc.getNPC( ).getActions( );
anyConversation = false;
for( int i = 0; i < actions.size( ) && !anyConversation; i++ )
if( actions.get( i ).getType( ) == Action.TALK_TO && new FunctionalConditions( actions.get( i ).getConditions( ) ).allConditionsOk( ) )
anyConversation = true;
if( anyConversation ) {
needsGoTo = true;
}
else {
needsGoTo = false;
}
}
| public FunctionalTalk( Action action, FunctionalElement npc ) {
super( action );
this.npc = (FunctionalNPC) npc;
this.type = ActionManager.ACTION_TALK;
if( functionalPlayer != null )
keepDistance = this.functionalPlayer.getWidth( ) / 2;
else
keepDistance = DEFAULT_DISTANCE_TO_KEEP;
keepDistance += npc.getWidth( ) / 2;
List<Action> actions = this.npc.getNPC( ).getActions( );
Action originalAction = null;
anyConversation = false;
for( int i = 0; i < actions.size( ) && !anyConversation; i++ )
if( actions.get( i ).getType( ) == Action.TALK_TO && new FunctionalConditions( actions.get( i ).getConditions( ) ).allConditionsOk( ) ) {
originalAction = actions.get( i );
anyConversation = true;
}
if( anyConversation ) {
needsGoTo = true;
if (originalAction != null) {
needsGoTo = originalAction.isNeedsGoTo( );
//Better leave the distance automatically calculated.
//keepDistance = originalAction.getKeepDistance( );
}
}
else {
needsGoTo = false;
}
}
|
diff --git a/src/cgeo/geocaching/cgBase.java b/src/cgeo/geocaching/cgBase.java
index aff7918dd..52c4a6a7d 100644
--- a/src/cgeo/geocaching/cgBase.java
+++ b/src/cgeo/geocaching/cgBase.java
@@ -1,5563 +1,5563 @@
package cgeo.geocaching;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.format.DateUtils;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.widget.EditText;
import cgeo.geocaching.activity.ActivityMixin;
public class cgBase {
private final static Pattern patternGeocode = Pattern.compile("<meta name=\"og:url\" content=\"[^\"]+/(GC[0-9A-Z]+)\"[^>]*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternCacheId = Pattern.compile("/seek/log\\.aspx\\?ID=(\\d+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternCacheGuid = Pattern.compile(Pattern.quote("&wid=") + "([0-9a-z\\-]+)" + Pattern.quote("&"), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternType = Pattern.compile("<img src=\"[^\"]*/WptTypes/\\d+\\.gif\" alt=\"([^\"]+)\" (title=\"[^\"]*\" )?width=\"32\" height=\"32\"[^>]*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternName = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_CacheName\">([^<]+)<\\/span>[^<]*<\\/h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternSize = Pattern.compile("<div class=\"CacheSize[^\"]*\">[^<]*<p[^>]*>[^S]*Size[^:]*:[^<]*<span[^>]*>[^<]*<img src=\"[^\"]*/icons/container/[a-z_]+\\.gif\" alt=\"Size: ([^\"]+)\"[^>]*>[^<]*<small>[^<]*</small>[^<]*</span>[^<]*</p>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternDifficulty = Pattern.compile("<span id=\"ctl00_ContentBody_uxLegendScale\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\" alt=\"[^\"]+\"[^>]*>[^<]*</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternTerrain = Pattern.compile("<span id=\"ctl00_ContentBody_Localize6\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\" alt=\"[^\"]+\"[^>]*>[^<]*</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternOwner = Pattern.compile("<span class=\"minorCacheDetails\">\\W*An?(\\W*Event)?\\W*cache\\W*by[^<]*<a href=\"[^\"]+\">([^<]+)</a>[^<]*</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternOwnerReal = Pattern.compile("<a id=\"ctl00_ContentBody_uxFindLinksHiddenByThisUser\" href=\"[^\"]*/seek/nearest\\.aspx\\?u=*([^\"]+)\">[^<]+</a>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternHidden = Pattern.compile("<span[^>]*>\\W*Hidden[^\\d]*([^<]+)</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternHiddenEvent = Pattern.compile("<span[^>]*>\\W*Event\\W*Date[^:]*:([^<]*)</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternFavourite = Pattern.compile("<a id=\"uxFavContainerLink\"[^>]*>[^<]*<div[^<]*<span class=\"favorite-value\">[^\\d]*([0-9]+)[^\\d^<]*</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternFound = Pattern.compile("<p>[^<]*<a id=\"ctl00_ContentBody_hlFoundItLog\"[^<]*<img src=\".*/images/stockholm/16x16/check\\.gif\"[^>]*>[^<]*</a>[^<]*</p>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternLatLon = Pattern.compile("<span id=\"ctl00_ContentBody_LatLon\"[^>]*>(<b>)?([^<]*)(<\\/b>)?<\\/span>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternLocation = Pattern.compile("<span id=\"ctl00_ContentBody_Location\"[^>]*>In ([^<]*)", Pattern.CASE_INSENSITIVE);
private final static Pattern patternHint = Pattern.compile("<p>([^<]*<strong>)?\\W*Additional Hints([^<]*<\\/strong>)?[^\\(]*\\(<a[^>]+>Encrypt</a>\\)[^<]*<\\/p>[^<]*<div id=\"div_hint\"[^>]*>(.*)</div>[^<]*<div id=[\\'|\"]dk[\\'|\"]", Pattern.CASE_INSENSITIVE);
private final static Pattern patternPersonalNote = Pattern.compile("<p id=\"cache_note\"[^>]*>([^<]*)</p>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternDescShort = Pattern.compile("<div class=\"UserSuppliedContent\">[^<]*<span id=\"ctl00_ContentBody_ShortDescription\"[^>]*>((?:(?!</span>[^\\w^<]*</div>).)*)</span>[^\\w^<]*</div>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternDesc = Pattern.compile("<span id=\"ctl00_ContentBody_LongDescription\"[^>]*>" + "(.*)</span>[^<]*</div>[^<]*<p>[^<]*</p>[^<]*<p>[^<]*<strong>\\W*Additional Hints</strong>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternCountLogs = Pattern.compile("<span id=\"ctl00_ContentBody_lblFindCounts\"><p>(.*)<\\/p><\\/span>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternCountLog = Pattern.compile(" src=\"\\/images\\/icons\\/([^\\.]*).gif\" alt=\"[^\"]*\" title=\"[^\"]*\" />([0-9]*)[^0-9]+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternLogs = Pattern.compile("<table class=\"LogsTable[^\"]*\"[^>]*>[^<]*<tr>(.*)</tr>[^<]*</table>[^<]*<p", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternLog = Pattern.compile("<td[^>]*>[^<]*<strong>[^<]*<img src=\"[^\"]*/images/icons/([^\\.]+)\\.[a-z]{2,5}\"[^>]*> ([a-zA-Z]+) (\\d+)(, (\\d+))? by <a href=[^>]+>([^<]+)</a>[<^]*</strong>([^\\(]*\\((\\d+) found\\))?(<br[^>]*>)+((?:(?!<small>).)*)(<br[^>]*>)+<small>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private final static Pattern patternLogImgs = Pattern.compile("a href=\"http://img.geocaching.com/cache/log/([^\"]+)\".+?<span>([^<]*)", Pattern.CASE_INSENSITIVE);
private final static Pattern patternAttributes = Pattern.compile("<h3 class=\"WidgetHeader\">[^<]*<img[^>]+>\\W*Attributes[^<]*</h3>[^<]*<div class=\"WidgetBody\">(([^<]*<img src=\"[^\"]+\" alt=\"[^\"]+\"[^>]*>)+)[^<]*<p", Pattern.CASE_INSENSITIVE);
private final static Pattern patternAttributesInside = Pattern.compile("[^<]*<img src=\"([^\"]+)\" alt=\"([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternSpoilers = Pattern.compile("<span id=\"ctl00_ContentBody_Images\">((<a href=\"[^\"]+\"[^>]*>[^<]*<img[^>]+>[^<]*<span>[^>]+</span>[^<]*</a>[^<]*<br[^>]*>([^<]*(<br[^>]*>)+)?)+)[^<]*</span>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternSpoilersInside = Pattern.compile("[^<]*<a href=\"([^\"]+)\"[^>]*>[^<]*<img[^>]+>[^<]*<span>([^>]+)</span>[^<]*</a>[^<]*<br[^>]*>(([^<]*)(<br[^<]*>)+)?", Pattern.CASE_INSENSITIVE);
private final static Pattern patternInventory = Pattern.compile("<span id=\"ctl00_ContentBody_uxTravelBugList_uxInventoryLabel\">\\W*Inventory[^<]*</span>[^<]*</h3>[^<]*<div class=\"WidgetBody\">([^<]*<ul>(([^<]*<li>[^<]*<a href=\"[^\"]+\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>[^<]+<\\/span>[^<]*<\\/a>[^<]*<\\/li>)+)[^<]*<\\/ul>)?", Pattern.CASE_INSENSITIVE);
private final static Pattern patternInventoryInside = Pattern.compile("[^<]*<li>[^<]*<a href=\"[a-z0-9\\-\\_\\.\\?\\/\\:\\@]*\\/track\\/details\\.aspx\\?guid=([0-9a-z\\-]+)[^\"]*\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>([^<]+)<\\/span>[^<]*<\\/a>[^<]*<\\/li>", Pattern.CASE_INSENSITIVE);
private final static Pattern patternOnWatchlist = Pattern.compile("<img\\s*src=\"\\/images\\/stockholm\\/16x16\\/icon_stop_watchlist.gif\"", Pattern.CASE_INSENSITIVE);
public static HashMap<String, String> cacheTypes = new HashMap<String, String>();
public static HashMap<String, String> cacheTypesInv = new HashMap<String, String>();
public static HashMap<String, String> cacheIDs = new HashMap<String, String>();
public static HashMap<String, String> cacheIDsChoices = new HashMap<String, String>();
public static HashMap<String, String> waypointTypes = new HashMap<String, String>();
public static HashMap<String, Integer> logTypes = new HashMap<String, Integer>();
public static HashMap<String, Integer> logTypes0 = new HashMap<String, Integer>();
public static HashMap<Integer, String> logTypes1 = new HashMap<Integer, String>();
public static HashMap<Integer, String> logTypes2 = new HashMap<Integer, String>();
public static HashMap<Integer, String> logTypesTrackable = new HashMap<Integer, String>();
public static HashMap<Integer, String> logTypesTrackableAction = new HashMap<Integer, String>();
public static HashMap<Integer, String> errorRetrieve = new HashMap<Integer, String>();
public static SimpleDateFormat dateInBackslash = new SimpleDateFormat("MM/dd/yyyy");
public static SimpleDateFormat dateInDash = new SimpleDateFormat("yyyy-MM-dd");
public static SimpleDateFormat dateEvIn = new SimpleDateFormat("dd MMMMM yyyy", Locale.ENGLISH); // 28 March 2009
public static SimpleDateFormat dateTbIn1 = new SimpleDateFormat("EEEEE, dd MMMMM yyyy", Locale.ENGLISH); // Saturday, 28 March 2009
public static SimpleDateFormat dateTbIn2 = new SimpleDateFormat("EEEEE, MMMMM dd, yyyy", Locale.ENGLISH); // Saturday, March 28, 2009
public static SimpleDateFormat dateSqlIn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 2010-07-25 14:44:01
public static SimpleDateFormat dateGPXIn = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // 2010-04-20T07:00:00Z
private Resources res = null;
private HashMap<String, String> cookies = new HashMap<String, String>();
private static final String passMatch = "[/\\?&]*[Pp]ass(word)?=[^&^#^$]+";
private static final Pattern patternLoggedIn = Pattern.compile("<span class=\"Success\">You are logged in as[^<]*<strong[^>]*>([^<]+)</strong>[^<]*</span>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern patternLogged2In = Pattern.compile("<strong>\\W*Hello,[^<]*<a[^>]+>([^<]+)</a>[^<]*</strong>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern patternViewstateFieldCount = Pattern.compile("id=\"__VIEWSTATEFIELDCOUNT\"[^(value)]+value=\"(\\d+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern patternViewstates = Pattern.compile("id=\"__VIEWSTATE(\\d*)\"[^(value)]+value=\"([^\"]+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final Pattern patternIsPremium = Pattern.compile("<span id=\"ctl00_litPMLevel\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public static final double kmInMiles = 1 / 1.609344;
public static final double deg2rad = Math.PI / 180;
public static final double rad2deg = 180 / Math.PI;
public static final float erad = 6371.0f;
private cgeoapplication app = null;
private cgSettings settings = null;
private SharedPreferences prefs = null;
public String version = null;
private String idBrowser = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.86 Safari/533.4";
Context context = null;
final private static HashMap<String, Integer> gcIcons = new HashMap<String, Integer>();
final private static HashMap<String, Integer> wpIcons = new HashMap<String, Integer>();
public static final int LOG_FOUND_IT = 2;
public static final int LOG_DIDNT_FIND_IT = 3;
public static final int LOG_NOTE = 4;
public static final int LOG_PUBLISH_LISTING = 1003; // unknown ID; used number doesn't match any GC.com's ID
public static final int LOG_ENABLE_LISTING = 23;
public static final int LOG_ARCHIVE = 5;
public static final int LOG_TEMP_DISABLE_LISTING = 22;
public static final int LOG_NEEDS_ARCHIVE = 7;
public static final int LOG_WILL_ATTEND = 9;
public static final int LOG_ATTENDED = 10;
public static final int LOG_RETRIEVED_IT = 13;
public static final int LOG_PLACED_IT = 14;
public static final int LOG_GRABBED_IT = 19;
public static final int LOG_NEEDS_MAINTENANCE = 45;
public static final int LOG_OWNER_MAINTENANCE = 46;
public static final int LOG_UPDATE_COORDINATES = 47;
public static final int LOG_DISCOVERED_IT = 48;
public static final int LOG_POST_REVIEWER_NOTE = 18;
public static final int LOG_VISIT = 1001; // unknown ID; used number doesn't match any GC.com's ID
public static final int LOG_WEBCAM_PHOTO_TAKEN = 11;
public static final int LOG_ANNOUNCEMENT = 74;
public cgBase(cgeoapplication appIn, cgSettings settingsIn, SharedPreferences prefsIn) {
context = appIn.getBaseContext();
res = appIn.getBaseContext().getResources();
// cache types
cacheTypes.put("traditional cache", "traditional");
cacheTypes.put("multi-cache", "multi");
cacheTypes.put("unknown cache", "mystery");
cacheTypes.put("letterbox hybrid", "letterbox");
cacheTypes.put("event cache", "event");
cacheTypes.put("mega-event cache", "mega");
cacheTypes.put("earthcache", "earth");
cacheTypes.put("cache in trash out event", "cito");
cacheTypes.put("webcam cache", "webcam");
cacheTypes.put("virtual cache", "virtual");
cacheTypes.put("wherigo cache", "wherigo");
cacheTypes.put("lost & found", "lostfound");
cacheTypes.put("project ape cache", "ape");
cacheTypes.put("groundspeak hq", "gchq");
cacheTypes.put("gps cache exhibit", "gps");
// cache types inverted
cacheTypesInv.put("traditional", res.getString(R.string.traditional));
cacheTypesInv.put("multi", res.getString(R.string.multi));
cacheTypesInv.put("mystery", res.getString(R.string.mystery));
cacheTypesInv.put("letterbox", res.getString(R.string.letterbox));
cacheTypesInv.put("event", res.getString(R.string.event));
cacheTypesInv.put("mega", res.getString(R.string.mega));
cacheTypesInv.put("earth", res.getString(R.string.earth));
cacheTypesInv.put("cito", res.getString(R.string.cito));
cacheTypesInv.put("webcam", res.getString(R.string.webcam));
cacheTypesInv.put("virtual", res.getString(R.string.virtual));
cacheTypesInv.put("wherigo", res.getString(R.string.wherigo));
cacheTypesInv.put("lostfound", res.getString(R.string.lostfound));
cacheTypesInv.put("ape", res.getString(R.string.ape));
cacheTypesInv.put("gchq", res.getString(R.string.gchq));
cacheTypesInv.put("gps", res.getString(R.string.gps));
// cache ids
cacheIDs.put("all", "9a79e6ce-3344-409c-bbe9-496530baf758"); // hard-coded also in cgSettings
cacheIDs.put("traditional", "32bc9333-5e52-4957-b0f6-5a2c8fc7b257");
cacheIDs.put("multi", "a5f6d0ad-d2f2-4011-8c14-940a9ebf3c74");
cacheIDs.put("mystery", "40861821-1835-4e11-b666-8d41064d03fe");
cacheIDs.put("letterbox", "4bdd8fb2-d7bc-453f-a9c5-968563b15d24");
cacheIDs.put("event", "69eb8534-b718-4b35-ae3c-a856a55b0874");
cacheIDs.put("mega-event", "69eb8535-b718-4b35-ae3c-a856a55b0874");
cacheIDs.put("earth", "c66f5cf3-9523-4549-b8dd-759cd2f18db8");
cacheIDs.put("cito", "57150806-bc1a-42d6-9cf0-538d171a2d22");
cacheIDs.put("webcam", "31d2ae3c-c358-4b5f-8dcd-2185bf472d3d");
cacheIDs.put("virtual", "294d4360-ac86-4c83-84dd-8113ef678d7e");
cacheIDs.put("wherigo", "0544fa55-772d-4e5c-96a9-36a51ebcf5c9");
cacheIDs.put("lostfound", "3ea6533d-bb52-42fe-b2d2-79a3424d4728");
cacheIDs.put("ape", "2555690d-b2bc-4b55-b5ac-0cb704c0b768");
cacheIDs.put("gchq", "416f2494-dc17-4b6a-9bab-1a29dd292d8c");
cacheIDs.put("gps", "72e69af2-7986-4990-afd9-bc16cbbb4ce3");
// cache choices
cacheIDsChoices.put(res.getString(R.string.all), cacheIDs.get("all"));
cacheIDsChoices.put(res.getString(R.string.traditional), cacheIDs.get("traditional"));
cacheIDsChoices.put(res.getString(R.string.multi), cacheIDs.get("multi"));
cacheIDsChoices.put(res.getString(R.string.mystery), cacheIDs.get("mystery"));
cacheIDsChoices.put(res.getString(R.string.letterbox), cacheIDs.get("letterbox"));
cacheIDsChoices.put(res.getString(R.string.event), cacheIDs.get("event"));
cacheIDsChoices.put(res.getString(R.string.mega), cacheIDs.get("mega"));
cacheIDsChoices.put(res.getString(R.string.earth), cacheIDs.get("earth"));
cacheIDsChoices.put(res.getString(R.string.cito), cacheIDs.get("cito"));
cacheIDsChoices.put(res.getString(R.string.webcam), cacheIDs.get("webcam"));
cacheIDsChoices.put(res.getString(R.string.virtual), cacheIDs.get("virtual"));
cacheIDsChoices.put(res.getString(R.string.wherigo), cacheIDs.get("whereigo"));
cacheIDsChoices.put(res.getString(R.string.lostfound), cacheIDs.get("lostfound"));
cacheIDsChoices.put(res.getString(R.string.ape), cacheIDs.get("ape"));
cacheIDsChoices.put(res.getString(R.string.gchq), cacheIDs.get("gchq"));
cacheIDsChoices.put(res.getString(R.string.gps), cacheIDs.get("gps"));
// waypoint types
waypointTypes.put("flag", res.getString(R.string.wp_final));
waypointTypes.put("stage", res.getString(R.string.wp_stage));
waypointTypes.put("puzzle", res.getString(R.string.wp_puzzle));
waypointTypes.put("pkg", res.getString(R.string.wp_pkg));
waypointTypes.put("trailhead", res.getString(R.string.wp_trailhead));
waypointTypes.put("waypoint", res.getString(R.string.wp_waypoint));
// log types
logTypes.put("icon_smile", LOG_FOUND_IT);
logTypes.put("icon_sad", LOG_DIDNT_FIND_IT);
logTypes.put("icon_note", LOG_NOTE);
logTypes.put("icon_greenlight", LOG_PUBLISH_LISTING);
logTypes.put("icon_enabled", LOG_ENABLE_LISTING);
logTypes.put("traffic_cone", LOG_ARCHIVE);
logTypes.put("icon_disabled", LOG_TEMP_DISABLE_LISTING);
logTypes.put("icon_remove", LOG_NEEDS_ARCHIVE);
logTypes.put("icon_rsvp", LOG_WILL_ATTEND);
logTypes.put("icon_attended", LOG_ATTENDED);
logTypes.put("picked_up", LOG_RETRIEVED_IT);
logTypes.put("dropped_off", LOG_PLACED_IT);
logTypes.put("transfer", LOG_GRABBED_IT);
logTypes.put("icon_needsmaint", LOG_NEEDS_MAINTENANCE);
logTypes.put("icon_maint", LOG_OWNER_MAINTENANCE);
logTypes.put("coord_update", LOG_UPDATE_COORDINATES);
logTypes.put("icon_discovered", LOG_DISCOVERED_IT);
logTypes.put("big_smile", LOG_POST_REVIEWER_NOTE);
logTypes.put("icon_visited", LOG_VISIT); // unknown ID; used number doesn't match any GC.com's ID
logTypes.put("icon_camera", LOG_WEBCAM_PHOTO_TAKEN); // unknown ID; used number doesn't match any GC.com's ID
logTypes.put("icon_announcement", LOG_ANNOUNCEMENT); // unknown ID; used number doesn't match any GC.com's ID
logTypes0.put("found it", LOG_FOUND_IT);
logTypes0.put("didn't find it", LOG_DIDNT_FIND_IT);
logTypes0.put("write note", LOG_NOTE);
logTypes0.put("publish listing", LOG_PUBLISH_LISTING);
logTypes0.put("enable listing", LOG_ENABLE_LISTING);
logTypes0.put("archive", LOG_ARCHIVE);
logTypes0.put("temporarily disable listing", LOG_TEMP_DISABLE_LISTING);
logTypes0.put("needs archived", LOG_NEEDS_ARCHIVE);
logTypes0.put("will attend", LOG_WILL_ATTEND);
logTypes0.put("attended", LOG_ATTENDED);
logTypes0.put("retrieved it", LOG_RETRIEVED_IT);
logTypes0.put("placed it", LOG_PLACED_IT);
logTypes0.put("grabbed it", LOG_GRABBED_IT);
logTypes0.put("needs maintenance", LOG_NEEDS_MAINTENANCE);
logTypes0.put("owner maintenance", LOG_OWNER_MAINTENANCE);
logTypes0.put("update coordinates", LOG_UPDATE_COORDINATES);
logTypes0.put("discovered it", LOG_DISCOVERED_IT);
logTypes0.put("post reviewer note", LOG_POST_REVIEWER_NOTE);
logTypes0.put("visit", LOG_VISIT); // unknown ID; used number doesn't match any GC.com's ID
logTypes0.put("webcam photo taken", LOG_WEBCAM_PHOTO_TAKEN); // unknown ID; used number doesn't match any GC.com's ID
logTypes0.put("announcement", LOG_ANNOUNCEMENT); // unknown ID; used number doesn't match any GC.com's ID
logTypes1.put(LOG_FOUND_IT, res.getString(R.string.log_found));
logTypes1.put(LOG_DIDNT_FIND_IT, res.getString(R.string.log_dnf));
logTypes1.put(LOG_NOTE, res.getString(R.string.log_note));
logTypes1.put(LOG_PUBLISH_LISTING, res.getString(R.string.log_published));
logTypes1.put(LOG_ENABLE_LISTING, res.getString(R.string.log_enabled));
logTypes1.put(LOG_ARCHIVE, res.getString(R.string.log_archived));
logTypes1.put(LOG_TEMP_DISABLE_LISTING, res.getString(R.string.log_disabled));
logTypes1.put(LOG_NEEDS_ARCHIVE, res.getString(R.string.log_needs_archived));
logTypes1.put(LOG_WILL_ATTEND, res.getString(R.string.log_attend));
logTypes1.put(LOG_ATTENDED, res.getString(R.string.log_attended));
logTypes1.put(LOG_RETRIEVED_IT, res.getString(R.string.log_retrieved));
logTypes1.put(LOG_PLACED_IT, res.getString(R.string.log_placed));
logTypes1.put(LOG_GRABBED_IT, res.getString(R.string.log_grabbed));
logTypes1.put(LOG_NEEDS_MAINTENANCE, res.getString(R.string.log_maintenance_needed));
logTypes1.put(LOG_OWNER_MAINTENANCE, res.getString(R.string.log_maintained));
logTypes1.put(LOG_UPDATE_COORDINATES, res.getString(R.string.log_update));
logTypes1.put(LOG_DISCOVERED_IT, res.getString(R.string.log_discovered));
logTypes1.put(LOG_POST_REVIEWER_NOTE, res.getString(R.string.log_reviewed));
logTypes1.put(LOG_VISIT, res.getString(R.string.log_taken));
logTypes1.put(LOG_WEBCAM_PHOTO_TAKEN, res.getString(R.string.log_webcam));
logTypes1.put(LOG_ANNOUNCEMENT, res.getString(R.string.log_announcement));
logTypes2.put(LOG_FOUND_IT, res.getString(R.string.log_found)); // traditional, multi, unknown, earth, wherigo, virtual, letterbox
logTypes2.put(LOG_DIDNT_FIND_IT, res.getString(R.string.log_dnf)); // traditional, multi, unknown, earth, wherigo, virtual, letterbox, webcam
logTypes2.put(LOG_NOTE, res.getString(R.string.log_note)); // traditional, multi, unknown, earth, wherigo, virtual, event, letterbox, webcam, trackable
logTypes2.put(LOG_PUBLISH_LISTING, res.getString(R.string.log_published)); // X
logTypes2.put(LOG_ENABLE_LISTING, res.getString(R.string.log_enabled)); // owner
logTypes2.put(LOG_ARCHIVE, res.getString(R.string.log_archived)); // traditional, multi, unknown, earth, event, wherigo, virtual, letterbox, webcam
logTypes2.put(LOG_TEMP_DISABLE_LISTING, res.getString(R.string.log_disabled)); // owner
logTypes2.put(LOG_NEEDS_ARCHIVE, res.getString(R.string.log_needs_archived)); // traditional, multi, unknown, earth, event, wherigo, virtual, letterbox, webcam
logTypes2.put(LOG_WILL_ATTEND, res.getString(R.string.log_attend)); // event
logTypes2.put(LOG_ATTENDED, res.getString(R.string.log_attended)); // event
logTypes2.put(LOG_WEBCAM_PHOTO_TAKEN, res.getString(R.string.log_webcam)); // webcam
logTypes2.put(LOG_RETRIEVED_IT, res.getString(R.string.log_retrieved)); //trackable
logTypes2.put(LOG_GRABBED_IT, res.getString(R.string.log_grabbed)); //trackable
logTypes2.put(LOG_NEEDS_MAINTENANCE, res.getString(R.string.log_maintenance_needed)); // traditional, unknown, multi, wherigo, virtual, letterbox, webcam
logTypes2.put(LOG_OWNER_MAINTENANCE, res.getString(R.string.log_maintained)); // owner
logTypes2.put(LOG_DISCOVERED_IT, res.getString(R.string.log_discovered)); //trackable
logTypes2.put(LOG_POST_REVIEWER_NOTE, res.getString(R.string.log_reviewed)); // X
logTypes2.put(LOG_ANNOUNCEMENT, res.getString(R.string.log_announcement)); // X
// trackables for logs
logTypesTrackable.put(0, res.getString(R.string.log_tb_nothing)); // do nothing
logTypesTrackable.put(1, res.getString(R.string.log_tb_visit)); // visit cache
logTypesTrackable.put(2, res.getString(R.string.log_tb_drop)); // drop here
logTypesTrackableAction.put(0, ""); // do nothing
logTypesTrackableAction.put(1, "_Visited"); // visit cache
logTypesTrackableAction.put(2, "_DroppedOff"); // drop here
// retrieving errors (because of ____ )
errorRetrieve.put(1, res.getString(R.string.err_none));
errorRetrieve.put(0, res.getString(R.string.err_start));
errorRetrieve.put(-1, res.getString(R.string.err_parse));
errorRetrieve.put(-2, res.getString(R.string.err_server));
errorRetrieve.put(-3, res.getString(R.string.err_login));
errorRetrieve.put(-4, res.getString(R.string.err_unknown));
errorRetrieve.put(-5, res.getString(R.string.err_comm));
errorRetrieve.put(-6, res.getString(R.string.err_wrong));
errorRetrieve.put(-7, res.getString(R.string.err_license));
// init
app = appIn;
settings = settingsIn;
prefs = prefsIn;
try {
PackageManager manager = app.getPackageManager();
PackageInfo info = manager.getPackageInfo(app.getPackageName(), 0);
version = info.versionName;
} catch (Exception e) {
// nothing
}
if (settings.asBrowser == 1) {
final long rndBrowser = Math.round(Math.random() * 6);
if (rndBrowser == 0) {
idBrowser = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.1 (KHTML, like Gecko) Chrome/5.0.322.2 Safari/533.1";
} else if (rndBrowser == 1) {
idBrowser = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)";
} else if (rndBrowser == 2) {
idBrowser = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
} else if (rndBrowser == 3) {
idBrowser = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10";
} else if (rndBrowser == 4) {
idBrowser = "Mozilla/5.0 (iPod; U; CPU iPhone OS 2_2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5H11a Safari/525.20";
} else if (rndBrowser == 5) {
idBrowser = "Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2";
} else if (rndBrowser == 6) {
idBrowser = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.86 Safari/533.4";
} else {
idBrowser = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.11 Safari/532.9";
}
}
}
/**
* read all viewstates from page
*
* @return String[] with all view states
*/
public static String[] getViewstates(String page) {
// Get the number of viewstates.
// If there is only one viewstate, __VIEWSTATEFIELDCOUNT is not present
int count = 1;
final Matcher matcherViewstateCount = patternViewstateFieldCount.matcher(page);
if (matcherViewstateCount.find())
count = Integer.parseInt(matcherViewstateCount.group(1));
String[] viewstates = new String[count];
// Get the viewstates
final Matcher matcherViewstates = patternViewstates.matcher(page);
while (matcherViewstates.find()) {
String sno = matcherViewstates.group(1); // number of viewstate
int no;
if ("".equals(sno))
no = 0;
else
no = Integer.parseInt(sno);
viewstates[no] = matcherViewstates.group(2);
}
if (viewstates.length == 1 && viewstates[0] == null)
// no viewstates were present
return null;
else
return viewstates;
}
/**
* put viewstates into request parameters
*/
public void setViewstates(String[] viewstates, HashMap<String, String> params) {
if (viewstates == null || viewstates.length == 0)
return;
params.put("__VIEWSTATE", viewstates[0]);
if (viewstates.length > 1) {
for (int i = 1; i < viewstates.length; i++)
params.put("__VIEWSTATE" + i, viewstates[i]);
params.put("__VIEWSTATEFIELDCOUNT", viewstates.length + "");
}
}
/**
* transfers the viewstates variables from a page (response) to parameters
* (next request)
*/
public void transferViewstates(String page, HashMap<String, String> params) {
setViewstates(getViewstates(page), params);
}
/**
* checks if an Array of Strings is empty or not. Empty means:
* - Array is null
* - or all elements are null or empty strings
*/
public static boolean isEmpty(String[] a) {
if (a == null)
return true;
for (String s: a)
if (s != null && s.length() > 0)
return false;
return true;
}
public class loginThread extends Thread {
@Override
public void run() {
login();
}
}
public int login() {
final String host = "www.geocaching.com";
final String path = "/login/default.aspx";
cgResponse loginResponse = null;
String loginData = null;
String[] viewstates = null;
final HashMap<String, String> loginStart = settings.getLogin();
if (loginStart == null) {
return -3; // no login information stored
}
loginResponse = request(true, host, path, "GET", new HashMap<String, String>(), false, false, false);
loginData = loginResponse.getData();
if (loginData != null && loginData.length() > 0) {
if (checkLogin(loginData)) {
Log.i(cgSettings.tag, "Already logged in Geocaching.com as " + loginStart.get("username"));
switchToEnglish(viewstates);
return 1; // logged in
}
viewstates = getViewstates(loginData);
if (isEmpty(viewstates)) {
Log.e(cgSettings.tag, "cgeoBase.login: Failed to find viewstates");
return -1; // no viewstates
}
} else {
Log.e(cgSettings.tag, "cgeoBase.login: Failed to retrieve login page (1st)");
return -2; // no loginpage
}
final HashMap<String, String> login = settings.getLogin();
final HashMap<String, String> params = new HashMap<String, String>();
if (login == null || login.get("username") == null || login.get("username").length() == 0 || login.get("password") == null || login.get("password").length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.login: No login information stored");
return -3;
}
settings.deleteCookies();
params.put("__EVENTTARGET", "");
params.put("__EVENTARGUMENT", "");
setViewstates(viewstates, params);
params.put("ctl00$SiteContent$tbUsername", login.get("username"));
params.put("ctl00$SiteContent$tbPassword", login.get("password"));
params.put("ctl00$SiteContent$cbRememberMe", "on");
params.put("ctl00$SiteContent$btnSignIn", "Login");
loginResponse = request(true, host, path, "POST", params, false, false, false);
loginData = loginResponse.getData();
if (loginData != null && loginData.length() > 0) {
if (checkLogin(loginData)) {
Log.i(cgSettings.tag, "Successfully logged in Geocaching.com as " + login.get("username"));
switchToEnglish(getViewstates(loginData));
return 1; // logged in
} else {
if (loginData.indexOf("Your username/password combination does not match.") != -1) {
Log.i(cgSettings.tag, "Failed to log in Geocaching.com as " + login.get("username") + " because of wrong username/password");
return -6; // wrong login
} else {
Log.i(cgSettings.tag, "Failed to log in Geocaching.com as " + login.get("username") + " for some unknown reason");
return -4; // can't login
}
}
} else {
Log.e(cgSettings.tag, "cgeoBase.login: Failed to retrieve login page (2nd)");
return -5; // no login page
}
}
public static Boolean isPremium(String page)
{
if (checkLogin(page)) {
final Matcher matcherIsPremium = patternIsPremium.matcher(page);
return matcherIsPremium.find();
} else
return false;
}
public static Boolean checkLogin(String page) {
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.checkLogin: No page given");
return false;
}
// on every page
final Matcher matcherLogged2In = patternLogged2In.matcher(page);
while (matcherLogged2In.find()) {
return true;
}
// after login
final Matcher matcherLoggedIn = patternLoggedIn.matcher(page);
while (matcherLoggedIn.find()) {
return true;
}
return false;
}
public String switchToEnglish(String[] viewstates) {
final String host = "www.geocaching.com";
final String path = "/default.aspx";
final HashMap<String, String> params = new HashMap<String, String>();
setViewstates(viewstates, params);
params.put("__EVENTTARGET", "ctl00$uxLocaleList$uxLocaleList$ctl00$uxLocaleItem"); // switch to english
params.put("__EVENTARGUMENT", "");
return request(false, host, path, "POST", params, false, false, false).getData();
}
public cgCacheWrap parseSearch(cgSearchThread thread, String url, String page, boolean showCaptcha) {
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseSearch: No page given");
return null;
}
final cgCacheWrap caches = new cgCacheWrap();
final ArrayList<String> cids = new ArrayList<String>();
final ArrayList<String> guids = new ArrayList<String>();
String recaptchaChallenge = null;
String recaptchaText = null;
caches.url = url;
final Pattern patternCacheType = Pattern.compile("<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^\\.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Pattern patternGuidAndDisabled = Pattern.compile("<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Pattern patternTbs = Pattern.compile("<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>", Pattern.CASE_INSENSITIVE);
final Pattern patternTbsInside = Pattern.compile("(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Pattern patternDirection = Pattern.compile("<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
final Pattern patternCode = Pattern.compile("\\|\\W*(GC[a-z0-9]+)[^\\|]*\\|", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Pattern patternId = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"", Pattern.CASE_INSENSITIVE);
final Pattern patternFavourite = Pattern.compile("<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>", Pattern.CASE_INSENSITIVE);
final Pattern patternTotalCnt = Pattern.compile("<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>", Pattern.CASE_INSENSITIVE);
final Pattern patternRecaptcha = Pattern.compile("<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
final Pattern patternRecaptchaChallenge = Pattern.compile("challenge : '([^']+)'", Pattern.CASE_INSENSITIVE);
caches.viewstates = getViewstates(page);
// recaptcha
if (showCaptcha) {
try {
String recaptchaJsParam = null;
final Matcher matcherRecaptcha = patternRecaptcha.matcher(page);
while (matcherRecaptcha.find()) {
if (matcherRecaptcha.groupCount() > 0) {
recaptchaJsParam = matcherRecaptcha.group(1);
}
}
if (recaptchaJsParam != null) {
final String recaptchaJs = request(false, "www.google.com", "/recaptcha/api/challenge", "GET", "k=" + urlencode_rfc3986(recaptchaJsParam.trim()), 0, true).getData();
if (recaptchaJs != null && recaptchaJs.length() > 0) {
final Matcher matcherRecaptchaChallenge = patternRecaptchaChallenge.matcher(recaptchaJs);
while (matcherRecaptchaChallenge.find()) {
if (matcherRecaptchaChallenge.groupCount() > 0) {
recaptchaChallenge = matcherRecaptchaChallenge.group(1).trim();
}
}
}
}
} catch (Exception e) {
// failed to parse recaptcha challenge
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge");
}
if (thread != null && recaptchaChallenge != null && recaptchaChallenge.length() > 0) {
thread.setChallenge(recaptchaChallenge);
thread.notifyNeed();
}
}
int startPos = -1;
int endPos = -1;
startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\"");
if (startPos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page");
return null;
}
page = page.substring(startPos); // cut on <table
startPos = page.indexOf(">");
endPos = page.indexOf("ctl00_ContentBody_UnitTxt");
if (startPos == -1 || endPos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page");
return null;
}
page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table>
final String[] rows = page.split("<tr class=");
final int rows_count = rows.length;
for (int z = 1; z < rows_count; z++) {
cgCache cache = new cgCache();
String row = rows[z];
// check for cache type presence
if (row.indexOf("images/wpttypes") == -1) {
continue;
}
try {
final Matcher matcherGuidAndDisabled = patternGuidAndDisabled.matcher(row);
while (matcherGuidAndDisabled.find()) {
if (matcherGuidAndDisabled.groupCount() > 0) {
guids.add(matcherGuidAndDisabled.group(1));
cache.guid = matcherGuidAndDisabled.group(1);
if (matcherGuidAndDisabled.group(4) != null) {
cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString();
}
if (matcherGuidAndDisabled.group(6) != null) {
cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString();
}
final String attr = matcherGuidAndDisabled.group(2);
if (attr != null) {
if (attr.contains("Strike")) {
cache.disabled = true;
} else {
cache.disabled = false;
}
if (attr.contains("OldWarning")) {
cache.archived = true;
} else {
cache.archived = false;
}
}
}
}
} catch (Exception e) {
// failed to parse GUID and/or Disabled
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data");
}
if (settings.excludeDisabled == 1 && (cache.disabled || cache.archived)) {
// skip disabled and archived caches
cache = null;
continue;
}
String inventoryPre = null;
// GC* code
try {
final Matcher matcherCode = patternCode.matcher(row);
while (matcherCode.find()) {
if (matcherCode.groupCount() > 0) {
cache.geocode = matcherCode.group(1).toUpperCase();
}
}
} catch (Exception e) {
// failed to parse code
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache code");
}
// cache type
try {
final Matcher matcherCacheType = patternCacheType.matcher(row);
while (matcherCacheType.find()) {
if (matcherCacheType.groupCount() > 0) {
cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase());
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache type");
}
// cache direction - image
try {
final Matcher matcherDirection = patternDirection.matcher(row);
while (matcherDirection.find()) {
if (matcherDirection.groupCount() > 0) {
cache.directionImg = matcherDirection.group(1);
}
}
} catch (Exception e) {
// failed to parse direction image
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache direction image");
}
// cache inventory
try {
final Matcher matcherTbs = patternTbs.matcher(row);
while (matcherTbs.find()) {
if (matcherTbs.groupCount() > 0) {
cache.inventoryItems = Integer.parseInt(matcherTbs.group(1));
inventoryPre = matcherTbs.group(2);
}
}
} catch (Exception e) {
// failed to parse inventory
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)");
}
if (inventoryPre != null && inventoryPre.trim().length() > 0) {
try {
final Matcher matcherTbsInside = patternTbsInside.matcher(inventoryPre);
while (matcherTbsInside.find()) {
if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null) {
final String inventoryItem = matcherTbsInside.group(2).toLowerCase();
if (inventoryItem.equals("premium member only cache")) {
continue;
} else {
if (cache.inventoryItems <= 0) {
cache.inventoryItems = 1;
}
}
}
}
} catch (Exception e) {
// failed to parse cache inventory info
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info");
}
}
// premium cache
if (row.indexOf("/images/small_profile.gif") != -1) {
cache.members = true;
} else {
cache.members = false;
}
// found it
if (row.indexOf("/images/icons/icon_smile") != -1) {
cache.found = true;
} else {
cache.found = false;
}
// own it
if (row.indexOf("/images/silk/star.png") != -1) {
cache.own = true;
} else {
cache.own = false;
}
// id
try {
final Matcher matcherId = patternId.matcher(row);
while (matcherId.find()) {
if (matcherId.groupCount() > 0) {
cache.cacheid = matcherId.group(1);
cids.add(cache.cacheid);
}
}
} catch (Exception e) {
// failed to parse cache id
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache id");
}
// favourite count
try {
final Matcher matcherFavourite = patternFavourite.matcher(row);
while (matcherFavourite.find()) {
if (matcherFavourite.groupCount() > 0) {
cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
}
}
} catch (Exception e) {
// failed to parse favourite count
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse favourite count");
}
if (cache.nameSp == null) {
cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name);
if (cache.disabled || cache.archived) { // strike
cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
caches.cacheList.add(cache);
}
// total caches found
try {
final Matcher matcherTotalCnt = patternTotalCnt.matcher(page);
while (matcherTotalCnt.find()) {
if (matcherTotalCnt.groupCount() > 0) {
if (matcherTotalCnt.group(1) != null) {
caches.totalCnt = new Integer(matcherTotalCnt.group(1));
}
}
}
} catch (Exception e) {
// failed to parse cache count
Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache count");
}
if (thread != null && recaptchaChallenge != null) {
if (thread.getText() == null) {
thread.waitForUser();
}
recaptchaText = thread.getText();
}
if (cids.size() > 0 && (recaptchaChallenge == null || (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0))) {
Log.i(cgSettings.tag, "Trying to get .loc for " + cids.size() + " caches");
try {
// get coordinates for parsed caches
final String host = "www.geocaching.com";
final String path = "/seek/nearest.aspx";
final StringBuilder params = new StringBuilder();
params.append("__EVENTTARGET=");
params.append("&");
params.append("__EVENTARGUMENT=");
if (caches.viewstates != null && caches.viewstates.length > 0) {
params.append("&__VIEWSTATE=");
params.append(urlencode_rfc3986(caches.viewstates[0]));
if (caches.viewstates.length > 1) {
for (int i = 1; i < caches.viewstates.length; i++) {
params.append("&__VIEWSTATE" + i + "=");
params.append(urlencode_rfc3986(caches.viewstates[i]));
}
params.append("&__VIEWSTATEFIELDCOUNT=" + caches.viewstates.length);
}
}
for (String cid : cids) {
params.append("&");
params.append("CID=");
params.append(urlencode_rfc3986(cid));
}
if (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0) {
params.append("&");
params.append("recaptcha_challenge_field=");
params.append(urlencode_rfc3986(recaptchaChallenge));
params.append("&");
params.append("recaptcha_response_field=");
params.append(urlencode_rfc3986(recaptchaText));
}
params.append("&");
params.append("ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints");
final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData();
if (coordinates != null && coordinates.length() > 0) {
if (coordinates.indexOf("You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com") > -1) {
Log.i(cgSettings.tag, "User has not agreed to the license agreement. Can\'t download .loc file.");
caches.error = errorRetrieve.get(-7);
return caches;
}
}
if (coordinates != null && coordinates.length() > 0) {
final HashMap<String, cgCoord> cidCoords = new HashMap<String, cgCoord>();
final Pattern patternCidCode = Pattern.compile("name id=\"([^\"]+)\"");
final Pattern patternCidLat = Pattern.compile("lat=\"([^\"]+)\"");
final Pattern patternCidLon = Pattern.compile("lon=\"([^\"]+)\"");
// premium only >>
final Pattern patternCidDif = Pattern.compile("<difficulty>([^<]+)</difficulty>");
final Pattern patternCidTer = Pattern.compile("<terrain>([^<]+)</terrain>");
final Pattern patternCidCon = Pattern.compile("<container>([^<]+)</container>");
// >> premium only
final String[] points = coordinates.split("<waypoint>");
// parse coordinates
for (String point : points) {
final cgCoord pointCoord = new cgCoord();
final Matcher matcherCidCode = patternCidCode.matcher(point);
final Matcher matcherLatCode = patternCidLat.matcher(point);
final Matcher matcherLonCode = patternCidLon.matcher(point);
final Matcher matcherDifCode = patternCidDif.matcher(point);
final Matcher matcherTerCode = patternCidTer.matcher(point);
final Matcher matcherConCode = patternCidCon.matcher(point);
HashMap<String, Object> tmp = null;
if (matcherCidCode.find()) {
pointCoord.name = matcherCidCode.group(1).trim().toUpperCase();
}
if (matcherLatCode.find()) {
tmp = parseCoordinate(matcherLatCode.group(1), "lat");
pointCoord.latitude = (Double) tmp.get("coordinate");
}
if (matcherLonCode.find()) {
tmp = parseCoordinate(matcherLonCode.group(1), "lon");
pointCoord.longitude = (Double) tmp.get("coordinate");
}
if (matcherDifCode.find()) {
pointCoord.difficulty = new Float(matcherDifCode.group(1));
}
if (matcherTerCode.find()) {
pointCoord.terrain = new Float(matcherTerCode.group(1));
}
if (matcherConCode.find()) {
final int size = Integer.parseInt(matcherConCode.group(1));
if (size == 1) {
pointCoord.size = "not chosen";
} else if (size == 2) {
pointCoord.size = "micro";
} else if (size == 3) {
pointCoord.size = "regular";
} else if (size == 4) {
pointCoord.size = "large";
} else if (size == 5) {
pointCoord.size = "virtual";
} else if (size == 6) {
pointCoord.size = "other";
} else if (size == 8) {
pointCoord.size = "small";
} else {
pointCoord.size = "unknown";
}
}
cidCoords.put(pointCoord.name, pointCoord);
}
Log.i(cgSettings.tag, "Coordinates found in .loc file: " + cidCoords.size());
// save found cache coordinates
for (cgCache oneCache : caches.cacheList) {
if (cidCoords.containsKey(oneCache.geocode)) {
cgCoord thisCoords = cidCoords.get(oneCache.geocode);
oneCache.latitude = thisCoords.latitude;
oneCache.longitude = thisCoords.longitude;
oneCache.difficulty = thisCoords.difficulty;
oneCache.terrain = thisCoords.terrain;
oneCache.size = thisCoords.size;
}
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.parseSearch.CIDs: " + e.toString());
}
}
// get direction images
for (cgCache oneCache : caches.cacheList) {
if (oneCache.latitude == null && oneCache.longitude == null && oneCache.direction == null && oneCache.directionImg != null) {
cgDirectionImg.getDrawable(oneCache.geocode, oneCache.directionImg);
}
}
// get ratings
if (guids.size() > 0) {
Log.i(cgSettings.tag, "Trying to get ratings for " + cids.size() + " caches");
try {
final HashMap<String, cgRating> ratings = getRating(guids, null);
if (ratings != null) {
// save found cache coordinates
for (cgCache oneCache : caches.cacheList) {
if (ratings.containsKey(oneCache.guid)) {
cgRating thisRating = ratings.get(oneCache.guid);
oneCache.rating = thisRating.rating;
oneCache.votes = thisRating.votes;
oneCache.myVote = thisRating.myVote;
}
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.parseSearch.GCvote: " + e.toString());
}
}
return caches;
}
public static cgCacheWrap parseMapJSON(String url, String data) {
if (data == null || data.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseMapJSON: No page given");
return null;
}
final cgCacheWrap caches = new cgCacheWrap();
caches.url = url;
try {
final JSONObject yoDawg = new JSONObject(data);
final String json = yoDawg.getString("d");
if (json == null || json.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseMapJSON: No JSON inside JSON");
return null;
}
final JSONObject dataJSON = new JSONObject(json);
final JSONObject extra = dataJSON.getJSONObject("cs");
if (extra != null && extra.length() > 0) {
int count = extra.getInt("count");
if (count > 0 && extra.has("cc")) {
final JSONArray cachesData = extra.getJSONArray("cc");
if (cachesData != null && cachesData.length() > 0) {
JSONObject oneCache = null;
for (int i = 0; i < count; i++) {
oneCache = cachesData.getJSONObject(i);
if (oneCache == null) {
break;
}
final cgCache cacheToAdd = new cgCache();
cacheToAdd.reliableLatLon = false;
cacheToAdd.geocode = oneCache.getString("gc");
cacheToAdd.latitude = oneCache.getDouble("lat");
cacheToAdd.longitude = oneCache.getDouble("lon");
cacheToAdd.name = oneCache.getString("nn");
cacheToAdd.found = oneCache.getBoolean("f");
cacheToAdd.own = oneCache.getBoolean("o");
cacheToAdd.disabled = !oneCache.getBoolean("ia");
int ctid = oneCache.getInt("ctid");
if (ctid == 2) {
cacheToAdd.type = "traditional";
} else if (ctid == 3) {
cacheToAdd.type = "multi";
} else if (ctid == 4) {
cacheToAdd.type = "virtual";
} else if (ctid == 5) {
cacheToAdd.type = "letterbox";
} else if (ctid == 6) {
cacheToAdd.type = "event";
} else if (ctid == 8) {
cacheToAdd.type = "mystery";
} else if (ctid == 11) {
cacheToAdd.type = "webcam";
} else if (ctid == 13) {
cacheToAdd.type = "cito";
} else if (ctid == 137) {
cacheToAdd.type = "earth";
} else if (ctid == 453) {
cacheToAdd.type = "mega";
} else if (ctid == 1858) {
cacheToAdd.type = "wherigo";
} else if (ctid == 3653) {
cacheToAdd.type = "lost";
}
caches.cacheList.add(cacheToAdd);
}
}
} else {
Log.w(cgSettings.tag, "There are no caches in viewport");
}
caches.totalCnt = caches.cacheList.size();
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.parseMapJSON: " + e.toString());
}
return caches;
}
public cgCacheWrap parseCache(String page, int reason) {
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: No page given");
return null;
}
final cgCacheWrap caches = new cgCacheWrap();
final cgCache cache = new cgCache();
if (page.indexOf("Cache is Unpublished") > -1) {
caches.error = "cache was unpublished";
return caches;
}
if (page.indexOf("Sorry, the owner of this listing has made it viewable to Premium Members only.") != -1) {
caches.error = "requested cache is for premium members only";
return caches;
}
if (page.indexOf("has chosen to make this cache listing visible to Premium Members only.") != -1) {
caches.error = "requested cache is for premium members only";
return caches;
}
if (page.indexOf("<li>This cache is temporarily unavailable.") != -1) {
cache.disabled = true;
} else {
cache.disabled = false;
}
if (page.indexOf("<li>This cache has been archived,") != -1) {
cache.archived = true;
} else {
cache.archived = false;
}
if (page.indexOf("<p class=\"Warning\">This is a Premium Member Only cache.</p>") != -1) {
cache.members = true;
} else {
cache.members = false;
}
cache.reason = reason;
// cache geocode
try {
final Matcher matcherGeocode = patternGeocode.matcher(page);
if (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
cache.geocode = getMatch(matcherGeocode.group(1));
}
}
} catch (Exception e) {
// failed to parse cache geocode
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache geocode");
}
// cache id
try {
final Matcher matcherCacheId = patternCacheId.matcher(page);
if (matcherCacheId.find()) {
if (matcherCacheId.groupCount() > 0) {
cache.cacheid = getMatch(matcherCacheId.group(1));
}
}
} catch (Exception e) {
// failed to parse cache id
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache id");
}
// cache guid
try {
final Matcher matcherCacheGuid = patternCacheGuid.matcher(page);
if (matcherCacheGuid.find()) {
if (matcherCacheGuid.groupCount() > 0) {
cache.guid = getMatch(matcherCacheGuid.group(1));
}
}
} catch (Exception e) {
// failed to parse cache guid
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache guid");
}
// name
try {
final Matcher matcherName = patternName.matcher(page);
if (matcherName.find()) {
if (matcherName.groupCount() > 0) {
cache.name = Html.fromHtml(matcherName.group(1)).toString();
}
}
} catch (Exception e) {
// failed to parse cache name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache name");
}
// owner real name
try {
final Matcher matcherOwnerReal = patternOwnerReal.matcher(page);
if (matcherOwnerReal.find()) {
if (matcherOwnerReal.groupCount() > 0) {
cache.ownerReal = URLDecoder.decode(matcherOwnerReal.group(1));
}
}
} catch (Exception e) {
// failed to parse owner real name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner real name");
}
final String username = settings.getUsername();
if (cache.ownerReal != null && username != null && cache.ownerReal.equalsIgnoreCase(username)) {
cache.own = true;
}
int pos = -1;
String tableInside = page;
pos = tableInside.indexOf("id=\"cacheDetails\"");
if (pos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"cacheDetails\" not found on page");
return null;
}
tableInside = tableInside.substring(pos);
pos = tableInside.indexOf("<div class=\"CacheInformationTable\"");
if (pos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"CacheInformationTable\" not found on page");
return null;
}
tableInside = tableInside.substring(0, pos);
if (tableInside != null && tableInside.length() > 0) {
// cache terrain
try {
final Matcher matcherTerrain = patternTerrain.matcher(tableInside);
if (matcherTerrain.find()) {
if (matcherTerrain.groupCount() > 0) {
cache.terrain = new Float(Pattern.compile("_").matcher(matcherTerrain.group(1)).replaceAll("."));
}
}
} catch (Exception e) {
// failed to parse terrain
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache terrain");
}
// cache difficulty
try {
final Matcher matcherDifficulty = patternDifficulty.matcher(tableInside);
if (matcherDifficulty.find()) {
if (matcherDifficulty.groupCount() > 0) {
cache.difficulty = new Float(Pattern.compile("_").matcher(matcherDifficulty.group(1)).replaceAll("."));
}
}
} catch (Exception e) {
// failed to parse difficulty
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache difficulty");
}
// owner
try {
final Matcher matcherOwner = patternOwner.matcher(tableInside);
if (matcherOwner.find()) {
if (matcherOwner.groupCount() > 0) {
cache.owner = Html.fromHtml(matcherOwner.group(2)).toString();
}
}
} catch (Exception e) {
// failed to parse owner
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner");
}
// hidden
try {
final Matcher matcherHidden = patternHidden.matcher(tableInside);
if (matcherHidden.find()) {
if (matcherHidden.groupCount() > 0) {
cache.hidden = parseDate(matcherHidden.group(1));
}
}
} catch (Exception e) {
// failed to parse cache hidden date
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hidden date");
}
if (cache.hidden == null) {
// event date
try {
final Matcher matcherHiddenEvent = patternHiddenEvent.matcher(tableInside);
if (matcherHiddenEvent.find()) {
if (matcherHiddenEvent.groupCount() > 0) {
cache.hidden = parseDate(matcherHiddenEvent.group(1));
}
}
} catch (Exception e) {
// failed to parse cache event date
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache event date");
}
}
// favourite
try {
final Matcher matcherFavourite = patternFavourite.matcher(tableInside);
if (matcherFavourite.find()) {
if (matcherFavourite.groupCount() > 0) {
cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
}
}
} catch (Exception e) {
// failed to parse favourite count
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse favourite count");
}
// cache size
try {
final Matcher matcherSize = patternSize.matcher(tableInside);
if (matcherSize.find()) {
if (matcherSize.groupCount() > 0) {
cache.size = getMatch(matcherSize.group(1)).toLowerCase();
}
}
} catch (Exception e) {
// failed to parse size
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache size");
}
}
// cache found
try {
final Matcher matcherFound = patternFound.matcher(page);
if (matcherFound.find()) {
if (matcherFound.group() != null && matcherFound.group().length() > 0) {
cache.found = true;
}
}
} catch (Exception e) {
// failed to parse found
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse found");
}
// cache type
try {
final Matcher matcherType = patternType.matcher(page);
if (matcherType.find()) {
if (matcherType.groupCount() > 0) {
cache.type = cacheTypes.get(matcherType.group(1).toLowerCase());
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache type");
}
// on watchlist
try {
final Matcher matcher = patternOnWatchlist.matcher(page);
cache.onWatchlist = matcher.find();
} catch (Exception e) {
// failed to parse watchlist state
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse watchlist state");
}
// latitude and logitude
try {
final Matcher matcherLatLon = patternLatLon.matcher(page);
if (matcherLatLon.find()) {
if (matcherLatLon.groupCount() > 0) {
cache.latlon = getMatch(matcherLatLon.group(2)); // first is <b>
HashMap<String, Object> tmp = cgBase.parseLatlon(cache.latlon);
if (tmp.size() > 0) {
cache.latitude = (Double) tmp.get("latitude");
cache.longitude = (Double) tmp.get("longitude");
cache.latitudeString = (String) tmp.get("latitudeString");
cache.longitudeString = (String) tmp.get("longitudeString");
cache.reliableLatLon = true;
}
tmp = null;
}
}
} catch (Exception e) {
// failed to parse latitude and/or longitude
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache coordinates");
}
// cache location
try {
final Matcher matcherLocation = patternLocation.matcher(page);
if (matcherLocation.find()) {
if (matcherLocation.groupCount() > 0) {
cache.location = getMatch(matcherLocation.group(1));
}
}
} catch (Exception e) {
// failed to parse location
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache location");
}
// cache hint
try {
final Matcher matcherHint = patternHint.matcher(page);
if (matcherHint.find()) {
if (matcherHint.groupCount() > 2 && matcherHint.group(3) != null) {
// replace linebreak and paragraph tags
String hint = Pattern.compile("<(br|p)[^>]*>").matcher(matcherHint.group(3)).replaceAll("\n");
if (hint != null) {
cache.hint = hint.replaceAll(Pattern.quote("</p>"), "").trim();
}
}
}
} catch (Exception e) {
// failed to parse hint
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hint");
}
checkFields(cache);
/*
// short info debug
Log.d(cgSettings.tag, "gc-code: " + cache.geocode);
Log.d(cgSettings.tag, "id: " + cache.cacheid);
Log.d(cgSettings.tag, "guid: " + cache.guid);
Log.d(cgSettings.tag, "name: " + cache.name);
Log.d(cgSettings.tag, "terrain: " + cache.terrain);
Log.d(cgSettings.tag, "difficulty: " + cache.difficulty);
Log.d(cgSettings.tag, "owner: " + cache.owner);
Log.d(cgSettings.tag, "owner (real): " + cache.ownerReal);
Log.d(cgSettings.tag, "hidden: " + dateOutShort.format(cache.hidden));
Log.d(cgSettings.tag, "favorite: " + cache.favouriteCnt);
Log.d(cgSettings.tag, "size: " + cache.size);
if (cache.found) {
Log.d(cgSettings.tag, "found!");
} else {
Log.d(cgSettings.tag, "not found");
}
Log.d(cgSettings.tag, "type: " + cache.type);
Log.d(cgSettings.tag, "latitude: " + String.format("%.6f", cache.latitude));
Log.d(cgSettings.tag, "longitude: " + String.format("%.6f", cache.longitude));
Log.d(cgSettings.tag, "location: " + cache.location);
Log.d(cgSettings.tag, "hint: " + cache.hint);
*/
// cache personal note
try {
final Matcher matcherPersonalNote = patternPersonalNote.matcher(page);
if (matcherPersonalNote.find()) {
if (matcherPersonalNote.groupCount() > 0) {
cache.personalNote = getMatch(matcherPersonalNote.group(1).trim());
}
}
} catch (Exception e) {
// failed to parse cache personal note
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache personal note");
}
// cache short description
try {
final Matcher matcherDescShort = patternDescShort.matcher(page);
if (matcherDescShort.find()) {
if (matcherDescShort.groupCount() > 0) {
cache.shortdesc = getMatch(matcherDescShort.group(1));
}
}
} catch (Exception e) {
// failed to parse short description
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache short description");
}
// cache description
try {
final Matcher matcherDesc = patternDesc.matcher(page);
if (matcherDesc.find()) {
if (matcherDesc.groupCount() > 0) {
cache.description = getMatch(matcherDesc.group(1));
}
}
} catch (Exception e) {
// failed to parse short description
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache description");
}
// cache attributes
try {
final Matcher matcherAttributes = patternAttributes.matcher(page);
while (matcherAttributes.find()) {
if (matcherAttributes.groupCount() > 0) {
final String attributesPre = matcherAttributes.group(1);
final Matcher matcherAttributesInside = patternAttributesInside.matcher(attributesPre);
while (matcherAttributesInside.find()) {
if (matcherAttributesInside.groupCount() > 1 && matcherAttributesInside.group(2).equalsIgnoreCase("blank") != true) {
if (cache.attributes == null) {
cache.attributes = new ArrayList<String>();
}
// by default, use the tooltip of the attribute
String attribute = matcherAttributesInside.group(2).toLowerCase();
// if the image name can be recognized, use the image name as attribute
String imageName = matcherAttributesInside.group(1).trim();
if (imageName.length() > 0) {
int start = imageName.lastIndexOf('/');
int end = imageName.lastIndexOf('.');
if (start >= 0 && end>= 0) {
- attribute = imageName.substring(start + 1, end).replace('-', '_');
+ attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase();
}
}
cache.attributes.add(attribute);
}
}
}
}
} catch (Exception e) {
// failed to parse cache attributes
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache attributes");
}
// cache spoilers
try {
final Matcher matcherSpoilers = patternSpoilers.matcher(page);
while (matcherSpoilers.find()) {
if (matcherSpoilers.groupCount() > 0) {
final String spoilersPre = matcherSpoilers.group(1);
final Matcher matcherSpoilersInside = patternSpoilersInside.matcher(spoilersPre);
while (matcherSpoilersInside.find()) {
if (matcherSpoilersInside.groupCount() > 0) {
final cgImage spoiler = new cgImage();
spoiler.url = matcherSpoilersInside.group(1);
if (matcherSpoilersInside.group(2) != null) {
spoiler.title = matcherSpoilersInside.group(2);
}
if (matcherSpoilersInside.group(4) != null) {
spoiler.description = matcherSpoilersInside.group(4);
}
if (cache.spoilers == null) {
cache.spoilers = new ArrayList<cgImage>();
}
cache.spoilers.add(spoiler);
}
}
}
}
} catch (Exception e) {
// failed to parse cache spoilers
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache spoilers");
}
// cache inventory
try {
cache.inventoryItems = 0;
final Matcher matcherInventory = patternInventory.matcher(page);
while (matcherInventory.find()) {
if (cache.inventory == null) {
cache.inventory = new ArrayList<cgTrackable>();
}
if (matcherInventory.groupCount() > 1) {
final String inventoryPre = matcherInventory.group(2);
if (inventoryPre != null && inventoryPre.length() > 0) {
final Matcher matcherInventoryInside = patternInventoryInside.matcher(inventoryPre);
while (matcherInventoryInside.find()) {
if (matcherInventoryInside.groupCount() > 0) {
final cgTrackable inventoryItem = new cgTrackable();
inventoryItem.guid = matcherInventoryInside.group(1);
inventoryItem.name = matcherInventoryInside.group(2);
cache.inventory.add(inventoryItem);
cache.inventoryItems++;
}
}
}
}
}
} catch (Exception e) {
// failed to parse cache inventory
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache inventory (2)");
}
// cache logs counts
try {
final Matcher matcherLogCounts = patternCountLogs.matcher(page);
while (matcherLogCounts.find()) {
if (matcherLogCounts.groupCount() > 0) {
final String[] logs = matcherLogCounts.group(1).split("<img");
final int logsCnt = logs.length;
for (int k = 1; k < logsCnt; k++) {
Integer type = null;
Integer count = null;
final Matcher matcherLog = patternCountLog.matcher(logs[k]);
if (matcherLog.find()) {
String typeStr = matcherLog.group(1);
String countStr = matcherLog.group(2);
if (typeStr != null && typeStr.length() > 0) {
if (logTypes.containsKey(typeStr.toLowerCase())) {
type = logTypes.get(typeStr.toLowerCase());
}
}
if (countStr != null && countStr.length() > 0) {
count = Integer.parseInt(countStr);
}
if (type != null && count != null) {
cache.logCounts.put(type, count);
}
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache log count");
}
// cache logs
try {
final Matcher matcherLogs = patternLogs.matcher(page);
while (matcherLogs.find()) {
if (matcherLogs.groupCount() > 0) {
final String[] logs = matcherLogs.group(1).split("</tr><tr>");
final int logsCnt = logs.length;
for (int k = 0; k < logsCnt; k++) {
final Matcher matcherLog = patternLog.matcher(logs[k]);
if (matcherLog.find()) {
final cgLog logDone = new cgLog();
String logTmp = matcherLog.group(10);
int day = -1;
try {
day = Integer.parseInt(matcherLog.group(3));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (day): " + e.toString());
}
int month = -1;
// January | February | March | April | May | June | July | August | September | October | November | December
if (matcherLog.group(2).equalsIgnoreCase("January")) {
month = 0;
} else if (matcherLog.group(2).equalsIgnoreCase("February")) {
month = 1;
} else if (matcherLog.group(2).equalsIgnoreCase("March")) {
month = 2;
} else if (matcherLog.group(2).equalsIgnoreCase("April")) {
month = 3;
} else if (matcherLog.group(2).equalsIgnoreCase("May")) {
month = 4;
} else if (matcherLog.group(2).equalsIgnoreCase("June")) {
month = 5;
} else if (matcherLog.group(2).equalsIgnoreCase("July")) {
month = 6;
} else if (matcherLog.group(2).equalsIgnoreCase("August")) {
month = 7;
} else if (matcherLog.group(2).equalsIgnoreCase("September")) {
month = 8;
} else if (matcherLog.group(2).equalsIgnoreCase("October")) {
month = 9;
} else if (matcherLog.group(2).equalsIgnoreCase("November")) {
month = 10;
} else if (matcherLog.group(2).equalsIgnoreCase("December")) {
month = 11;
} else {
Log.w(cgSettings.tag, "Failed to parse logs date (month).");
}
int year = -1;
final String yearPre = matcherLog.group(5);
if (yearPre == null) {
Calendar date = Calendar.getInstance();
year = date.get(Calendar.YEAR);
} else {
try {
year = Integer.parseInt(matcherLog.group(5));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (year): " + e.toString());
}
}
long logDate;
if (year > 0 && month >= 0 && day > 0) {
Calendar date = Calendar.getInstance();
date.set(year, month, day, 12, 0, 0);
logDate = date.getTimeInMillis();
logDate = (logDate / 1000L) * 1000L;
} else {
logDate = 0;
}
if (logTypes.containsKey(matcherLog.group(1).toLowerCase())) {
logDone.type = logTypes.get(matcherLog.group(1).toLowerCase());
} else {
logDone.type = logTypes.get("icon_note");
}
logDone.author = Html.fromHtml(matcherLog.group(6)).toString();
logDone.date = logDate;
if (matcherLog.group(8) != null) {
logDone.found = new Integer(matcherLog.group(8));
}
final Matcher matcherImg = patternLogImgs.matcher(logs[k]);
while (matcherImg.find()) {
final cgImage logImage = new cgImage();
logImage.url = "http://img.geocaching.com/cache/log/" + matcherImg.group(1);
logImage.title = matcherImg.group(2);
if (logDone.logImages == null) {
logDone.logImages = new ArrayList<cgImage>();
}
logDone.logImages.add(logImage);
}
logDone.log = logTmp;
if (cache.logs == null) {
cache.logs = new ArrayList<cgLog>();
}
cache.logs.add(logDone);
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache logs");
}
int wpBegin = 0;
int wpEnd = 0;
wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">");
if (wpBegin != -1) { // parse waypoints
final Pattern patternWpType = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg", Pattern.CASE_INSENSITIVE);
final Pattern patternWpPrefixOrLookupOrLatlon = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>", Pattern.CASE_INSENSITIVE);
final Pattern patternWpName = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>", Pattern.CASE_INSENSITIVE);
final Pattern patternWpNote = Pattern.compile("colspan=\"6\">(.*)<\\/td>", Pattern.CASE_INSENSITIVE);
String wpList = page.substring(wpBegin);
wpEnd = wpList.indexOf("</p>");
if (wpEnd > -1 && wpEnd <= wpList.length()) {
wpList = wpList.substring(0, wpEnd);
}
if (wpList.indexOf("No additional waypoints to display.") == -1) {
wpEnd = wpList.indexOf("</table>");
wpList = wpList.substring(0, wpEnd);
wpBegin = wpList.indexOf("<tbody>");
wpEnd = wpList.indexOf("</tbody>");
if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) {
wpList = wpList.substring(wpBegin + 7, wpEnd);
}
final String[] wpItems = wpList.split("<tr");
String[] wp;
for (int j = 1; j < wpItems.length; j++) {
final cgWaypoint waypoint = new cgWaypoint();
wp = wpItems[j].split("<td");
// waypoint type
try {
final Matcher matcherWpType = patternWpType.matcher(wp[3]);
while (matcherWpType.find()) {
if (matcherWpType.groupCount() > 0) {
waypoint.type = matcherWpType.group(1);
if (waypoint.type != null) {
waypoint.type = waypoint.type.trim();
}
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint type");
}
// waypoint prefix
try {
final Matcher matcherWpPrefix = patternWpPrefixOrLookupOrLatlon.matcher(wp[4]);
while (matcherWpPrefix.find()) {
if (matcherWpPrefix.groupCount() > 1) {
waypoint.prefix = matcherWpPrefix.group(2);
if (waypoint.prefix != null) {
waypoint.prefix = waypoint.prefix.trim();
}
}
}
} catch (Exception e) {
// failed to parse prefix
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint prefix");
}
// waypoint lookup
try {
final Matcher matcherWpLookup = patternWpPrefixOrLookupOrLatlon.matcher(wp[5]);
while (matcherWpLookup.find()) {
if (matcherWpLookup.groupCount() > 1) {
waypoint.lookup = matcherWpLookup.group(2);
if (waypoint.lookup != null) {
waypoint.lookup = waypoint.lookup.trim();
}
}
}
} catch (Exception e) {
// failed to parse lookup
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint lookup");
}
// waypoint name
try {
final Matcher matcherWpName = patternWpName.matcher(wp[6]);
while (matcherWpName.find()) {
if (matcherWpName.groupCount() > 0) {
waypoint.name = matcherWpName.group(1);
if (waypoint.name != null) {
waypoint.name = waypoint.name.trim();
}
}
}
} catch (Exception e) {
// failed to parse name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint name");
}
// waypoint latitude and logitude
try {
final Matcher matcherWpLatLon = patternWpPrefixOrLookupOrLatlon.matcher(wp[7]);
while (matcherWpLatLon.find()) {
if (matcherWpLatLon.groupCount() > 1) {
waypoint.latlon = Html.fromHtml(matcherWpLatLon.group(2)).toString();
final HashMap<String, Object> tmp = cgBase.parseLatlon(waypoint.latlon);
if (tmp.size() > 0) {
waypoint.latitude = (Double) tmp.get("latitude");
waypoint.longitude = (Double) tmp.get("longitude");
waypoint.latitudeString = (String) tmp.get("latitudeString");
waypoint.longitudeString = (String) tmp.get("longitudeString");
}
}
}
} catch (Exception e) {
// failed to parse latitude and/or longitude
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint coordinates");
}
j++;
if (wpItems.length > j) {
wp = wpItems[j].split("<td");
}
// waypoint note
try {
final Matcher matcherWpNote = patternWpNote.matcher(wp[3]);
while (matcherWpNote.find()) {
if (matcherWpNote.groupCount() > 0) {
waypoint.note = matcherWpNote.group(1);
if (waypoint.note != null) {
waypoint.note = waypoint.note.trim();
}
}
}
} catch (Exception e) {
// failed to parse note
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint note");
}
if (cache.waypoints == null)
cache.waypoints = new ArrayList<cgWaypoint>();
cache.waypoints.add(waypoint);
}
}
}
if (cache.latitude != null && cache.longitude != null) {
cache.elevation = getElevation(cache.latitude, cache.longitude);
}
final cgRating rating = getRating(cache.guid, cache.geocode);
if (rating != null) {
cache.rating = rating.rating;
cache.votes = rating.votes;
cache.myVote = rating.myVote;
}
cache.updated = System.currentTimeMillis();
cache.detailedUpdate = System.currentTimeMillis();
cache.detailed = true;
caches.cacheList.add(cache);
return caches;
}
private void checkFields(cgCache cache) {
if (cache.geocode == null || cache.geocode.length() == 0) {
Log.w(cgSettings.tag, "geo code not parsed correctly");
}
if (cache.name == null || cache.name.length() == 0) {
Log.w(cgSettings.tag, "name not parsed correctly");
}
if (cache.guid == null || cache.guid.length() == 0) {
Log.w(cgSettings.tag, "guid not parsed correctly");
}
if (cache.terrain == null || cache.terrain == 0.0) {
Log.w(cgSettings.tag, "terrain not parsed correctly");
}
if (cache.difficulty == null || cache.difficulty == 0.0) {
Log.w(cgSettings.tag, "difficulty not parsed correctly");
}
if (cache.owner == null || cache.owner.length() == 0) {
Log.w(cgSettings.tag, "owner not parsed correctly");
}
if (cache.ownerReal == null || cache.ownerReal.length() == 0) {
Log.w(cgSettings.tag, "owner real not parsed correctly");
}
if (cache.hidden == null) {
Log.w(cgSettings.tag, "hidden not parsed correctly");
}
if (cache.favouriteCnt == null) {
Log.w(cgSettings.tag, "favoriteCount not parsed correctly");
}
if (cache.size == null || cache.size.length() == 0) {
Log.w(cgSettings.tag, "size not parsed correctly");
}
if (cache.type == null || cache.type.length() == 0) {
Log.w(cgSettings.tag, "type not parsed correctly");
}
if (cache.latitude == null) {
Log.w(cgSettings.tag, "latitude not parsed correctly");
}
if (cache.longitude == null) {
Log.w(cgSettings.tag, "longitude not parsed correctly");
}
if (cache.location == null || cache.location.length() == 0) {
Log.w(cgSettings.tag, "location not parsed correctly");
}
}
private static String getMatch(String match) {
// creating a new String via String constructor is necessary here!!
return new String(match);
// Java copies the whole page String, when matching with regular expressions
// later this would block the garbage collector, as we only need tiny parts of the page
// see http://developer.android.com/reference/java/lang/String.html#backing_array
// And BTW: You cannot even see that effect in the debugger, but must use a separate memory profiler!
}
private static Date parseDate(String input) {
if (input == null) {
return null;
}
input = input.trim();
try {
Date result;
if (input.indexOf('/') > 0) {
result = dateInBackslash.parse(input);
if (result != null) {
return result;
}
}
if (input.indexOf('-') > 0) {
result = dateInDash.parse(input);
if (result != null) {
return result;
}
}
result = dateEvIn.parse(input);
if (result != null) {
return result;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public cgRating getRating(String guid, String geocode) {
ArrayList<String> guids = null;
ArrayList<String> geocodes = null;
if (guid != null && guid.length() > 0) {
guids = new ArrayList<String>();
guids.add(guid);
} else if (geocode != null && geocode.length() > 0) {
geocodes = new ArrayList<String>();
geocodes.add(geocode);
} else {
return null;
}
final HashMap<String, cgRating> ratings = getRating(guids, geocodes);
if(ratings != null){
for (Entry<String, cgRating> entry : ratings.entrySet()) {
return entry.getValue();
}
}
return null;
}
public HashMap<String, cgRating> getRating(ArrayList<String> guids, ArrayList<String> geocodes) {
if (guids == null && geocodes == null) {
return null;
}
final HashMap<String, cgRating> ratings = new HashMap<String, cgRating>();
try {
final HashMap<String, String> params = new HashMap<String, String>();
if (settings.isLogin()) {
final HashMap<String, String> login = settings.getGCvoteLogin();
if (login != null) {
params.put("userName", login.get("username"));
params.put("password", login.get("password"));
}
}
if (guids != null && guids.size() > 0) {
params.put("cacheIds", implode(",", guids.toArray()));
} else {
params.put("waypoints", implode(",", geocodes.toArray()));
}
params.put("version", "cgeo");
final String votes = request(false, "gcvote.com", "/getVotes.php", "GET", params, false, false, false).getData();
if (votes == null) {
return null;
}
final Pattern patternLogIn = Pattern.compile("loggedIn='([^']+)'", Pattern.CASE_INSENSITIVE);
final Pattern patternGuid = Pattern.compile("cacheId='([^']+)'", Pattern.CASE_INSENSITIVE);
final Pattern patternRating = Pattern.compile("voteAvg='([0-9\\.]+)'", Pattern.CASE_INSENSITIVE);
final Pattern patternVotes = Pattern.compile("voteCnt='([0-9]+)'", Pattern.CASE_INSENSITIVE);
final Pattern patternVote = Pattern.compile("voteUser='([0-9\\.]+)'", Pattern.CASE_INSENSITIVE);
String voteData = null;
final Pattern patternVoteElement = Pattern.compile("<vote ([^>]+)>", Pattern.CASE_INSENSITIVE);
final Matcher matcherVoteElement = patternVoteElement.matcher(votes);
while (matcherVoteElement.find()) {
if (matcherVoteElement.groupCount() > 0) {
voteData = matcherVoteElement.group(1);
}
if (voteData == null) {
continue;
}
String guid = null;
cgRating rating = new cgRating();
boolean loggedIn = false;
try {
final Matcher matcherGuid = patternGuid.matcher(voteData);
if (matcherGuid.find()) {
if (matcherGuid.groupCount() > 0) {
guid = (String) matcherGuid.group(1);
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse guid");
}
try {
final Matcher matcherLoggedIn = patternLogIn.matcher(votes);
if (matcherLoggedIn.find()) {
if (matcherLoggedIn.groupCount() > 0) {
if (matcherLoggedIn.group(1).equalsIgnoreCase("true")) {
loggedIn = true;
}
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse loggedIn");
}
try {
final Matcher matcherRating = patternRating.matcher(voteData);
if (matcherRating.find()) {
if (matcherRating.groupCount() > 0) {
rating.rating = Float.parseFloat(matcherRating.group(1));
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse rating");
}
try {
final Matcher matcherVotes = patternVotes.matcher(voteData);
if (matcherVotes.find()) {
if (matcherVotes.groupCount() > 0) {
rating.votes = Integer.parseInt(matcherVotes.group(1));
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse vote count");
}
if (loggedIn) {
try {
final Matcher matcherVote = patternVote.matcher(voteData);
if (matcherVote.find()) {
if (matcherVote.groupCount() > 0) {
rating.myVote = Float.parseFloat(matcherVote.group(1));
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.getRating: Failed to parse user's vote");
}
}
if (guid != null) {
ratings.put(guid, rating);
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.getRating: " + e.toString());
}
return ratings;
}
public static Long parseGPX(cgeoapplication app, File file, int listId, Handler handler) {
cgSearch search = new cgSearch();
long searchId = 0l;
try {
cgGPXParser GPXparser = new cgGPXParser(app, listId, search);
searchId = GPXparser.parse(file, 10, handler);
if (searchId == 0l) {
searchId = GPXparser.parse(file, 11, handler);
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.parseGPX: " + e.toString());
}
Log.i(cgSettings.tag, "Caches found in .gpx file: " + app.getCount(searchId));
return search.getCurrentId();
}
public cgTrackable parseTrackable(String page) {
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseTrackable: No page given");
return null;
}
final Pattern patternTrackableId = Pattern.compile("<a id=\"ctl00_ContentBody_LogLink\" title=\"[^\"]*\" href=\".*log\\.aspx\\?wid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>", Pattern.CASE_INSENSITIVE);
final Pattern patternGeocode = Pattern.compile("<span id=\"ctl00_ContentBody_BugDetails_BugTBNum\" String=\"[^\"]*\">Use[^<]*<strong>(TB[0-9a-z]+)[^<]*</strong> to reference this item.[^<]*</span>", Pattern.CASE_INSENSITIVE);
final Pattern patternName = Pattern.compile("<h2>([^<]*<img[^>]*>)?[^<]*<span id=\"ctl00_ContentBody_lbHeading\">([^<]+)</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE);
final Pattern patternOwner = Pattern.compile("<dt>\\W*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternReleased = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternOrigin = Pattern.compile("<dt>\\W*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternSpottedCache = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternSpottedUser = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternSpottedUnknown = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternSpottedOwner = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE);
final Pattern patternGoal = Pattern.compile("<h3>\\W*Current GOAL[^<]*</h3>[^<]*<p[^>]*>(.*)</p>[^<]*<h3>\\W*About This Item[^<]*</h3>", Pattern.CASE_INSENSITIVE);
final Pattern patternDetailsImage = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*<div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">", Pattern.CASE_INSENSITIVE);
final Pattern patternLogs = Pattern.compile("<table class=\"TrackableItemLogTable Table\">(.*)<\\/table>[^<]*<ul", Pattern.CASE_INSENSITIVE);
final Pattern patternIcon = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
final Pattern patternType = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
final Pattern patternDistance = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9\\.,]+(km|mi))[^\\)]*\\)", Pattern.CASE_INSENSITIVE);
final cgTrackable trackable = new cgTrackable();
// trackable geocode
try {
final Matcher matcherGeocode = patternGeocode.matcher(page);
while (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
trackable.geocode = matcherGeocode.group(1).toUpperCase();
}
}
} catch (Exception e) {
// failed to parse trackable geocode
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable geocode");
}
// trackable id
try {
final Matcher matcherTrackableId = patternTrackableId.matcher(page);
while (matcherTrackableId.find()) {
if (matcherTrackableId.groupCount() > 0) {
trackable.guid = matcherTrackableId.group(1);
}
}
} catch (Exception e) {
// failed to parse trackable id
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable id");
}
// trackable icon
try {
final Matcher matcherTrackableIcon = patternIcon.matcher(page);
while (matcherTrackableIcon.find()) {
if (matcherTrackableIcon.groupCount() > 0) {
trackable.iconUrl = matcherTrackableIcon.group(1);
}
}
} catch (Exception e) {
// failed to parse trackable icon
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable icon");
}
// trackable name
try {
final Matcher matcherName = patternName.matcher(page);
while (matcherName.find()) {
if (matcherName.groupCount() > 1) {
trackable.name = matcherName.group(2);
}
}
} catch (Exception e) {
// failed to parse trackable name
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable name");
}
// trackable type
if (trackable.name != null && trackable.name.length() > 0) {
try {
final Matcher matcherType = patternType.matcher(page);
while (matcherType.find()) {
if (matcherType.groupCount() > 0) {
trackable.type = matcherType.group(1);
}
}
} catch (Exception e) {
// failed to parse trackable type
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable type");
}
}
// trackable owner name
try {
final Matcher matcherOwner = patternOwner.matcher(page);
while (matcherOwner.find()) {
if (matcherOwner.groupCount() > 0) {
trackable.ownerGuid = matcherOwner.group(1);
trackable.owner = matcherOwner.group(2);
}
}
} catch (Exception e) {
// failed to parse trackable owner name
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable owner name");
}
// trackable origin
try {
final Matcher matcherOrigin = patternOrigin.matcher(page);
while (matcherOrigin.find()) {
if (matcherOrigin.groupCount() > 0) {
trackable.origin = matcherOrigin.group(1);
}
}
} catch (Exception e) {
// failed to parse trackable origin
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable origin");
}
// trackable spotted
try {
final Matcher matcherSpottedCache = patternSpottedCache.matcher(page);
while (matcherSpottedCache.find()) {
if (matcherSpottedCache.groupCount() > 0) {
trackable.spottedGuid = matcherSpottedCache.group(1);
trackable.spottedName = matcherSpottedCache.group(2);
trackable.spottedType = cgTrackable.SPOTTED_CACHE;
}
}
final Matcher matcherSpottedUser = patternSpottedUser.matcher(page);
while (matcherSpottedUser.find()) {
if (matcherSpottedUser.groupCount() > 0) {
trackable.spottedGuid = matcherSpottedUser.group(1);
trackable.spottedName = matcherSpottedUser.group(2);
trackable.spottedType = cgTrackable.SPOTTED_USER;
}
}
final Matcher matcherSpottedUnknown = patternSpottedUnknown.matcher(page);
if (matcherSpottedUnknown.find()) {
trackable.spottedType = cgTrackable.SPOTTED_UNKNOWN;
}
final Matcher matcherSpottedOwner = patternSpottedOwner.matcher(page);
if (matcherSpottedOwner.find()) {
trackable.spottedType = cgTrackable.SPOTTED_OWNER;
}
} catch (Exception e) {
// failed to parse trackable last known place
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable last known place");
}
// released
try {
final Matcher matcherReleased = patternReleased.matcher(page);
while (matcherReleased.find()) {
if (matcherReleased.groupCount() > 0 && matcherReleased.group(1) != null) {
try {
if (trackable.released == null) {
trackable.released = dateTbIn1.parse(matcherReleased.group(1));
}
} catch (Exception e) {
//
}
try {
if (trackable.released == null) {
trackable.released = dateTbIn2.parse(matcherReleased.group(1));
}
} catch (Exception e) {
//
}
}
}
} catch (Exception e) {
// failed to parse trackable released date
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable released date");
}
// trackable distance
try {
final Matcher matcherDistance = patternDistance.matcher(page);
while (matcherDistance.find()) {
if (matcherDistance.groupCount() > 0) {
trackable.distance = parseDistance(matcherDistance.group(1));
}
}
} catch (Exception e) {
// failed to parse trackable distance
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable distance");
}
// trackable goal
try {
final Matcher matcherGoal = patternGoal.matcher(page);
while (matcherGoal.find()) {
if (matcherGoal.groupCount() > 0) {
trackable.goal = matcherGoal.group(1);
}
}
} catch (Exception e) {
// failed to parse trackable goal
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable goal");
}
// trackable details & image
try {
final Matcher matcherDetailsImage = patternDetailsImage.matcher(page);
while (matcherDetailsImage.find()) {
if (matcherDetailsImage.groupCount() > 0) {
final String image = matcherDetailsImage.group(3);
final String details = matcherDetailsImage.group(4);
if (image != null) {
trackable.image = image;
}
if (details != null) {
trackable.details = details;
}
}
}
} catch (Exception e) {
// failed to parse trackable details & image
Log.w(cgSettings.tag, "cgeoBase.parseTrackable: Failed to parse trackable details & image");
}
// trackable logs
try {
final Matcher matcherLogs = patternLogs.matcher(page);
while (matcherLogs.find()) {
if (matcherLogs.groupCount() > 0) {
final Pattern patternLog = Pattern.compile("[^>]*>" +
"[^<]*<td[^<]*<img src=[\"|'].*\\/icons\\/([^\\.]+)\\.[a-z]{2,5}[\"|'][^>]*> (\\d+).(\\d+).(\\d+)[^<]*</td>" +
"[^<]*<td>[^<]*<a href=[^>]+>([^<]+)<.a>([^<]*|[^<]*<a href=[\"|'].*guid=([^\"]*)\">([^<]*)</a>[^<]*)</td>" +
"[^<]*<td>[^<]*</td>" +
"[^<]*<td[^<]*<a href=[^>]+>[^<]+</a>[^<]*</td>[^<]*</tr>" +
"[^<]*<tr[^>]*>[^<]*<td[^>]*>(.*?)</td>[^<]*</tr>.*" +
"");
// 1 filename == type
// 2 month
// 3 date
// 4 year
// 5 user
// 6 action dependent
// 7 cache guid
// 8 cache name
// 9 text
final String[] logs = matcherLogs.group(1).split("<tr class=\"Data BorderTop");
final int logsCnt = logs.length;
for (int k = 1; k < logsCnt; k++) {
final Matcher matcherLog = patternLog.matcher(logs[k]);
if (matcherLog.find()) {
final cgLog logDone = new cgLog();
String logTmp = matcherLog.group(9);
logTmp = Pattern.compile("<p>").matcher(logTmp).replaceAll("\n");
logTmp = Pattern.compile("<br[^>]*>").matcher(logTmp).replaceAll("\n");
logTmp = Pattern.compile("<\\/p>").matcher(logTmp).replaceAll("");
logTmp = Pattern.compile("\r+").matcher(logTmp).replaceAll("\n");
int day = -1;
try {
day = Integer.parseInt(matcherLog.group(3));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (day): " + e.toString());
}
int month = -1;
try {
month = Integer.parseInt(matcherLog.group(2));
month -= 1;
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (month): " + e.toString());
}
int year = -1;
try {
year = Integer.parseInt(matcherLog.group(4));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (year): " + e.toString());
}
long logDate;
if (year > 0 && month >= 0 && day > 0) {
Calendar date = Calendar.getInstance();
date.set(year, month, day, 12, 0, 0);
logDate = date.getTimeInMillis();
logDate = (logDate / 1000L) * 1000L;
} else {
logDate = 0;
}
if (logTypes.containsKey(matcherLog.group(1).toLowerCase())) {
logDone.type = logTypes.get(matcherLog.group(1).toLowerCase());
} else {
logDone.type = logTypes.get("icon_note");
}
logDone.author = Html.fromHtml(matcherLog.group(5)).toString();
logDone.date = logDate;
logDone.log = logTmp;
if (matcherLog.group(7) != null && matcherLog.group(8) != null) {
logDone.cacheGuid = matcherLog.group(7);
logDone.cacheName = matcherLog.group(8);
}
trackable.logs.add(logDone);
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache logs");
}
app.saveTrackable(trackable);
return trackable;
}
public static ArrayList<Integer> parseTypes(String page) {
if (page == null || page.length() == 0) {
return null;
}
final ArrayList<Integer> types = new ArrayList<Integer>();
final Pattern typeBoxPattern = Pattern.compile("<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>"
+ "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>", Pattern.CASE_INSENSITIVE);
final Matcher typeBoxMatcher = typeBoxPattern.matcher(page);
String typesText = null;
if (typeBoxMatcher.find()) {
if (typeBoxMatcher.groupCount() > 0) {
typesText = typeBoxMatcher.group(1);
}
}
if (typesText != null) {
final Pattern typePattern = Pattern.compile("<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE);
final Matcher typeMatcher = typePattern.matcher(typesText);
while (typeMatcher.find()) {
if (typeMatcher.groupCount() > 1) {
final int type = Integer.parseInt(typeMatcher.group(2));
if (type > 0) {
types.add(type);
}
}
}
}
return types;
}
public static ArrayList<cgTrackableLog> parseTrackableLog(String page) {
if (page == null || page.length() == 0) {
return null;
}
final ArrayList<cgTrackableLog> trackables = new ArrayList<cgTrackableLog>();
int startPos = -1;
int endPos = -1;
startPos = page.indexOf("<table id=\"tblTravelBugs\"");
if (startPos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: ID \"tblTravelBugs\" not found on page");
return null;
}
page = page.substring(startPos); // cut on <table
endPos = page.indexOf("</table>");
if (endPos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: end of ID \"tblTravelBugs\" not found on page");
return null;
}
page = page.substring(0, endPos); // cut on </table>
startPos = page.indexOf("<tbody>");
if (startPos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: tbody not found on page");
return null;
}
page = page.substring(startPos); // cut on <tbody>
endPos = page.indexOf("</tbody>");
if (endPos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseTrackableLog: end of tbody not found on page");
return null;
}
page = page.substring(0, endPos); // cut on </tbody>
final Pattern trackablePattern = Pattern.compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>"
+ "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>"
+ "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>"
+ "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+"
+ "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE);
final Matcher trackableMatcher = trackablePattern.matcher(page);
while (trackableMatcher.find()) {
if (trackableMatcher.groupCount() > 0) {
final cgTrackableLog trackable = new cgTrackableLog();
if (trackableMatcher.group(1) != null) {
trackable.trackCode = trackableMatcher.group(1);
} else {
continue;
}
if (trackableMatcher.group(2) != null) {
trackable.name = Html.fromHtml(trackableMatcher.group(2)).toString();
} else {
continue;
}
if (trackableMatcher.group(3) != null) {
trackable.ctl = new Integer(trackableMatcher.group(3));
} else {
continue;
}
if (trackableMatcher.group(5) != null) {
trackable.id = new Integer(trackableMatcher.group(5));
} else {
continue;
}
Log.i(cgSettings.tag, "Trackable in inventory (#" + trackable.ctl + "/" + trackable.id + "): " + trackable.trackCode + " - " + trackable.name);
trackables.add(trackable);
}
}
return trackables;
}
public static int parseFindCount(String page) {
if (page == null || page.length() == 0) {
return -1;
}
int findCount = -1;
try {
final Pattern findPattern = Pattern.compile("<strong>Caches Found:<\\/strong>([^<]+)<br", Pattern.CASE_INSENSITIVE);
final Matcher findMatcher = findPattern.matcher(page);
if (findMatcher.find()) {
if (findMatcher.groupCount() > 0) {
String count = findMatcher.group(1);
if (count != null) {
count = count.trim().replaceAll(",", "");
if (count.length() == 0) {
findCount = 0;
} else {
findCount = Integer.parseInt(count);
}
}
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.parseFindCount: " + e.toString());
}
return findCount;
}
public static String stripParagraphs(String text) {
if (text == null) {
return "";
}
final Pattern patternP = Pattern.compile("(<p>|</p>|<br \\/>|<br>)", Pattern.CASE_INSENSITIVE);
final Pattern patternP2 = Pattern.compile("([ ]+)", Pattern.CASE_INSENSITIVE);
final Matcher matcherP = patternP.matcher(text);
final Matcher matcherP2 = patternP2.matcher(text);
matcherP.replaceAll(" ");
matcherP2.replaceAll(" ");
return text.trim();
}
public static String stripTags(String text) {
if (text == null) {
return "";
}
final Pattern patternP = Pattern.compile("(<[^>]+>)", Pattern.CASE_INSENSITIVE);
final Matcher matcherP = patternP.matcher(text);
matcherP.replaceAll(" ");
return text.trim();
}
public static String capitalizeSentence(String sentence) {
if (sentence == null) {
return "";
}
final String[] word = sentence.split(" ");
for (int i = 0; i < word.length; i++) {
word[i] = capitalizeWord(word[i]);
}
return implode(" ", word);
}
public static String capitalizeWord(String word) {
if (word.length() == 0) {
return word;
}
return (word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase());
}
public static Double parseDistance(String dst) {
Double distance = null;
final Pattern pattern = Pattern.compile("([0-9\\.,]+)[ ]*(km|mi)", Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(dst);
while (matcher.find()) {
if (matcher.groupCount() > 1) {
if (matcher.group(2).equalsIgnoreCase("km")) {
distance = Double.valueOf(matcher.group(1));
} else {
distance = Double.valueOf(matcher.group(1)) / kmInMiles;
}
}
}
return distance;
}
public static double getDistance(Double lat1, Double lon1, Double lat2, Double lon2) {
if (lat1 == null || lon1 == null || lat2 == null || lon2 == null) {
return 0d;
}
lat1 *= deg2rad;
lon1 *= deg2rad;
lat2 *= deg2rad;
lon2 *= deg2rad;
final double d = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2);
final double distance = erad * Math.acos(d); // distance in km
if (Double.isNaN(distance) == false && distance > 0) {
return distance;
} else {
return 0d;
}
}
public static Double getHeading(Double lat1, Double lon1, Double lat2, Double lon2) {
Double result = Double.valueOf(0);
int ilat1 = (int) Math.round(0.5 + lat1 * 360000);
int ilon1 = (int) Math.round(0.5 + lon1 * 360000);
int ilat2 = (int) Math.round(0.5 + lat2 * 360000);
int ilon2 = (int) Math.round(0.5 + lon2 * 360000);
lat1 *= deg2rad;
lon1 *= deg2rad;
lat2 *= deg2rad;
lon2 *= deg2rad;
if (ilat1 == ilat2 && ilon1 == ilon2) {
return Double.valueOf(result);
} else if (ilat1 == ilat2) {
if (ilon1 > ilon2) {
result = Double.valueOf(270);
} else {
result = Double.valueOf(90);
}
} else if (ilon1 == ilon2) {
if (ilat1 > ilat2) {
result = Double.valueOf(180);
}
} else {
Double c = Math.acos(Math.sin(lat2) * Math.sin(lat1) + Math.cos(lat2) * Math.cos(lat1) * Math.cos(lon2 - lon1));
Double A = Math.asin(Math.cos(lat2) * Math.sin(lon2 - lon1) / Math.sin(c));
result = Double.valueOf(A * rad2deg);
if (ilat2 > ilat1 && ilon2 > ilon1) {
// result don't need change
} else if (ilat2 < ilat1 && ilon2 < ilon1) {
result = 180f - result;
} else if (ilat2 < ilat1 && ilon2 > ilon1) {
result = 180f - result;
} else if (ilat2 > ilat1 && ilon2 < ilon1) {
result += 360f;
}
}
return result;
}
public static HashMap<String, Double> getRadialDistance(Double latitude, Double longitude, Double bearing, Double distance) {
final Double rlat1 = latitude * deg2rad;
final Double rlon1 = longitude * deg2rad;
final Double rbearing = bearing * deg2rad;
final Double rdistance = distance / erad;
final Double rlat = Math.asin(Math.sin(rlat1) * Math.cos(rdistance) + Math.cos(rlat1) * Math.sin(rdistance) * Math.cos(rbearing));
final Double rlon = rlon1 + Math.atan2(Math.sin(rbearing) * Math.sin(rdistance) * Math.cos(rlat1), Math.cos(rdistance) - Math.sin(rlat1) * Math.sin(rlat));
HashMap<String, Double> result = new HashMap<String, Double>();
result.put("latitude", rlat * rad2deg);
result.put("longitude", rlon * rad2deg);
return result;
}
public String getHumanDistance(Float distance) {
if (distance == null) {
return "?";
}
return getHumanDistance(Double.valueOf(distance));
}
public String getHumanDistance(Double distance) {
if (distance == null) {
return "?";
}
if (settings.units == cgSettings.unitsImperial) {
distance *= kmInMiles;
if (distance > 100) {
return String.format(Locale.getDefault(), "%.0f", Double.valueOf(Math.round(distance))) + " mi";
} else if (distance > 0.5) {
return String.format(Locale.getDefault(), "%.1f", Double.valueOf(Math.round(distance * 10.0) / 10.0)) + " mi";
} else if (distance > 0.1) {
return String.format(Locale.getDefault(), "%.2f", Double.valueOf(Math.round(distance * 100.0) / 100.0)) + " mi";
} else if (distance > 0.05) {
return String.format(Locale.getDefault(), "%.0f", Double.valueOf(Math.round(distance * 5280.0))) + " ft";
} else if (distance > 0.01) {
return String.format(Locale.getDefault(), "%.1f", Double.valueOf(Math.round(distance * 5280 * 10.0) / 10.0)) + " ft";
} else {
return String.format(Locale.getDefault(), "%.2f", Double.valueOf(Math.round(distance * 5280 * 100.0) / 100.0)) + " ft";
}
} else {
if (distance > 100) {
return String.format(Locale.getDefault(), "%.0f", Double.valueOf(Math.round(distance))) + " km";
} else if (distance > 10) {
return String.format(Locale.getDefault(), "%.1f", Double.valueOf(Math.round(distance * 10.0) / 10.0)) + " km";
} else if (distance > 1) {
return String.format(Locale.getDefault(), "%.2f", Double.valueOf(Math.round(distance * 100.0) / 100.0)) + " km";
} else if (distance > 0.1) {
return String.format(Locale.getDefault(), "%.0f", Double.valueOf(Math.round(distance * 1000.0))) + " m";
} else if (distance > 0.01) {
return String.format(Locale.getDefault(), "%.1f", Double.valueOf(Math.round(distance * 1000.0 * 10.0) / 10.0)) + " m";
} else {
return String.format(Locale.getDefault(), "%.2f", Double.valueOf(Math.round(distance * 1000.0 * 100.0) / 100.0)) + " m";
}
}
}
public String getHumanSpeed(float speed) {
double kph = speed * 3.6;
String unit = "km/h";
if (this.settings.units == cgSettings.unitsImperial) {
kph *= kmInMiles;
unit = "mph";
}
if (kph < 10.0) {
return String.format(Locale.getDefault(), "%.1f", Double.valueOf((Math.round(kph * 10.0) / 10.0))) + " " + unit;
} else {
return String.format(Locale.getDefault(), "%.0f", Double.valueOf(Math.round(kph))) + " " + unit;
}
}
public static HashMap<String, Object> parseLatlon(String latlon) {
final HashMap<String, Object> result = new HashMap<String, Object>();
final Pattern patternLatlon = Pattern.compile("([NS])[^\\d]*(\\d+)[^°]*° (\\d+)\\.(\\d+) ([WE])[^\\d]*(\\d+)[^°]*° (\\d+)\\.(\\d+)", Pattern.CASE_INSENSITIVE);
final Matcher matcherLatlon = patternLatlon.matcher(latlon);
while (matcherLatlon.find()) {
if (matcherLatlon.groupCount() > 0) {
result.put("latitudeString", (String) (matcherLatlon.group(1) + " " + matcherLatlon.group(2) + "° " + matcherLatlon.group(3) + "." + matcherLatlon.group(4)));
result.put("longitudeString", (String) (matcherLatlon.group(5) + " " + matcherLatlon.group(6) + "° " + matcherLatlon.group(7) + "." + matcherLatlon.group(8)));
int latNegative = -1;
int lonNegative = -1;
if (matcherLatlon.group(1).equalsIgnoreCase("N")) {
latNegative = 1;
}
if (matcherLatlon.group(5).equalsIgnoreCase("E")) {
lonNegative = 1;
}
result.put("latitude", Double.valueOf(latNegative * (Float.valueOf(matcherLatlon.group(2)) + Float.valueOf(matcherLatlon.group(3) + "." + matcherLatlon.group(4)) / 60)));
result.put("longitude", Double.valueOf(lonNegative * (Float.valueOf(matcherLatlon.group(6)) + Float.valueOf(matcherLatlon.group(7) + "." + matcherLatlon.group(8)) / 60)));
} else {
Log.w(cgSettings.tag, "cgBase.parseLatlon: Failed to parse coordinates.");
}
}
return result;
}
public static String formatCoordinate(Double coord, String latlon, boolean degrees) {
String formatted = "";
if (coord == null) {
return formatted;
}
String worldSide = "";
if (latlon.equalsIgnoreCase("lat")) {
if (coord >= 0) {
// have the blanks here at the direction to avoid one String concatenation
worldSide = "N ";
} else {
worldSide = "S ";
}
} else if (latlon.equalsIgnoreCase("lon")) {
if (coord >= 0) {
worldSide = "E ";
} else {
worldSide = "W ";
}
}
coord = Math.abs(coord);
if (latlon.equalsIgnoreCase("lat")) {
if (degrees) {
formatted = worldSide + String.format(Locale.getDefault(), "%02.0f", Math.floor(coord)) + "° " + String.format(Locale.getDefault(), "%06.3f", ((coord - Math.floor(coord)) * 60));
} else {
formatted = worldSide + String.format(Locale.getDefault(), "%02.0f", Math.floor(coord)) + " " + String.format(Locale.getDefault(), "%06.3f", ((coord - Math.floor(coord)) * 60));
}
} else {
if (degrees) {
formatted = worldSide + String.format(Locale.getDefault(), "%03.0f", Math.floor(coord)) + "° " + String.format(Locale.getDefault(), "%06.3f", ((coord - Math.floor(coord)) * 60));
} else {
formatted = worldSide + String.format(Locale.getDefault(), "%03.0f", Math.floor(coord)) + " " + String.format(Locale.getDefault(), "%06.3f", ((coord - Math.floor(coord)) * 60));
}
}
return formatted;
}
public static HashMap<String, Object> parseCoordinate(String coord, String latlon) {
final HashMap<String, Object> coords = new HashMap<String, Object>();
final Pattern patternA = Pattern.compile("^([NSWE])[^\\d]*(\\d+)°? +(\\d+)([\\.|,](\\d+))?$", Pattern.CASE_INSENSITIVE);
final Pattern patternB = Pattern.compile("^([NSWE])[^\\d]*(\\d+)([\\.|,](\\d+))?$", Pattern.CASE_INSENSITIVE);
final Pattern patternC = Pattern.compile("^(-?\\d+)([\\.|,](\\d+))?$", Pattern.CASE_INSENSITIVE);
final Pattern patternD = Pattern.compile("^([NSWE])[^\\d]*(\\d+)°?$", Pattern.CASE_INSENSITIVE);
final Pattern patternE = Pattern.compile("^(-?\\d+)°?$", Pattern.CASE_INSENSITIVE);
final Pattern patternF = Pattern.compile("^([NSWE])[^\\d]*(\\d+)$", Pattern.CASE_INSENSITIVE);
final Pattern pattern0 = Pattern.compile("^(-?\\d+)([\\.|,](\\d+))?$", Pattern.CASE_INSENSITIVE);
coord = coord.trim().toUpperCase();
final Matcher matcherA = patternA.matcher(coord);
final Matcher matcherB = patternB.matcher(coord);
final Matcher matcherC = patternC.matcher(coord);
final Matcher matcherD = patternD.matcher(coord);
final Matcher matcherE = patternE.matcher(coord);
final Matcher matcherF = patternF.matcher(coord);
final Matcher matcher0 = pattern0.matcher(coord);
int latlonNegative;
if (matcherA.find() && matcherA.groupCount() > 0) {
if (matcherA.group(1).equalsIgnoreCase("N") || matcherA.group(1).equalsIgnoreCase("E")) {
latlonNegative = 1;
} else {
latlonNegative = -1;
}
if (matcherA.groupCount() < 5 || matcherA.group(5) == null) {
coords.put("coordinate", Double.valueOf(latlonNegative * (Double.valueOf(matcherA.group(2)) + Double.valueOf(matcherA.group(3) + ".0") / 60)));
coords.put("string", matcherA.group(1) + " " + matcherA.group(2) + "° " + matcherA.group(3) + ".000");
} else {
coords.put("coordinate", Double.valueOf(latlonNegative * (Double.valueOf(matcherA.group(2)) + Double.valueOf(matcherA.group(3) + "." + matcherA.group(5)) / 60)));
coords.put("string", matcherA.group(1) + " " + matcherA.group(2) + "° " + matcherA.group(3) + "." + matcherA.group(5));
}
return coords;
} else if (matcherB.find() && matcherB.groupCount() > 0) {
if (matcherB.group(1).equalsIgnoreCase("N") || matcherB.group(1).equalsIgnoreCase("E")) {
latlonNegative = 1;
} else {
latlonNegative = -1;
}
if (matcherB.groupCount() < 4 || matcherB.group(4) == null) {
coords.put("coordinate", Double.valueOf(latlonNegative * (Double.valueOf(matcherB.group(2) + ".0"))));
} else {
coords.put("coordinate", Double.valueOf(latlonNegative * (Double.valueOf(matcherB.group(2) + "." + matcherB.group(4)))));
}
} else if (matcherC.find() && matcherC.groupCount() > 0) {
if (matcherC.groupCount() < 3 || matcherC.group(3) == null) {
coords.put("coordinate", Double.valueOf(new Float(matcherC.group(1) + ".0")));
} else {
coords.put("coordinate", Double.valueOf(new Float(matcherC.group(1) + "." + matcherC.group(3))));
}
} else if (matcherD.find() && matcherD.groupCount() > 0) {
if (matcherD.group(1).equalsIgnoreCase("N") || matcherD.group(1).equalsIgnoreCase("E")) {
latlonNegative = 1;
} else {
latlonNegative = -1;
}
coords.put("coordinate", Double.valueOf(latlonNegative * (Double.valueOf(matcherB.group(2)))));
} else if (matcherE.find() && matcherE.groupCount() > 0) {
coords.put("coordinate", Double.valueOf(matcherE.group(1)));
} else if (matcherF.find() && matcherF.groupCount() > 0) {
if (matcherF.group(1).equalsIgnoreCase("N") || matcherF.group(1).equalsIgnoreCase("E")) {
latlonNegative = 1;
} else {
latlonNegative = -1;
}
coords.put("coordinate", Double.valueOf(latlonNegative * (Double.valueOf(matcherB.group(2)))));
} else {
return null;
}
if (matcher0.find() && matcher0.groupCount() > 0) {
String tmpDir = null;
Float tmpCoord;
if (matcher0.groupCount() < 3 || matcher0.group(3) == null) {
tmpCoord = new Float("0.0");
} else {
tmpCoord = new Float("0." + matcher0.group(3));
}
if (latlon.equalsIgnoreCase("lat")) {
if (matcher0.group(1).equals("+")) {
tmpDir = "N";
}
if (matcher0.group(1).equals("-")) {
tmpDir = "S";
}
} else if (latlon.equalsIgnoreCase("lon")) {
if (matcher0.group(1).equals("+")) {
tmpDir = "E";
}
if (matcher0.group(1).equals("-")) {
tmpDir = "W";
}
}
coords.put("string", tmpDir + " " + matcher0.group(1) + "° " + (Math.round(tmpCoord / (1 / 60) * 1000) * 1000));
return coords;
} else {
return new HashMap<String, Object>();
}
}
public Long searchByNextPage(cgSearchThread thread, Long searchId, int reason, boolean showCaptcha) {
final String[] viewstates = app.getViewstates(searchId);
cgCacheWrap caches = new cgCacheWrap();
String url = app.getUrl(searchId);
if (url == null || url.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByNextPage: No url found");
return searchId;
}
if (isEmpty(viewstates)) {
Log.e(cgSettings.tag, "cgeoBase.searchByNextPage: No viewstate given");
return searchId;
}
String host = "www.geocaching.com";
String path = "/";
final String method = "POST";
int dash = -1;
if (url.indexOf("http://") > -1) {
url = url.substring(7);
}
dash = url.indexOf("/");
if (dash > -1) {
host = url.substring(0, dash);
url = url.substring(dash);
} else {
host = url;
url = "";
}
dash = url.indexOf("?");
if (dash > -1) {
path = url.substring(0, dash);
} else {
path = url;
}
final HashMap<String, String> params = new HashMap<String, String>();
setViewstates(viewstates, params);
params.put("__EVENTTARGET", "ctl00$ContentBody$pgrBottom$ctl08");
params.put("__EVENTARGUMENT", "");
String page = request(false, host, path, method, params, false, false, true).getData();
if (checkLogin(page) == false) {
int loginState = login();
if (loginState == 1) {
page = request(false, host, path, method, params, false, false, true).getData();
} else if (loginState == -3) {
Log.i(cgSettings.tag, "Working as guest.");
} else {
app.setError(searchId, errorRetrieve.get(loginState));
Log.e(cgSettings.tag, "cgeoBase.searchByNextPage: Can not log in geocaching");
return searchId;
}
}
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByNextPage: No data from server");
return searchId;
}
caches = parseSearch(thread, url, page, showCaptcha);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
Log.e(cgSettings.tag, "cgeoBase.searchByNextPage: No cache parsed");
return searchId;
}
// save to application
app.setError(searchId, caches.error);
app.setViewstates(searchId, caches.viewstates);
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
for (cgCache cache : caches.cacheList) {
app.addGeocode(searchId, cache.geocode);
cacheList.add(cache);
}
app.addSearch(searchId, cacheList, true, reason);
return searchId;
}
public Long searchByGeocode(HashMap<String, String> parameters, int reason, boolean forceReload) {
final cgSearch search = new cgSearch();
String geocode = parameters.get("geocode");
String guid = parameters.get("guid");
if ((geocode == null || geocode.length() == 0) && ((guid == null || guid.length() == 0))) {
Log.e(cgSettings.tag, "cgeoBase.searchByGeocode: No geocode nor guid given");
return null;
}
if (forceReload == false && reason == 0 && (app.isOffline(geocode, guid) || app.isThere(geocode, guid, true, true))) {
if ((geocode == null || geocode.length() == 0) && guid != null && guid.length() > 0) {
geocode = app.getGeocode(guid);
}
ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
cacheList.add(app.getCacheByGeocode(geocode, true, true, true, true, true, true));
search.addGeocode(geocode);
app.addSearch(search, cacheList, false, reason);
cacheList.clear();
cacheList = null;
return search.getCurrentId();
}
final String host = "www.geocaching.com";
final String path = "/seek/cache_details.aspx";
final String method = "GET";
final HashMap<String, String> params = new HashMap<String, String>();
if (geocode != null && geocode.length() > 0) {
params.put("wp", geocode);
} else if (guid != null && guid.length() > 0) {
params.put("guid", guid);
}
params.put("decrypt", "y");
params.put("log", "y"); // download logs (more than 5
params.put("numlogs", "35"); // 35 logs
String page = requestLogged(false, host, path, method, params, false, false, false);
if (page == null || page.length() == 0) {
if (app.isThere(geocode, guid, true, false)) {
if ((geocode == null || geocode.length() == 0) && guid != null && guid.length() > 0) {
Log.i(cgSettings.tag, "Loading old cache from cache.");
geocode = app.getGeocode(guid);
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
cacheList.add(app.getCacheByGeocode(geocode));
search.addGeocode(geocode);
search.error = null;
search.errorRetrieve = 0; // reset errors from previous failed request
app.addSearch(search, cacheList, false, reason);
cacheList.clear();
return search.getCurrentId();
}
Log.e(cgSettings.tag, "cgeoBase.searchByGeocode: No data from server");
return null;
}
final cgCacheWrap caches = parseCache(page, reason);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
if (caches != null && caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches != null && caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
app.addSearch(search, null, true, reason);
Log.e(cgSettings.tag, "cgeoBase.searchByGeocode: No cache parsed");
return null;
}
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByGeocode: No application found");
return null;
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
if (caches != null) {
if (caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
search.viewstates = caches.viewstates;
search.totalCnt = caches.totalCnt;
for (cgCache cache : caches.cacheList) {
search.addGeocode(cache.geocode);
cacheList.add(cache);
}
}
app.addSearch(search, cacheList, true, reason);
page = null;
cacheList.clear();
return search.getCurrentId();
}
public Long searchByOffline(HashMap<String, Object> parameters) {
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByOffline: No application found");
return null;
}
Double latitude = null;
Double longitude = null;
String cachetype = null;
Integer list = 1;
if (parameters.containsKey("latitude") && parameters.containsKey("longitude")) {
latitude = (Double) parameters.get("latitude");
longitude = (Double) parameters.get("longitude");
}
if (parameters.containsKey("cachetype")) {
cachetype = (String) parameters.get("cachetype");
}
if (parameters.containsKey("list")) {
list = (Integer) parameters.get("list");
}
final cgSearch search = app.getBatchOfStoredCaches(true, latitude, longitude, cachetype, list);
search.totalCnt = app.getAllStoredCachesCount(true, cachetype, list);
return search.getCurrentId();
}
public Long searchByHistory(HashMap<String, Object> parameters) {
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByHistory: No application found");
return null;
}
String cachetype = null;
if (parameters.containsKey("cachetype")) {
cachetype = (String) parameters.get("cachetype");
}
final cgSearch search = app.getHistoryOfCaches(true, cachetype);
search.totalCnt = app.getAllHistoricCachesCount(true, cachetype);
return search.getCurrentId();
}
public Long searchByCoords(cgSearchThread thread, HashMap<String, String> parameters, int reason, boolean showCaptcha) {
final cgSearch search = new cgSearch();
final String latitude = parameters.get("latitude");
final String longitude = parameters.get("longitude");
cgCacheWrap caches = new cgCacheWrap();
String cacheType = parameters.get("cachetype");
if (latitude == null || latitude.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No latitude given");
return null;
}
if (longitude == null || longitude.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No longitude given");
return null;
}
if (cacheType != null && cacheType.length() == 0) {
cacheType = null;
}
final String host = "www.geocaching.com";
final String path = "/seek/nearest.aspx";
final String method = "GET";
final HashMap<String, String> params = new HashMap<String, String>();
if (cacheType != null && cacheIDs.containsKey(cacheType)) {
params.put("tx", cacheIDs.get(cacheType));
} else {
params.put("tx", cacheIDs.get("all"));
}
params.put("lat", latitude);
params.put("lng", longitude);
final String url = "http://" + host + path + "?" + prepareParameters(params, false, true);
String page = requestLogged(false, host, path, method, params, false, false, true);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No data from server");
return null;
}
caches = parseSearch(thread, url, page, showCaptcha);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No cache parsed");
}
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No application found");
return null;
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
if (caches != null) {
if (caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
search.viewstates = caches.viewstates;
search.totalCnt = caches.totalCnt;
for (cgCache cache : caches.cacheList) {
if (settings.excludeDisabled == 0 || (settings.excludeDisabled == 1 && cache.disabled == false)) {
search.addGeocode(cache.geocode);
cacheList.add(cache);
}
}
}
app.addSearch(search, cacheList, true, reason);
return search.getCurrentId();
}
public Long searchByKeyword(cgSearchThread thread, HashMap<String, String> parameters, int reason, boolean showCaptcha) {
final cgSearch search = new cgSearch();
final String keyword = parameters.get("keyword");
cgCacheWrap caches = new cgCacheWrap();
String cacheType = parameters.get("cachetype");
if (keyword == null || keyword.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByKeyword: No keyword given");
return null;
}
if (cacheType != null && cacheType.length() == 0) {
cacheType = null;
}
final String host = "www.geocaching.com";
final String path = "/seek/nearest.aspx";
final String method = "GET";
final HashMap<String, String> params = new HashMap<String, String>();
if (cacheType != null && cacheIDs.containsKey(cacheType)) {
params.put("tx", cacheIDs.get(cacheType));
} else {
params.put("tx", cacheIDs.get("all"));
}
params.put("key", keyword);
final String url = "http://" + host + path + "?" + prepareParameters(params, false, true);
String page = requestLogged(false, host, path, method, params, false, false, true);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByKeyword: No data from server");
return null;
}
caches = parseSearch(thread, url, page, showCaptcha);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
Log.e(cgSettings.tag, "cgeoBase.searchByKeyword: No cache parsed");
}
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No application found");
return null;
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
if (caches != null) {
if (caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
search.viewstates = caches.viewstates;
search.totalCnt = caches.totalCnt;
for (cgCache cache : caches.cacheList) {
if (settings.excludeDisabled == 0 || (settings.excludeDisabled == 1 && cache.disabled == false)) {
search.addGeocode(cache.geocode);
cacheList.add(cache);
}
}
}
app.addSearch(search, cacheList, true, reason);
return search.getCurrentId();
}
public Long searchByUsername(cgSearchThread thread, HashMap<String, String> parameters, int reason, boolean showCaptcha) {
final cgSearch search = new cgSearch();
final String userName = parameters.get("username");
cgCacheWrap caches = new cgCacheWrap();
String cacheType = parameters.get("cachetype");
if (userName == null || userName.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByUsername: No user name given");
return null;
}
if (cacheType != null && cacheType.length() == 0) {
cacheType = null;
}
final String host = "www.geocaching.com";
final String path = "/seek/nearest.aspx";
final String method = "GET";
final HashMap<String, String> params = new HashMap<String, String>();
if (cacheType != null && cacheIDs.containsKey(cacheType)) {
params.put("tx", cacheIDs.get(cacheType));
} else {
params.put("tx", cacheIDs.get("all"));
}
params.put("ul", userName);
boolean my = false;
if (userName.equalsIgnoreCase(settings.getLogin().get("username"))) {
my = true;
Log.i(cgSettings.tag, "cgBase.searchByUsername: Overriding users choice, downloading all caches.");
}
final String url = "http://" + host + path + "?" + prepareParameters(params, my, true);
String page = requestLogged(false, host, path, method, params, false, my, true);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByUsername: No data from server");
return null;
}
caches = parseSearch(thread, url, page, showCaptcha);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
Log.e(cgSettings.tag, "cgeoBase.searchByUsername: No cache parsed");
}
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No application found");
return null;
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
if (caches != null) {
if (caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
search.viewstates = caches.viewstates;
search.totalCnt = caches.totalCnt;
for (cgCache cache : caches.cacheList) {
if (settings.excludeDisabled == 0 || (settings.excludeDisabled == 1 && cache.disabled == false)) {
search.addGeocode(cache.geocode);
cacheList.add(cache);
}
}
}
app.addSearch(search, cacheList, true, reason);
return search.getCurrentId();
}
public Long searchByOwner(cgSearchThread thread, HashMap<String, String> parameters, int reason, boolean showCaptcha) {
final cgSearch search = new cgSearch();
final String userName = parameters.get("username");
cgCacheWrap caches = new cgCacheWrap();
String cacheType = parameters.get("cachetype");
if (userName == null || userName.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByOwner: No user name given");
return null;
}
if (cacheType != null && cacheType.length() == 0) {
cacheType = null;
}
final String host = "www.geocaching.com";
final String path = "/seek/nearest.aspx";
final String method = "GET";
final HashMap<String, String> params = new HashMap<String, String>();
if (cacheType != null && cacheIDs.containsKey(cacheType)) {
params.put("tx", cacheIDs.get(cacheType));
} else {
params.put("tx", cacheIDs.get("all"));
}
params.put("u", userName);
final String url = "http://" + host + path + "?" + prepareParameters(params, false, true);
String page = requestLogged(false, host, path, method, params, false, false, true);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByOwner: No data from server");
return null;
}
caches = parseSearch(thread, url, page, showCaptcha);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
Log.e(cgSettings.tag, "cgeoBase.searchByOwner: No cache parsed");
}
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByCoords: No application found");
return null;
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
if (caches != null) {
if (caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
search.viewstates = caches.viewstates;
search.totalCnt = caches.totalCnt;
for (cgCache cache : caches.cacheList) {
if (settings.excludeDisabled == 0 || (settings.excludeDisabled == 1 && cache.disabled == false)) {
search.addGeocode(cache.geocode);
cacheList.add(cache);
}
}
}
app.addSearch(search, cacheList, true, reason);
return search.getCurrentId();
}
public Long searchByViewport(HashMap<String, String> parameters, int reason) {
final cgSearch search = new cgSearch();
final String latMin = parameters.get("latitude-min");
final String latMax = parameters.get("latitude-max");
final String lonMin = parameters.get("longitude-min");
final String lonMax = parameters.get("longitude-max");
String usertoken = null;
if (parameters.get("usertoken") != null) {
usertoken = parameters.get("usertoken");
} else {
usertoken = "";
}
cgCacheWrap caches = new cgCacheWrap();
String page = null;
if (latMin == null || latMin.length() == 0 || latMax == null || latMax.length() == 0 || lonMin == null || lonMin.length() == 0 || lonMax == null || lonMax.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByViewport: Not enough parameters to recognize viewport");
return null;
}
final String host = "www.geocaching.com";
final String path = "/map/default.aspx/MapAction";
String params = "{\"dto\":{\"data\":{\"c\":1,\"m\":\"\",\"d\":\"" + latMax + "|" + latMin + "|" + lonMax + "|" + lonMin + "\"},\"ut\":\"" + usertoken + "\"}}";
final String url = "http://" + host + path + "?" + params;
page = requestJSONgc(host, path, params);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchByViewport: No data from server");
return null;
}
caches = parseMapJSON(url, page);
if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) {
Log.e(cgSettings.tag, "cgeoBase.searchByViewport: No cache parsed");
}
if (app == null) {
Log.e(cgSettings.tag, "cgeoBase.searchByViewport: No application found");
return null;
}
final ArrayList<cgCache> cacheList = new ArrayList<cgCache>();
if (caches != null) {
if (caches.error != null && caches.error.length() > 0) {
search.error = caches.error;
}
if (caches.url != null && caches.url.length() > 0) {
search.url = caches.url;
}
search.viewstates = caches.viewstates;
search.totalCnt = caches.totalCnt;
if (caches.cacheList != null && caches.cacheList.size() > 0) {
for (cgCache cache : caches.cacheList) {
if ((settings.excludeDisabled == 0 || (settings.excludeDisabled == 1 && cache.disabled == false))
&& (settings.excludeMine == 0 || (settings.excludeMine == 1 && cache.own == false))
&& (settings.excludeMine == 0 || (settings.excludeMine == 1 && cache.found == false))
&& (settings.cacheType == null || (settings.cacheType.equals(cache.type)))) {
search.addGeocode(cache.geocode);
cacheList.add(cache);
}
}
}
}
app.addSearch(search, cacheList, true, reason);
return search.getCurrentId();
}
public ArrayList<cgUser> getGeocachersInViewport(String username, Double latMin, Double latMax, Double lonMin, Double lonMax) {
final ArrayList<cgUser> users = new ArrayList<cgUser>();
if (username == null) {
return users;
}
if (latMin == null || latMax == null || lonMin == null || lonMax == null) {
return users;
}
final String host = "api.go4cache.com";
final String path = "/get.php";
final String method = "POST";
final HashMap<String, String> params = new HashMap<String, String>();
params.put("u", username);
params.put("ltm", String.format((Locale) null, "%.6f", latMin));
params.put("ltx", String.format((Locale) null, "%.6f", latMax));
params.put("lnm", String.format((Locale) null, "%.6f", lonMin));
params.put("lnx", String.format((Locale) null, "%.6f", lonMax));
final String data = request(false, host, path, method, params, false, false, false).getData();
if (data == null || data.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.getGeocachersInViewport: No data from server");
return null;
}
try {
final JSONObject dataJSON = new JSONObject(data);
final JSONArray usersData = dataJSON.getJSONArray("users");
if (usersData != null && usersData.length() > 0) {
int count = usersData.length();
JSONObject oneUser = null;
for (int i = 0; i < count; i++) {
final cgUser user = new cgUser();
oneUser = usersData.getJSONObject(i);
if (oneUser != null) {
final String located = oneUser.getString("located");
if (located != null) {
user.located = dateSqlIn.parse(located);
} else {
user.located = new Date();
}
user.username = oneUser.getString("user");
user.latitude = oneUser.getDouble("latitude");
user.longitude = oneUser.getDouble("longitude");
user.action = oneUser.getString("action");
user.client = oneUser.getString("client");
if (user.latitude != null && user.longitude != null) {
users.add(user);
}
}
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.getGeocachersInViewport: " + e.toString());
}
return users;
}
public cgTrackable searchTrackable(HashMap<String, String> parameters) {
final String geocode = parameters.get("geocode");
final String guid = parameters.get("guid");
final String id = parameters.get("id");
cgTrackable trackable = new cgTrackable();
if ((geocode == null || geocode.length() == 0) && (guid == null || guid.length() == 0) && (id == null || id.length() == 0)) {
Log.e(cgSettings.tag, "cgeoBase.searchTrackable: No geocode nor guid nor id given");
return null;
}
final String host = "www.geocaching.com";
final String path = "/track/details.aspx";
final String method = "GET";
final HashMap<String, String> params = new HashMap<String, String>();
if (geocode != null && geocode.length() > 0) {
params.put("tracker", geocode);
} else if (guid != null && guid.length() > 0) {
params.put("guid", guid);
} else if (id != null && id.length() > 0) {
params.put("id", id);
}
String page = requestLogged(false, host, path, method, params, false, false, false);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.searchTrackable: No data from server");
return trackable;
}
trackable = parseTrackable(page);
if (trackable == null) {
Log.e(cgSettings.tag, "cgeoBase.searchTrackable: No trackable parsed");
return trackable;
}
return trackable;
}
public int postLog(cgeoapplication app, String geocode, String cacheid, String[] viewstates,
int logType, int year, int month, int day, String log, ArrayList<cgTrackableLog> trackables) {
if (isEmpty(viewstates)) {
Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate given");
return 1000;
}
if (logTypes2.containsKey(logType) == false) {
Log.e(cgSettings.tag, "cgeoBase.postLog: Unknown logtype");
return 1000;
}
if (log == null || log.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.postLog: No log text given");
return 1001;
}
// fix log (non-Latin characters converted to HTML entities)
final int logLen = log.length();
final StringBuilder logUpdated = new StringBuilder();
for (int i = 0; i < logLen; i++) {
char c = log.charAt(i);
if (c > 300) {
logUpdated.append("&#");
logUpdated.append(Integer.toString((int) c));
logUpdated.append(";");
} else {
logUpdated.append(c);
}
}
log = logUpdated.toString();
log = log.replace("\n", "\r\n"); // windows' eol
if (trackables != null) {
Log.i(cgSettings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + log + "; trackables: " + trackables.size());
} else {
Log.i(cgSettings.tag, "Trying to post log for cache #" + cacheid + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + log + "; trackables: 0");
}
final String host = "www.geocaching.com";
final String path = "/seek/log.aspx?ID=" + cacheid;
final String method = "POST";
final HashMap<String, String> params = new HashMap<String, String>();
setViewstates(viewstates, params);
params.put("__EVENTTARGET", "");
params.put("__EVENTARGUMENT", "");
params.put("__LASTFOCUS", "");
params.put("ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType));
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", String.format("%02d", month) + "/" + String.format("%02d", day) + "/" + String.format("%04d", year));
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month));
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day));
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year));
params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
params.put("ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry");
params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
if (trackables != null && trackables.isEmpty() == false) { // we have some trackables to proceed
final StringBuilder hdnSelected = new StringBuilder();
for (cgTrackableLog tb : trackables) {
final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);
if (tb.action > 0) {
hdnSelected.append(action);
hdnSelected.append(",");
}
}
params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables
params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
}
String page = request(false, host, path, method, params, false, false, false).getData();
if (checkLogin(page) == false) {
int loginState = login();
if (loginState == 1) {
page = request(false, host, path, method, params, false, false, false).getData();
} else {
Log.e(cgSettings.tag, "cgeoBase.postLog: Can not log in geocaching (error: " + loginState + ")");
return loginState;
}
}
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.postLog: No data from server");
return 1002;
}
// maintenance, archived needs to be confirmed
final Pattern pattern = Pattern.compile("<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>", Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(page);
try {
if (matcher.find() && matcher.groupCount() > 0) {
final String[] viewstatesConfirm = getViewstates(page);
if (isEmpty(viewstatesConfirm)) {
Log.e(cgSettings.tag, "cgeoBase.postLog: No viewstate for confirm log");
return 1000;
}
params.clear();
setViewstates(viewstatesConfirm, params);
params.put("__EVENTTARGET", "");
params.put("__EVENTARGUMENT", "");
params.put("__LASTFOCUS", "");
params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes");
params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
if (trackables != null && trackables.isEmpty() == false) { // we have some trackables to proceed
final StringBuilder hdnSelected = new StringBuilder();
for (cgTrackableLog tb : trackables) {
String ctl = null;
final String action = Integer.toString(tb.id) + logTypesTrackableAction.get(tb.action);
if (tb.ctl < 10) {
ctl = "0" + Integer.toString(tb.ctl);
} else {
ctl = Integer.toString(tb.ctl);
}
params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$repTravelBugs$ctl" + ctl + "$ddlAction", action);
if (tb.action > 0) {
hdnSelected.append(action);
hdnSelected.append(",");
}
}
params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnSelectedActions", hdnSelected.toString()); // selected trackables
params.put("ctl00$ContentBody$LogBookPanel1$uxTrackables$hdnCurrentFilter", "");
}
page = request(false, host, path, method, params, false, false, false).getData();
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.postLog.confim: " + e.toString());
}
try {
final Pattern patternOk = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Matcher matcherOk = patternOk.matcher(page);
if (matcherOk.find()) {
Log.i(cgSettings.tag, "Log successfully posted to cache #" + cacheid);
if (app != null && geocode != null) {
app.saveVisitDate(geocode);
}
return 1;
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.postLog.check: " + e.toString());
}
Log.e(cgSettings.tag, "cgeoBase.postLog: Failed to post log because of unknown error");
return 1000;
}
public int postLogTrackable(String tbid, String trackingCode, String[] viewstates,
int logType, int year, int month, int day, String log) {
if (isEmpty(viewstates)) {
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable: No viewstate given");
return 1000;
}
if (logTypes2.containsKey(logType) == false) {
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable: Unknown logtype");
return 1000;
}
if (log == null || log.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable: No log text given");
return 1001;
}
Log.i(cgSettings.tag, "Trying to post log for trackable #" + trackingCode + " - action: " + logType + "; date: " + year + "." + month + "." + day + ", log: " + log);
log = log.replace("\n", "\r\n"); // windows' eol
final Calendar currentDate = Calendar.getInstance();
final String host = "www.geocaching.com";
final String path = "/track/log.aspx?wid=" + tbid;
final String method = "POST";
final HashMap<String, String> params = new HashMap<String, String>();
setViewstates(viewstates, params);
params.put("__EVENTTARGET", "");
params.put("__EVENTARGUMENT", "");
params.put("__LASTFOCUS", "");
params.put("ctl00$ContentBody$LogBookPanel1$ddLogType", Integer.toString(logType));
params.put("ctl00$ContentBody$LogBookPanel1$tbCode", trackingCode);
if (currentDate.get(Calendar.YEAR) == year && (currentDate.get(Calendar.MONTH) + 1) == month && currentDate.get(Calendar.DATE) == day) {
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", "");
} else {
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged", Integer.toString(month) + "/" + Integer.toString(day) + "/" + Integer.toString(year));
}
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Day", Integer.toString(day));
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Month", Integer.toString(month));
params.put("ctl00$ContentBody$LogBookPanel1$DateTimeLogged$Year", Integer.toString(year));
params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", log);
params.put("ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry");
params.put("ctl00$ContentBody$uxVistOtherListingGC", "");
String page = request(false, host, path, method, params, false, false, false).getData();
if (checkLogin(page) == false) {
int loginState = login();
if (loginState == 1) {
page = request(false, host, path, method, params, false, false, false).getData();
} else {
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable: Can not log in geocaching (error: " + loginState + ")");
return loginState;
}
}
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable: No data from server");
return 1002;
}
try {
final Pattern patternOk = Pattern.compile("<div id=[\"|']ctl00_ContentBody_LogBookPanel1_ViewLogPanel[\"|']>", Pattern.CASE_INSENSITIVE);
final Matcher matcherOk = patternOk.matcher(page);
if (matcherOk.find()) {
Log.i(cgSettings.tag, "Log successfully posted to trackable #" + trackingCode);
return 1;
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable.check: " + e.toString());
}
Log.e(cgSettings.tag, "cgeoBase.postLogTrackable: Failed to post log because of unknown error");
return 1000;
}
/**
* Adds the cache to the watchlist of the user.
*
* @param cache the cache to add
* @return -1: error occured
*/
public int addToWatchlist(cgCache cache) {
String page = requestLogged(false, "www.geocaching.com", "/my/watchlist.aspx?w=" + cache.cacheid,
"POST", null, false, false, false);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgBase.addToWatchlist: No data from server");
return -1; // error
}
boolean guidOnPage = cache.isGuidContainedInPage(page);
if (guidOnPage) {
Log.i(cgSettings.tag, "cgBase.addToWatchlist: cache is on watchlist");
cache.onWatchlist = true;
} else {
Log.e(cgSettings.tag, "cgBase.addToWatchlist: cache is not on watchlist");
}
return guidOnPage ? 1 : -1; // on watchlist (=added) / else: error
}
/**
* Removes the cache from the watchlist
*
* @param cache the cache to remove
* @return -1: error occured
*/
public int removeFromWatchlist(cgCache cache) {
String host = "www.geocaching.com";
String path = "/my/watchlist.aspx?ds=1&action=rem&id=" + cache.cacheid;
String method = "POST";
String page = requestLogged(false, host, path, method, null, false, false, false);
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgBase.removeFromWatchlist: No data from server");
return -1; // error
}
// removing cache from list needs approval by hitting "Yes" button
final HashMap<String, String> params = new HashMap<String, String>();
transferViewstates(page, params);
params.put("__EVENTTARGET", "");
params.put("__EVENTARGUMENT", "");
params.put("ctl00$ContentBody$btnYes", "Yes");
page = request(false, host, path, method, params, false, false, false).getData();
boolean guidOnPage = cache.isGuidContainedInPage(page);
if (! guidOnPage) {
Log.i(cgSettings.tag, "cgBase.removeFromWatchlist: cache removed from watchlist");
cache.onWatchlist = false;
} else {
Log.e(cgSettings.tag, "cgBase.removeFromWatchlist: cache not removed from watchlist");
}
return guidOnPage ? -1 : 0; // on watchlist (=error) / not on watchlist
}
final public static HostnameVerifier doNotVerify = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
public static void trustAllHosts() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.trustAllHosts: " + e.toString());
}
}
public static void postTweetCache(cgeoapplication app, cgSettings settings, String geocode) {
final cgCache cache = app.getCacheByGeocode(geocode);
String name = cache.name;
if (name.length() > 84) {
name = name.substring(0, 81) + "...";
}
final String status = "I found " + name + " (http://coord.info/" + cache.geocode.toUpperCase() + ")! #cgeo #geocaching"; // 56 chars + cache name
postTweet(app, settings, status, null, null);
}
public static void postTweetTrackable(cgeoapplication app, cgSettings settings, String geocode) {
final cgTrackable trackable = app.getTrackableByGeocode(geocode);
String name = trackable.name;
if (name.length() > 82) {
name = name.substring(0, 79) + "...";
}
final String status = "I touched " + name + " (http://coord.info/" + trackable.geocode.toUpperCase() + ")! #cgeo #geocaching"; // 58 chars + trackable name
postTweet(app, settings, status, null, null);
}
public static void postTweet(cgeoapplication app, cgSettings settings, String status, Double latitude, Double longitude) {
if (app == null) {
return;
}
if (settings == null || settings.tokenPublic == null || settings.tokenPublic.length() == 0 || settings.tokenSecret == null || settings.tokenSecret.length() == 0) {
return;
}
try {
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("status", status);
if (latitude != null && longitude != null) {
parameters.put("lat", String.format("%.6f", latitude));
parameters.put("long", String.format("%.6f", longitude));
parameters.put("display_coordinates", "true");
}
final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false, parameters, settings.tokenPublic, settings.tokenSecret);
HttpURLConnection connection = null;
try {
final StringBuffer buffer = new StringBuffer();
final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
final URLConnection uc = u.openConnection();
uc.setRequestProperty("Host", "api.twitter.com");
connection = (HttpURLConnection) uc;
connection.setReadTimeout(30000);
connection.setRequestMethod("POST");
HttpURLConnection.setFollowRedirects(true);
connection.setDoInput(true);
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
final OutputStreamWriter wr = new OutputStreamWriter(out);
wr.write(paramsDone);
wr.flush();
wr.close();
Log.i(cgSettings.tag, "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());
InputStream ins;
final String encoding = connection.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
ins = new GZIPInputStream(connection.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
} else {
ins = connection.getInputStream();
}
final InputStreamReader inr = new InputStreamReader(ins);
final BufferedReader br = new BufferedReader(inr);
readIntoBuffer(br, buffer);
br.close();
ins.close();
inr.close();
connection.disconnect();
} catch (IOException e) {
Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": " + connection.getResponseMessage() + " ~ " + e.toString());
final InputStream ins = connection.getErrorStream();
final StringBuffer buffer = new StringBuffer();
final InputStreamReader inr = new InputStreamReader(ins);
final BufferedReader br = new BufferedReader(inr);
readIntoBuffer(br, buffer);
br.close();
ins.close();
inr.close();
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
}
connection.disconnect();
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
}
}
private static void readIntoBuffer(BufferedReader br, StringBuffer buffer) throws IOException {
int bufferSize = 1024*16;
char[] bytes = new char[bufferSize];
int bytesRead;
while ((bytesRead = br.read(bytes)) > 0) {
if (bytesRead == bufferSize) {
buffer.append(bytes);
}
else {
buffer.append(bytes, 0, bytesRead);
}
}
}
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// nothing
}
return null;
}
public static String implode(String delim, Object[] array) {
StringBuilder out = new StringBuilder();
try {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
out.append(delim);
}
out.append(array[i].toString());
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.implode: " + e.toString());
}
return out.toString();
}
public static String urlencode_rfc3986(String text) {
final String encoded = URLEncoder.encode(text).replace("+", "%20").replaceAll("%7E", "~");
return encoded;
}
public String prepareParameters(HashMap<String, String> params, boolean my, boolean addF) {
String paramsDone = null;
if (my != true && settings.excludeMine > 0) {
if (params == null) {
params = new HashMap<String, String>();
}
if (addF) {
params.put("f", "1");
}
Log.i(cgSettings.tag, "Skipping caches found or hidden by user.");
}
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
ArrayList<String> paramsEncoded = new ArrayList<String>();
for(Map.Entry<String, String> entry : entrySet)
{
String key = entry.getKey();
String value = entry.getValue();
if (key.charAt(0) == '^') {
key = "";
}
if (value == null) {
value = "";
}
paramsEncoded.add(key + "=" + urlencode_rfc3986(value));
}
paramsDone = implode("&", paramsEncoded.toArray());
} else {
paramsDone = "";
}
return paramsDone;
}
public String[] requestViewstates(boolean secure, String host, String path, String method, HashMap<String, String> params, boolean xContentType, boolean my) {
final cgResponse response = request(secure, host, path, method, params, xContentType, my, false);
return getViewstates(response.getData());
}
public String requestLogged(boolean secure, String host, String path, String method, HashMap<String, String> params, boolean xContentType, boolean my, boolean addF) {
cgResponse response = request(secure, host, path, method, params, xContentType, my, addF);
String data = response.getData();
if (checkLogin(data) == false) {
int loginState = login();
if (loginState == 1) {
response = request(secure, host, path, method, params, xContentType, my, addF);
data = response.getData();
} else {
Log.i(cgSettings.tag, "Working as guest.");
}
}
return data;
}
public cgResponse request(boolean secure, String host, String path, String method, HashMap<String, String> params, boolean xContentType, boolean my, boolean addF) {
// prepare parameters
final String paramsDone = prepareParameters(params, my, addF);
return request(secure, host, path, method, paramsDone, 0, xContentType);
}
public cgResponse request(boolean secure, String host, String path, String method, HashMap<String, String> params, int requestId, boolean xContentType, boolean my, boolean addF) {
// prepare parameters
final String paramsDone = prepareParameters(params, my, addF);
return request(secure, host, path, method, paramsDone, requestId, xContentType);
}
public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId, Boolean xContentType) {
URL u = null;
int httpCode = -1;
String httpMessage = null;
String httpLocation = null;
if (requestId == 0) {
requestId = (int) (Math.random() * 1000);
}
if (method == null || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
method = "POST";
} else {
method = method.toUpperCase();
}
// https
String scheme = "http://";
if (secure) {
scheme = "https://";
}
// prepare cookies
String cookiesDone = null;
if (cookies == null || cookies.isEmpty()) {
if (cookies == null) {
cookies = new HashMap<String, String>();
}
final Map<String, ?> prefsAll = prefs.getAll();
final Set<? extends Map.Entry<String, ?>> entrySet = prefsAll.entrySet();
for(Map.Entry<String, ?> entry : entrySet){
String key = entry.getKey();
if (key.matches("cookie_.+")) {
final String cookieKey = key.substring(7);
final String cookieValue = (String) entry.getValue();
cookies.put(cookieKey, cookieValue);
}
}
}
if (cookies != null) {
final Set<Map.Entry<String, String>> entrySet = cookies.entrySet();
final ArrayList<String> cookiesEncoded = new ArrayList<String>();
for(Map.Entry<String, String> entry : entrySet){
cookiesEncoded.add(entry.getKey() + "=" + entry.getValue());
}
if (cookiesEncoded.size() > 0) {
cookiesDone = implode("; ", cookiesEncoded.toArray());
}
}
if (cookiesDone == null) {
Map<String, ?> prefsValues = prefs.getAll();
if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
final Set<? extends Map.Entry<String, ?>> entrySet = prefsValues.entrySet();
final ArrayList<String> cookiesEncoded = new ArrayList<String>();
for(Map.Entry<String, ?> entry : entrySet){
String key = entry.getKey();
if (key.length() > 7 && key.substring(0, 7).equals("cookie_")) {
cookiesEncoded.add(key + "=" + entry.getValue());
}
}
if (cookiesEncoded.size() > 0) {
cookiesDone = implode("; ", cookiesEncoded.toArray());
}
}
}
if (cookiesDone == null) {
cookiesDone = "";
}
URLConnection uc = null;
HttpURLConnection connection = null;
Integer timeout = 30000;
StringBuffer buffer = null;
for (int i = 0; i < 5; i++) {
if (i > 0) {
Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
}
buffer = new StringBuffer();
timeout = 30000 + (i * 10000);
try {
if (method.equals("GET")) {
// GET
u = new URL(scheme + host + path + "?" + params);
uc = u.openConnection();
uc.setRequestProperty("Host", host);
uc.setRequestProperty("Cookie", cookiesDone);
if (xContentType) {
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
if (settings.asBrowser == 1) {
uc.setRequestProperty("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
// uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
uc.setRequestProperty("Accept-Language", "en-US");
uc.setRequestProperty("User-Agent", idBrowser);
uc.setRequestProperty("Connection", "keep-alive");
uc.setRequestProperty("Keep-Alive", "300");
}
connection = (HttpURLConnection) uc;
connection.setReadTimeout(timeout);
connection.setRequestMethod(method);
HttpURLConnection.setFollowRedirects(false);
connection.setDoInput(true);
connection.setDoOutput(false);
} else {
// POST
u = new URL(scheme + host + path);
uc = u.openConnection();
uc.setRequestProperty("Host", host);
uc.setRequestProperty("Cookie", cookiesDone);
if (xContentType) {
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
if (settings.asBrowser == 1) {
uc.setRequestProperty("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
// uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
uc.setRequestProperty("Accept-Language", "en-US");
uc.setRequestProperty("User-Agent", idBrowser);
uc.setRequestProperty("Connection", "keep-alive");
uc.setRequestProperty("Keep-Alive", "300");
}
connection = (HttpURLConnection) uc;
connection.setReadTimeout(timeout);
connection.setRequestMethod(method);
HttpURLConnection.setFollowRedirects(false);
connection.setDoInput(true);
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
final OutputStreamWriter wr = new OutputStreamWriter(out);
wr.write(params);
wr.flush();
wr.close();
}
String headerName = null;
final SharedPreferences.Editor prefsEditor = prefs.edit();
for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
int index;
String cookie = uc.getHeaderField(j);
index = cookie.indexOf(";");
if (index > -1) {
cookie = cookie.substring(0, cookie.indexOf(";"));
}
index = cookie.indexOf("=");
if (index > - 1 && cookie.length() > (index + 1)) {
String name = cookie.substring(0, cookie.indexOf("="));
String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookies.put(name, value);
prefsEditor.putString("cookie_" + name, value);
}
}
}
prefsEditor.commit();
final String encoding = connection.getContentEncoding();
InputStream ins;
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
ins = new GZIPInputStream(connection.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
} else {
ins = connection.getInputStream();
}
final InputStreamReader inr = new InputStreamReader(ins);
final BufferedReader br = new BufferedReader(inr, 16 * 1024);
readIntoBuffer(br, buffer);
httpCode = connection.getResponseCode();
httpMessage = connection.getResponseMessage();
httpLocation = uc.getHeaderField("Location");
final String paramsLog = params.replaceAll(passMatch, "password=***");
if (buffer != null && connection != null) {
Log.i(cgSettings.tag + "|" + requestId, "[" + method + " " + (int)(params.length() / 1024) + "k | " + httpCode + " | " + (int)(buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?" + paramsLog);
} else {
Log.i(cgSettings.tag + "|" + requestId, "[" + method + " | " + httpCode + "] Failed to download " + scheme + host + path + "?" + paramsLog);
}
connection.disconnect();
br.close();
ins.close();
inr.close();
} catch (IOException e) {
Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
}
if (buffer != null && buffer.length() > 0) {
break;
}
}
cgResponse response = new cgResponse();
try {
if (httpCode == 302 && httpLocation != null) {
final Uri newLocation = Uri.parse(httpLocation);
if (newLocation.isRelative()) {
response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false, false, false);
} else {
boolean secureRedir = false;
if (newLocation.getScheme().equals("https")) {
secureRedir = true;
}
response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET", new HashMap<String, String>(), requestId, false, false, false);
}
} else {
if (buffer != null && buffer.length() > 0) {
replaceWhitespace(buffer);
String data = buffer.toString();
buffer = null;
if (data != null) {
response.setData(data);
} else {
response.setData("");
}
response.setStatusCode(httpCode);
response.setStatusMessage(httpMessage);
response.setUrl(u.toString());
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
}
return response;
}
private static void replaceWhitespace(final StringBuffer buffer) {
final int length = buffer.length();
final char[] chars = new char[length];
buffer.getChars(0, length, chars, 0);
int resultSize = 0;
boolean lastWasWhitespace = false;
for (int i = 0; i < length; i++) {
char c = chars[i];
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
if (!lastWasWhitespace) {
chars[resultSize++] =' ';
}
lastWasWhitespace = true;
} else {
chars[resultSize++] = c;
lastWasWhitespace = false;
}
}
buffer.setLength(0);
buffer.append(chars);
}
public String requestJSONgc(String host, String path, String params) {
int httpCode = -1;
String httpLocation = null;
// prepare cookies
String cookiesDone = null;
if (cookies == null || cookies.isEmpty()) {
if (cookies == null) {
cookies = new HashMap<String, String>();
}
final Map<String, ?> prefsAll = prefs.getAll();
final Set<? extends Map.Entry<String, ?>> entrySet = prefsAll.entrySet();
for(Map.Entry<String, ?> entry : entrySet){
String key = entry.getKey();
if (key.matches("cookie_.+")) {
final String cookieKey = key.substring(7);
final String cookieValue = (String) entry.getValue();
cookies.put(cookieKey, cookieValue);
}
}
}
if (cookies != null) {
final Set<Map.Entry<String, String>> entrySet = cookies.entrySet();
final ArrayList<String> cookiesEncoded = new ArrayList<String>();
for(Map.Entry<String, String> entry : entrySet){
cookiesEncoded.add(entry.getKey() + "=" + entry.getValue());
}
if (cookiesEncoded.size() > 0) {
cookiesDone = implode("; ", cookiesEncoded.toArray());
}
}
if (cookiesDone == null) {
Map<String, ?> prefsValues = prefs.getAll();
if (prefsValues != null && prefsValues.size() > 0) {
final Set<? extends Map.Entry<String, ?>> entrySet = prefsValues.entrySet();
final ArrayList<String> cookiesEncoded = new ArrayList<String>();
for(Map.Entry<String, ?> entry : entrySet){
String key = entry.getKey();
if (key.length() > 7 && key.substring(0, 7).equals("cookie_")) {
cookiesEncoded.add(key + "=" + entry.getValue());
}
}
if (cookiesEncoded.size() > 0) {
cookiesDone = implode("; ", cookiesEncoded.toArray());
}
}
}
if (cookiesDone == null) {
cookiesDone = "";
}
URLConnection uc = null;
HttpURLConnection connection = null;
Integer timeout = 30000;
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 3; i++) {
if (i > 0) {
Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
}
buffer.delete(0, buffer.length());
timeout = 30000 + (i * 15000);
try {
// POST
final URL u = new URL("http://" + host + path);
uc = u.openConnection();
uc.setRequestProperty("Host", host);
uc.setRequestProperty("Cookie", cookiesDone);
uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
uc.setRequestProperty("Referer", host + "/" + path);
if (settings.asBrowser == 1) {
uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
uc.setRequestProperty("Accept-Language", "en-US");
uc.setRequestProperty("User-Agent", idBrowser);
uc.setRequestProperty("Connection", "keep-alive");
uc.setRequestProperty("Keep-Alive", "300");
}
connection = (HttpURLConnection) uc;
connection.setReadTimeout(timeout);
connection.setRequestMethod("POST");
HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
connection.setDoInput(true);
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
final OutputStreamWriter wr = new OutputStreamWriter(out);
wr.write(params);
wr.flush();
wr.close();
String headerName = null;
final SharedPreferences.Editor prefsEditor = prefs.edit();
for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
int index;
String cookie = uc.getHeaderField(j);
index = cookie.indexOf(";");
if (index > -1) {
cookie = cookie.substring(0, cookie.indexOf(";"));
}
index = cookie.indexOf("=");
if (index > - 1 && cookie.length() > (index + 1)) {
String name = cookie.substring(0, cookie.indexOf("="));
String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookies.put(name, value);
prefsEditor.putString("cookie_" + name, value);
}
}
}
prefsEditor.commit();
final String encoding = connection.getContentEncoding();
InputStream ins;
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
ins = new GZIPInputStream(connection.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
} else {
ins = connection.getInputStream();
}
final InputStreamReader inr = new InputStreamReader(ins);
final BufferedReader br = new BufferedReader(inr);
readIntoBuffer(br, buffer);
httpCode = connection.getResponseCode();
httpLocation = uc.getHeaderField("Location");
final String paramsLog = params.replaceAll(passMatch, "password=***");
Log.i(cgSettings.tag + " | JSON", "[POST " + (int)(params.length() / 1024) + "k | " + httpCode + " | " + (int)(buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?" + paramsLog);
connection.disconnect();
br.close();
ins.close();
inr.close();
} catch (IOException e) {
Log.e(cgSettings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.requestJSONgc: " + e.toString());
}
if (buffer != null && buffer.length() > 0) {
break;
}
}
String page = null;
if (httpCode == 302 && httpLocation != null) {
final Uri newLocation = Uri.parse(httpLocation);
if (newLocation.isRelative()) {
page = requestJSONgc(host, path, params);
} else {
page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
}
} else {
replaceWhitespace(buffer);
page = buffer.toString();
}
if (page != null) {
return page;
} else {
return "";
}
}
public static String requestJSON(String host, String path, String params) {
return requestJSON("http://", host, path, "GET", params);
}
public static String requestJSON(String scheme, String host, String path, String method, String params) {
int httpCode = -1;
//String httpLocation = null;
if (method == null) {
method = "GET";
} else {
method = method.toUpperCase();
}
boolean methodPost = false;
if (method.equalsIgnoreCase("POST")) {
methodPost = true;
}
URLConnection uc = null;
HttpURLConnection connection = null;
Integer timeout = 30000;
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 3; i++) {
if (i > 0) {
Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
}
buffer.delete(0, buffer.length());
timeout = 30000 + (i * 15000);
try {
try {
URL u = null;
if (methodPost) {
u = new URL(scheme + host + path);
} else {
u = new URL(scheme + host + path + "?" + params);
}
if (u.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
https.setHostnameVerifier(doNotVerify);
uc = https;
} else {
uc = (HttpURLConnection) u.openConnection();
}
uc.setRequestProperty("Host", host);
uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
if (methodPost) {
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
uc.setRequestProperty("X-HTTP-Method-Override", "GET");
} else {
uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
}
uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
connection = (HttpURLConnection) uc;
connection.setReadTimeout(timeout);
connection.setRequestMethod(method);
HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
connection.setDoInput(true);
if (methodPost) {
connection.setDoOutput(true);
final OutputStream out = connection.getOutputStream();
final OutputStreamWriter wr = new OutputStreamWriter(out);
wr.write(params);
wr.flush();
wr.close();
} else {
connection.setDoOutput(false);
}
final String encoding = connection.getContentEncoding();
InputStream ins;
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
ins = new GZIPInputStream(connection.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
} else {
ins = connection.getInputStream();
}
final InputStreamReader inr = new InputStreamReader(ins);
final BufferedReader br = new BufferedReader(inr, 1024);
readIntoBuffer(br, buffer);
httpCode = connection.getResponseCode();
final String paramsLog = params.replaceAll(passMatch, "password=***");
Log.i(cgSettings.tag + " | JSON", "[POST " + (int)(params.length() / 1024) + "k | " + httpCode + " | " + (int)(buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?" + paramsLog);
connection.disconnect();
br.close();
ins.close();
inr.close();
} catch (IOException e) {
httpCode = connection.getResponseCode();
Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": " + connection.getResponseMessage() + " ~ " + e.toString());
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
}
if (buffer != null && buffer.length() > 0) {
break;
}
if (httpCode == 403) {
// we're not allowed to download content, so let's move
break;
}
}
String page = null;
//This is reported as beeing deadCode (httpLocation is always null)
//2011-08-09 - 302 is redirect so something should probably be done
/*if (httpCode == 302 && httpLocation != null) {
final Uri newLocation = Uri.parse(httpLocation);
if (newLocation.isRelative()) {
page = requestJSONgc(host, path, params);
} else {
page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
}
} else {*/
replaceWhitespace(buffer);
page = buffer.toString();
//}
if (page != null) {
return page;
} else {
return "";
}
}
public static String rot13(String text) {
final StringBuilder result = new StringBuilder();
// plaintext flag (do not convert)
boolean plaintext = false;
int length = text.length();
for (int index = 0; index < length; index++) {
int c = text.charAt(index);
if (c == '[') {
plaintext = true;
} else if (c == ']') {
plaintext = false;
} else if (!plaintext) {
int capitalized = c & 32;
c &= ~capitalized;
c = ((c >= 'A') && (c <= 'Z') ? ((c - 'A' + 13) % 26 + 'A') : c)
| capitalized;
}
result.append((char) c);
}
return result.toString();
}
public static String md5(String text) {
String hashed = "";
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(text.getBytes(), 0, text.length());
hashed = new BigInteger(1, digest.digest()).toString(16);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.md5: " + e.toString());
}
return hashed;
}
public static String sha1(String text) {
String hashed = "";
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(text.getBytes(), 0, text.length());
hashed = new BigInteger(1, digest.digest()).toString(16);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.sha1: " + e.toString());
}
return hashed;
}
public static byte[] hashHmac(String text, String salt) {
byte[] macBytes = {};
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(salt.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKeySpec);
macBytes = mac.doFinal(text.getBytes());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.hashHmac: " + e.toString());
}
return macBytes;
}
public static boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
public void storeCache(cgeoapplication app, Activity activity, cgCache cache, String geocode, int listId, Handler handler) {
try {
// cache details
if (cache != null) {
final HashMap<String, String> params = new HashMap<String, String>();
params.put("geocode", cache.geocode);
final Long searchId = searchByGeocode(params, listId, false);
cache = app.getCache(searchId);
} else if (geocode != null) {
final HashMap<String, String> params = new HashMap<String, String>();
params.put("geocode", geocode);
final Long searchId = searchByGeocode(params, listId, false);
cache = app.getCache(searchId);
}
if (cache == null) {
if (handler != null) {
handler.sendMessage(new Message());
}
return;
}
final cgHtmlImg imgGetter = new cgHtmlImg(activity, cache.geocode, false, listId, true);
// store images from description
if (cache.description != null) {
Html.fromHtml(cache.description, imgGetter, null);
}
// store spoilers
if (cache.spoilers != null && cache.spoilers.isEmpty() == false) {
for (cgImage oneSpoiler : cache.spoilers) {
imgGetter.getDrawable(oneSpoiler.url);
}
}
// store images from logs
if (settings.storelogimages) {
for (cgLog log : cache.logs) {
if (log.logImages != null && log.logImages.isEmpty() == false) {
for (cgImage oneLogImg : log.logImages) {
imgGetter.getDrawable(oneLogImg.url);
}
}
}
}
// store map previews
StaticMapsProvider.downloadMaps(cache, settings, activity);
app.markStored(cache.geocode, listId);
app.removeCacheFromCache(cache.geocode);
if (handler != null) {
handler.sendMessage(new Message());
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.storeCache: " + e.toString());
}
}
public static void dropCache(cgeoapplication app, Activity activity, cgCache cache, Handler handler) {
try {
app.markDropped(cache.geocode);
app.removeCacheFromCache(cache.geocode);
handler.sendMessage(new Message());
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.dropCache: " + e.toString());
}
}
public static boolean isInViewPort(int centerLat1, int centerLon1, int centerLat2, int centerLon2, int spanLat1, int spanLon1, int spanLat2, int spanLon2) {
try {
// expects coordinates in E6 format
final int left1 = centerLat1 - (spanLat1 / 2);
final int right1 = centerLat1 + (spanLat1 / 2);
final int top1 = centerLon1 + (spanLon1 / 2);
final int bottom1 = centerLon1 - (spanLon1 / 2);
final int left2 = centerLat2 - (spanLat2 / 2);
final int right2 = centerLat2 + (spanLat2 / 2);
final int top2 = centerLon2 + (spanLon2 / 2);
final int bottom2 = centerLon2 - (spanLon2 / 2);
if (left2 <= left1) {
return false;
}
if (right2 >= right1) {
return false;
}
if (top2 >= top1) {
return false;
}
if (bottom2 <= bottom1) {
return false;
}
return true;
} catch (Exception e) {
Log.e(cgSettings.tag, "cgBase.isInViewPort: " + e.toString());
return false;
}
}
public static boolean isCacheInViewPort(int centerLat, int centerLon, int spanLat, int spanLon, Double cacheLat, Double cacheLon) {
if (cacheLat == null || cacheLon == null) {
return false;
}
// viewport is defined by center, span and some (10%) reserve on every side
int minLat = centerLat - (spanLat / 2) - (spanLat / 10);
int maxLat = centerLat + (spanLat / 2) + (spanLat / 10);
int minLon = centerLon - (spanLon / 2) - (spanLon / 10);
int maxLon = centerLon + (spanLon / 2) + (spanLon / 10);
int cLat = (int) Math.round(cacheLat * 1e6);
int cLon = (int) Math.round(cacheLon * 1e6);
int mid = 0;
if (maxLat < minLat) {
mid = minLat;
minLat = maxLat;
maxLat = mid;
}
if (maxLon < minLon) {
mid = minLon;
minLon = maxLon;
maxLon = mid;
}
boolean latOk = false;
boolean lonOk = false;
if (cLat >= minLat && cLat <= maxLat) {
latOk = true;
}
if (cLon >= minLon && cLon <= maxLon) {
lonOk = true;
}
if (latOk && lonOk) {
return true;
} else {
return false;
}
}
private static char[] base64map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++) {
base64map1[i++] = c;
}
for (char c = 'a'; c <= 'z'; c++) {
base64map1[i++] = c;
}
for (char c = '0'; c <= '9'; c++) {
base64map1[i++] = c;
}
base64map1[i++] = '+';
base64map1[i++] = '/';
}
private static byte[] base64map2 = new byte[128];
static {
for (int i = 0; i < base64map2.length; i++) {
base64map2[i] = -1;
}
for (int i = 0; i < 64; i++) {
base64map2[base64map1[i]] = (byte) i;
}
}
public static String base64Encode(byte[] in) {
int iLen = in.length;
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = base64map1[o0];
out[op++] = base64map1[o1];
out[op] = op < oDataLen ? base64map1[o2] : '=';
op++;
out[op] = op < oDataLen ? base64map1[o3] : '=';
op++;
}
return new String(out);
}
public static byte[] base64Decode(String text) {
char[] in = text.toCharArray();
int iLen = in.length;
if (iLen % 4 != 0) {
throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4.");
}
while (iLen > 0 && in[iLen - 1] == '=') {
iLen--;
}
int oLen = (iLen * 3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) {
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
}
int b0 = base64map2[i0];
int b1 = base64map2[i1];
int b2 = base64map2[i2];
int b3 = base64map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) {
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
}
int o0 = (b0 << 2) | (b1 >>> 4);
int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
int o2 = ((b2 & 3) << 6) | b3;
out[op++] = (byte) o0;
if (op < oLen) {
out[op++] = (byte) o1;
}
if (op < oLen) {
out[op++] = (byte) o2;
}
}
return out;
}
public static int getIcon(boolean cache, String type, boolean own, boolean found, boolean disabled) {
if (gcIcons.isEmpty()) {
// default markers
gcIcons.put("ape", R.drawable.marker_cache_ape);
gcIcons.put("cito", R.drawable.marker_cache_cito);
gcIcons.put("earth", R.drawable.marker_cache_earth);
gcIcons.put("event", R.drawable.marker_cache_event);
gcIcons.put("letterbox", R.drawable.marker_cache_letterbox);
gcIcons.put("locationless", R.drawable.marker_cache_locationless);
gcIcons.put("mega", R.drawable.marker_cache_mega);
gcIcons.put("multi", R.drawable.marker_cache_multi);
gcIcons.put("traditional", R.drawable.marker_cache_traditional);
gcIcons.put("virtual", R.drawable.marker_cache_virtual);
gcIcons.put("webcam", R.drawable.marker_cache_webcam);
gcIcons.put("wherigo", R.drawable.marker_cache_wherigo);
gcIcons.put("mystery", R.drawable.marker_cache_mystery);
gcIcons.put("gchq", R.drawable.marker_cache_gchq);
// own cache markers
gcIcons.put("ape-own", R.drawable.marker_cache_ape_own);
gcIcons.put("cito-own", R.drawable.marker_cache_cito_own);
gcIcons.put("earth-own", R.drawable.marker_cache_earth_own);
gcIcons.put("event-own", R.drawable.marker_cache_event_own);
gcIcons.put("letterbox-own", R.drawable.marker_cache_letterbox_own);
gcIcons.put("locationless-own", R.drawable.marker_cache_locationless_own);
gcIcons.put("mega-own", R.drawable.marker_cache_mega_own);
gcIcons.put("multi-own", R.drawable.marker_cache_multi_own);
gcIcons.put("traditional-own", R.drawable.marker_cache_traditional_own);
gcIcons.put("virtual-own", R.drawable.marker_cache_virtual_own);
gcIcons.put("webcam-own", R.drawable.marker_cache_webcam_own);
gcIcons.put("wherigo-own", R.drawable.marker_cache_wherigo_own);
gcIcons.put("mystery-own", R.drawable.marker_cache_mystery_own);
gcIcons.put("gchq-own", R.drawable.marker_cache_gchq_own);
// found cache markers
gcIcons.put("ape-found", R.drawable.marker_cache_ape_found);
gcIcons.put("cito-found", R.drawable.marker_cache_cito_found);
gcIcons.put("earth-found", R.drawable.marker_cache_earth_found);
gcIcons.put("event-found", R.drawable.marker_cache_event_found);
gcIcons.put("letterbox-found", R.drawable.marker_cache_letterbox_found);
gcIcons.put("locationless-found", R.drawable.marker_cache_locationless_found);
gcIcons.put("mega-found", R.drawable.marker_cache_mega_found);
gcIcons.put("multi-found", R.drawable.marker_cache_multi_found);
gcIcons.put("traditional-found", R.drawable.marker_cache_traditional_found);
gcIcons.put("virtual-found", R.drawable.marker_cache_virtual_found);
gcIcons.put("webcam-found", R.drawable.marker_cache_webcam_found);
gcIcons.put("wherigo-found", R.drawable.marker_cache_wherigo_found);
gcIcons.put("mystery-found", R.drawable.marker_cache_mystery_found);
gcIcons.put("gchq-found", R.drawable.marker_cache_gchq_found);
// disabled cache markers
gcIcons.put("ape-disabled", R.drawable.marker_cache_ape_disabled);
gcIcons.put("cito-disabled", R.drawable.marker_cache_cito_disabled);
gcIcons.put("earth-disabled", R.drawable.marker_cache_earth_disabled);
gcIcons.put("event-disabled", R.drawable.marker_cache_event_disabled);
gcIcons.put("letterbox-disabled", R.drawable.marker_cache_letterbox_disabled);
gcIcons.put("locationless-disabled", R.drawable.marker_cache_locationless_disabled);
gcIcons.put("mega-disabled", R.drawable.marker_cache_mega_disabled);
gcIcons.put("multi-disabled", R.drawable.marker_cache_multi_disabled);
gcIcons.put("traditional-disabled", R.drawable.marker_cache_traditional_disabled);
gcIcons.put("virtual-disabled", R.drawable.marker_cache_virtual_disabled);
gcIcons.put("webcam-disabled", R.drawable.marker_cache_webcam_disabled);
gcIcons.put("wherigo-disabled", R.drawable.marker_cache_wherigo_disabled);
gcIcons.put("mystery-disabled", R.drawable.marker_cache_mystery_disabled);
gcIcons.put("gchq-disabled", R.drawable.marker_cache_gchq_disabled);
}
if (wpIcons.isEmpty()) {
wpIcons.put("waypoint", R.drawable.marker_waypoint_waypoint);
wpIcons.put("flag", R.drawable.marker_waypoint_flag);
wpIcons.put("pkg", R.drawable.marker_waypoint_pkg);
wpIcons.put("puzzle", R.drawable.marker_waypoint_puzzle);
wpIcons.put("stage", R.drawable.marker_waypoint_stage);
wpIcons.put("trailhead", R.drawable.marker_waypoint_trailhead);
}
int icon = -1;
String iconTxt = null;
if (cache) {
if (type != null && type.length() > 0) {
if (own) {
iconTxt = type + "-own";
} else if (found) {
iconTxt = type + "-found";
} else if (disabled) {
iconTxt = type + "-disabled";
} else {
iconTxt = type;
}
} else {
iconTxt = "traditional";
}
if (gcIcons.containsKey(iconTxt)) {
icon = gcIcons.get(iconTxt);
} else {
icon = gcIcons.get("traditional");
}
} else {
if (type != null && type.length() > 0) {
iconTxt = type;
} else {
iconTxt = "waypoint";
}
if (wpIcons.containsKey(iconTxt)) {
icon = wpIcons.get(iconTxt);
} else {
icon = wpIcons.get("waypoint");
}
}
return icon;
}
public static boolean runNavigation(Activity activity, Resources res, cgSettings settings, Double latitude, Double longitude) {
return runNavigation(activity, res, settings, latitude, longitude, null, null);
}
public static boolean runNavigation(Activity activity, Resources res, cgSettings settings, Double latitude, Double longitude, Double latitudeNow, Double longitudeNow) {
if (activity == null) {
return false;
}
if (settings == null) {
return false;
}
// Google Navigation
if (settings.useGNavigation == 1) {
try {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:ll=" + latitude + "," + longitude)));
return true;
} catch (Exception e) {
// nothing
}
}
// Google Maps Directions
try {
if (latitudeNow != null && longitudeNow != null) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=" + latitudeNow + "," + longitudeNow + "&daddr=" + latitude + "," + longitude)));
} else {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&daddr=" + latitude + "," + longitude)));
}
return true;
} catch (Exception e) {
// nothing
}
Log.i(cgSettings.tag, "cgBase.runNavigation: No navigation application available.");
if (res != null) {
ActivityMixin.showToast(activity, res.getString(R.string.err_navigation_no));
}
return false;
}
public String getMapUserToken(Handler noTokenHandler) {
final cgResponse response = request(false, "www.geocaching.com", "/map/default.aspx", "GET", "", 0, false);
final String data = response.getData();
String usertoken = null;
if (data != null && data.length() > 0) {
final Pattern pattern = Pattern.compile("var userToken[^=]*=[^']*'([^']+)';", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
if (matcher.groupCount() > 0) {
usertoken = matcher.group(1);
}
}
}
if (noTokenHandler != null && (usertoken == null || usertoken.length() == 0)) {
noTokenHandler.sendEmptyMessage(0);
}
return usertoken;
}
public static Double getElevation(Double latitude, Double longitude) {
Double elv = null;
try {
final String host = "maps.googleapis.com";
final String path = "/maps/api/elevation/json";
final String params = "sensor=false&locations=" + String.format((Locale) null, "%.6f", latitude) + "," + String.format((Locale) null, "%.6f", longitude);
final String data = requestJSON(host, path, params);
if (data == null || data.length() == 0) {
return elv;
}
JSONObject response = new JSONObject(data);
String status = response.getString("status");
if (status == null || status.equalsIgnoreCase("OK") == false) {
return elv;
}
if (response.has("results")) {
JSONArray results = response.getJSONArray("results");
JSONObject result = results.getJSONObject(0);
elv = result.getDouble("elevation");
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgBase.getElevation: " + e.toString());
}
return elv;
}
/**
* Generate a time string according to system-wide settings (locale, 12/24 hour)
* such as "13:24".
*
* @param context a context
* @param date milliseconds since the epoch
* @return the formatted string
*/
public String formatTime(long date) {
return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_TIME);
}
/**
* Generate a date string according to system-wide settings (locale, date format)
* such as "20 December" or "20 December 2010". The year will only be included when necessary.
*
* @param context a context
* @param date milliseconds since the epoch
* @return the formatted string
*/
public String formatDate(long date) {
return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE);
}
/**
* Generate a date string according to system-wide settings (locale, date format)
* such as "20 December 2010". The year will always be included, making it suitable
* to generate long-lived log entries.
*
* @param context a context
* @param date milliseconds since the epoch
* @return the formatted string
*/
public String formatFullDate(long date) {
return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR);
}
/**
* Generate a numeric date string according to system-wide settings (locale, date format)
* such as "10/20/2010".
*
* @param context a context
* @param date milliseconds since the epoch
* @return the formatted string
*/
public String formatShortDate(long date) {
return DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE);
}
/**
* TODO This method is only needed until the settings are a singleton
* @return
*/
public String getUserName() {
return settings.getUsername();
}
/**
* insert text into the EditText at the current cursor position
* @param editText
* @param insertText
* @param addSpace add a space character, if there is no whitespace before the current cursor position
*/
static void insertAtPosition(final EditText editText, String insertText, final boolean addSpace) {
int selectionStart = editText.getSelectionStart();
int selectionEnd = editText.getSelectionEnd();
int start = Math.min(selectionStart, selectionEnd);
int end = Math.max(selectionStart, selectionEnd);
String content = editText.getText().toString();
if (start > 0 && !Character.isWhitespace(content.charAt(start - 1))) {
insertText = " " + insertText;
}
editText.getText().replace(start, end, insertText);
int newCursor = start + insertText.length();
editText.setSelection(newCursor, newCursor);
}
}
| true | true | public cgCacheWrap parseCache(String page, int reason) {
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: No page given");
return null;
}
final cgCacheWrap caches = new cgCacheWrap();
final cgCache cache = new cgCache();
if (page.indexOf("Cache is Unpublished") > -1) {
caches.error = "cache was unpublished";
return caches;
}
if (page.indexOf("Sorry, the owner of this listing has made it viewable to Premium Members only.") != -1) {
caches.error = "requested cache is for premium members only";
return caches;
}
if (page.indexOf("has chosen to make this cache listing visible to Premium Members only.") != -1) {
caches.error = "requested cache is for premium members only";
return caches;
}
if (page.indexOf("<li>This cache is temporarily unavailable.") != -1) {
cache.disabled = true;
} else {
cache.disabled = false;
}
if (page.indexOf("<li>This cache has been archived,") != -1) {
cache.archived = true;
} else {
cache.archived = false;
}
if (page.indexOf("<p class=\"Warning\">This is a Premium Member Only cache.</p>") != -1) {
cache.members = true;
} else {
cache.members = false;
}
cache.reason = reason;
// cache geocode
try {
final Matcher matcherGeocode = patternGeocode.matcher(page);
if (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
cache.geocode = getMatch(matcherGeocode.group(1));
}
}
} catch (Exception e) {
// failed to parse cache geocode
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache geocode");
}
// cache id
try {
final Matcher matcherCacheId = patternCacheId.matcher(page);
if (matcherCacheId.find()) {
if (matcherCacheId.groupCount() > 0) {
cache.cacheid = getMatch(matcherCacheId.group(1));
}
}
} catch (Exception e) {
// failed to parse cache id
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache id");
}
// cache guid
try {
final Matcher matcherCacheGuid = patternCacheGuid.matcher(page);
if (matcherCacheGuid.find()) {
if (matcherCacheGuid.groupCount() > 0) {
cache.guid = getMatch(matcherCacheGuid.group(1));
}
}
} catch (Exception e) {
// failed to parse cache guid
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache guid");
}
// name
try {
final Matcher matcherName = patternName.matcher(page);
if (matcherName.find()) {
if (matcherName.groupCount() > 0) {
cache.name = Html.fromHtml(matcherName.group(1)).toString();
}
}
} catch (Exception e) {
// failed to parse cache name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache name");
}
// owner real name
try {
final Matcher matcherOwnerReal = patternOwnerReal.matcher(page);
if (matcherOwnerReal.find()) {
if (matcherOwnerReal.groupCount() > 0) {
cache.ownerReal = URLDecoder.decode(matcherOwnerReal.group(1));
}
}
} catch (Exception e) {
// failed to parse owner real name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner real name");
}
final String username = settings.getUsername();
if (cache.ownerReal != null && username != null && cache.ownerReal.equalsIgnoreCase(username)) {
cache.own = true;
}
int pos = -1;
String tableInside = page;
pos = tableInside.indexOf("id=\"cacheDetails\"");
if (pos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"cacheDetails\" not found on page");
return null;
}
tableInside = tableInside.substring(pos);
pos = tableInside.indexOf("<div class=\"CacheInformationTable\"");
if (pos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"CacheInformationTable\" not found on page");
return null;
}
tableInside = tableInside.substring(0, pos);
if (tableInside != null && tableInside.length() > 0) {
// cache terrain
try {
final Matcher matcherTerrain = patternTerrain.matcher(tableInside);
if (matcherTerrain.find()) {
if (matcherTerrain.groupCount() > 0) {
cache.terrain = new Float(Pattern.compile("_").matcher(matcherTerrain.group(1)).replaceAll("."));
}
}
} catch (Exception e) {
// failed to parse terrain
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache terrain");
}
// cache difficulty
try {
final Matcher matcherDifficulty = patternDifficulty.matcher(tableInside);
if (matcherDifficulty.find()) {
if (matcherDifficulty.groupCount() > 0) {
cache.difficulty = new Float(Pattern.compile("_").matcher(matcherDifficulty.group(1)).replaceAll("."));
}
}
} catch (Exception e) {
// failed to parse difficulty
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache difficulty");
}
// owner
try {
final Matcher matcherOwner = patternOwner.matcher(tableInside);
if (matcherOwner.find()) {
if (matcherOwner.groupCount() > 0) {
cache.owner = Html.fromHtml(matcherOwner.group(2)).toString();
}
}
} catch (Exception e) {
// failed to parse owner
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner");
}
// hidden
try {
final Matcher matcherHidden = patternHidden.matcher(tableInside);
if (matcherHidden.find()) {
if (matcherHidden.groupCount() > 0) {
cache.hidden = parseDate(matcherHidden.group(1));
}
}
} catch (Exception e) {
// failed to parse cache hidden date
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hidden date");
}
if (cache.hidden == null) {
// event date
try {
final Matcher matcherHiddenEvent = patternHiddenEvent.matcher(tableInside);
if (matcherHiddenEvent.find()) {
if (matcherHiddenEvent.groupCount() > 0) {
cache.hidden = parseDate(matcherHiddenEvent.group(1));
}
}
} catch (Exception e) {
// failed to parse cache event date
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache event date");
}
}
// favourite
try {
final Matcher matcherFavourite = patternFavourite.matcher(tableInside);
if (matcherFavourite.find()) {
if (matcherFavourite.groupCount() > 0) {
cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
}
}
} catch (Exception e) {
// failed to parse favourite count
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse favourite count");
}
// cache size
try {
final Matcher matcherSize = patternSize.matcher(tableInside);
if (matcherSize.find()) {
if (matcherSize.groupCount() > 0) {
cache.size = getMatch(matcherSize.group(1)).toLowerCase();
}
}
} catch (Exception e) {
// failed to parse size
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache size");
}
}
// cache found
try {
final Matcher matcherFound = patternFound.matcher(page);
if (matcherFound.find()) {
if (matcherFound.group() != null && matcherFound.group().length() > 0) {
cache.found = true;
}
}
} catch (Exception e) {
// failed to parse found
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse found");
}
// cache type
try {
final Matcher matcherType = patternType.matcher(page);
if (matcherType.find()) {
if (matcherType.groupCount() > 0) {
cache.type = cacheTypes.get(matcherType.group(1).toLowerCase());
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache type");
}
// on watchlist
try {
final Matcher matcher = patternOnWatchlist.matcher(page);
cache.onWatchlist = matcher.find();
} catch (Exception e) {
// failed to parse watchlist state
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse watchlist state");
}
// latitude and logitude
try {
final Matcher matcherLatLon = patternLatLon.matcher(page);
if (matcherLatLon.find()) {
if (matcherLatLon.groupCount() > 0) {
cache.latlon = getMatch(matcherLatLon.group(2)); // first is <b>
HashMap<String, Object> tmp = cgBase.parseLatlon(cache.latlon);
if (tmp.size() > 0) {
cache.latitude = (Double) tmp.get("latitude");
cache.longitude = (Double) tmp.get("longitude");
cache.latitudeString = (String) tmp.get("latitudeString");
cache.longitudeString = (String) tmp.get("longitudeString");
cache.reliableLatLon = true;
}
tmp = null;
}
}
} catch (Exception e) {
// failed to parse latitude and/or longitude
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache coordinates");
}
// cache location
try {
final Matcher matcherLocation = patternLocation.matcher(page);
if (matcherLocation.find()) {
if (matcherLocation.groupCount() > 0) {
cache.location = getMatch(matcherLocation.group(1));
}
}
} catch (Exception e) {
// failed to parse location
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache location");
}
// cache hint
try {
final Matcher matcherHint = patternHint.matcher(page);
if (matcherHint.find()) {
if (matcherHint.groupCount() > 2 && matcherHint.group(3) != null) {
// replace linebreak and paragraph tags
String hint = Pattern.compile("<(br|p)[^>]*>").matcher(matcherHint.group(3)).replaceAll("\n");
if (hint != null) {
cache.hint = hint.replaceAll(Pattern.quote("</p>"), "").trim();
}
}
}
} catch (Exception e) {
// failed to parse hint
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hint");
}
checkFields(cache);
/*
// short info debug
Log.d(cgSettings.tag, "gc-code: " + cache.geocode);
Log.d(cgSettings.tag, "id: " + cache.cacheid);
Log.d(cgSettings.tag, "guid: " + cache.guid);
Log.d(cgSettings.tag, "name: " + cache.name);
Log.d(cgSettings.tag, "terrain: " + cache.terrain);
Log.d(cgSettings.tag, "difficulty: " + cache.difficulty);
Log.d(cgSettings.tag, "owner: " + cache.owner);
Log.d(cgSettings.tag, "owner (real): " + cache.ownerReal);
Log.d(cgSettings.tag, "hidden: " + dateOutShort.format(cache.hidden));
Log.d(cgSettings.tag, "favorite: " + cache.favouriteCnt);
Log.d(cgSettings.tag, "size: " + cache.size);
if (cache.found) {
Log.d(cgSettings.tag, "found!");
} else {
Log.d(cgSettings.tag, "not found");
}
Log.d(cgSettings.tag, "type: " + cache.type);
Log.d(cgSettings.tag, "latitude: " + String.format("%.6f", cache.latitude));
Log.d(cgSettings.tag, "longitude: " + String.format("%.6f", cache.longitude));
Log.d(cgSettings.tag, "location: " + cache.location);
Log.d(cgSettings.tag, "hint: " + cache.hint);
*/
// cache personal note
try {
final Matcher matcherPersonalNote = patternPersonalNote.matcher(page);
if (matcherPersonalNote.find()) {
if (matcherPersonalNote.groupCount() > 0) {
cache.personalNote = getMatch(matcherPersonalNote.group(1).trim());
}
}
} catch (Exception e) {
// failed to parse cache personal note
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache personal note");
}
// cache short description
try {
final Matcher matcherDescShort = patternDescShort.matcher(page);
if (matcherDescShort.find()) {
if (matcherDescShort.groupCount() > 0) {
cache.shortdesc = getMatch(matcherDescShort.group(1));
}
}
} catch (Exception e) {
// failed to parse short description
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache short description");
}
// cache description
try {
final Matcher matcherDesc = patternDesc.matcher(page);
if (matcherDesc.find()) {
if (matcherDesc.groupCount() > 0) {
cache.description = getMatch(matcherDesc.group(1));
}
}
} catch (Exception e) {
// failed to parse short description
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache description");
}
// cache attributes
try {
final Matcher matcherAttributes = patternAttributes.matcher(page);
while (matcherAttributes.find()) {
if (matcherAttributes.groupCount() > 0) {
final String attributesPre = matcherAttributes.group(1);
final Matcher matcherAttributesInside = patternAttributesInside.matcher(attributesPre);
while (matcherAttributesInside.find()) {
if (matcherAttributesInside.groupCount() > 1 && matcherAttributesInside.group(2).equalsIgnoreCase("blank") != true) {
if (cache.attributes == null) {
cache.attributes = new ArrayList<String>();
}
// by default, use the tooltip of the attribute
String attribute = matcherAttributesInside.group(2).toLowerCase();
// if the image name can be recognized, use the image name as attribute
String imageName = matcherAttributesInside.group(1).trim();
if (imageName.length() > 0) {
int start = imageName.lastIndexOf('/');
int end = imageName.lastIndexOf('.');
if (start >= 0 && end>= 0) {
attribute = imageName.substring(start + 1, end).replace('-', '_');
}
}
cache.attributes.add(attribute);
}
}
}
}
} catch (Exception e) {
// failed to parse cache attributes
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache attributes");
}
// cache spoilers
try {
final Matcher matcherSpoilers = patternSpoilers.matcher(page);
while (matcherSpoilers.find()) {
if (matcherSpoilers.groupCount() > 0) {
final String spoilersPre = matcherSpoilers.group(1);
final Matcher matcherSpoilersInside = patternSpoilersInside.matcher(spoilersPre);
while (matcherSpoilersInside.find()) {
if (matcherSpoilersInside.groupCount() > 0) {
final cgImage spoiler = new cgImage();
spoiler.url = matcherSpoilersInside.group(1);
if (matcherSpoilersInside.group(2) != null) {
spoiler.title = matcherSpoilersInside.group(2);
}
if (matcherSpoilersInside.group(4) != null) {
spoiler.description = matcherSpoilersInside.group(4);
}
if (cache.spoilers == null) {
cache.spoilers = new ArrayList<cgImage>();
}
cache.spoilers.add(spoiler);
}
}
}
}
} catch (Exception e) {
// failed to parse cache spoilers
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache spoilers");
}
// cache inventory
try {
cache.inventoryItems = 0;
final Matcher matcherInventory = patternInventory.matcher(page);
while (matcherInventory.find()) {
if (cache.inventory == null) {
cache.inventory = new ArrayList<cgTrackable>();
}
if (matcherInventory.groupCount() > 1) {
final String inventoryPre = matcherInventory.group(2);
if (inventoryPre != null && inventoryPre.length() > 0) {
final Matcher matcherInventoryInside = patternInventoryInside.matcher(inventoryPre);
while (matcherInventoryInside.find()) {
if (matcherInventoryInside.groupCount() > 0) {
final cgTrackable inventoryItem = new cgTrackable();
inventoryItem.guid = matcherInventoryInside.group(1);
inventoryItem.name = matcherInventoryInside.group(2);
cache.inventory.add(inventoryItem);
cache.inventoryItems++;
}
}
}
}
}
} catch (Exception e) {
// failed to parse cache inventory
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache inventory (2)");
}
// cache logs counts
try {
final Matcher matcherLogCounts = patternCountLogs.matcher(page);
while (matcherLogCounts.find()) {
if (matcherLogCounts.groupCount() > 0) {
final String[] logs = matcherLogCounts.group(1).split("<img");
final int logsCnt = logs.length;
for (int k = 1; k < logsCnt; k++) {
Integer type = null;
Integer count = null;
final Matcher matcherLog = patternCountLog.matcher(logs[k]);
if (matcherLog.find()) {
String typeStr = matcherLog.group(1);
String countStr = matcherLog.group(2);
if (typeStr != null && typeStr.length() > 0) {
if (logTypes.containsKey(typeStr.toLowerCase())) {
type = logTypes.get(typeStr.toLowerCase());
}
}
if (countStr != null && countStr.length() > 0) {
count = Integer.parseInt(countStr);
}
if (type != null && count != null) {
cache.logCounts.put(type, count);
}
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache log count");
}
// cache logs
try {
final Matcher matcherLogs = patternLogs.matcher(page);
while (matcherLogs.find()) {
if (matcherLogs.groupCount() > 0) {
final String[] logs = matcherLogs.group(1).split("</tr><tr>");
final int logsCnt = logs.length;
for (int k = 0; k < logsCnt; k++) {
final Matcher matcherLog = patternLog.matcher(logs[k]);
if (matcherLog.find()) {
final cgLog logDone = new cgLog();
String logTmp = matcherLog.group(10);
int day = -1;
try {
day = Integer.parseInt(matcherLog.group(3));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (day): " + e.toString());
}
int month = -1;
// January | February | March | April | May | June | July | August | September | October | November | December
if (matcherLog.group(2).equalsIgnoreCase("January")) {
month = 0;
} else if (matcherLog.group(2).equalsIgnoreCase("February")) {
month = 1;
} else if (matcherLog.group(2).equalsIgnoreCase("March")) {
month = 2;
} else if (matcherLog.group(2).equalsIgnoreCase("April")) {
month = 3;
} else if (matcherLog.group(2).equalsIgnoreCase("May")) {
month = 4;
} else if (matcherLog.group(2).equalsIgnoreCase("June")) {
month = 5;
} else if (matcherLog.group(2).equalsIgnoreCase("July")) {
month = 6;
} else if (matcherLog.group(2).equalsIgnoreCase("August")) {
month = 7;
} else if (matcherLog.group(2).equalsIgnoreCase("September")) {
month = 8;
} else if (matcherLog.group(2).equalsIgnoreCase("October")) {
month = 9;
} else if (matcherLog.group(2).equalsIgnoreCase("November")) {
month = 10;
} else if (matcherLog.group(2).equalsIgnoreCase("December")) {
month = 11;
} else {
Log.w(cgSettings.tag, "Failed to parse logs date (month).");
}
int year = -1;
final String yearPre = matcherLog.group(5);
if (yearPre == null) {
Calendar date = Calendar.getInstance();
year = date.get(Calendar.YEAR);
} else {
try {
year = Integer.parseInt(matcherLog.group(5));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (year): " + e.toString());
}
}
long logDate;
if (year > 0 && month >= 0 && day > 0) {
Calendar date = Calendar.getInstance();
date.set(year, month, day, 12, 0, 0);
logDate = date.getTimeInMillis();
logDate = (logDate / 1000L) * 1000L;
} else {
logDate = 0;
}
if (logTypes.containsKey(matcherLog.group(1).toLowerCase())) {
logDone.type = logTypes.get(matcherLog.group(1).toLowerCase());
} else {
logDone.type = logTypes.get("icon_note");
}
logDone.author = Html.fromHtml(matcherLog.group(6)).toString();
logDone.date = logDate;
if (matcherLog.group(8) != null) {
logDone.found = new Integer(matcherLog.group(8));
}
final Matcher matcherImg = patternLogImgs.matcher(logs[k]);
while (matcherImg.find()) {
final cgImage logImage = new cgImage();
logImage.url = "http://img.geocaching.com/cache/log/" + matcherImg.group(1);
logImage.title = matcherImg.group(2);
if (logDone.logImages == null) {
logDone.logImages = new ArrayList<cgImage>();
}
logDone.logImages.add(logImage);
}
logDone.log = logTmp;
if (cache.logs == null) {
cache.logs = new ArrayList<cgLog>();
}
cache.logs.add(logDone);
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache logs");
}
int wpBegin = 0;
int wpEnd = 0;
wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">");
if (wpBegin != -1) { // parse waypoints
final Pattern patternWpType = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg", Pattern.CASE_INSENSITIVE);
final Pattern patternWpPrefixOrLookupOrLatlon = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>", Pattern.CASE_INSENSITIVE);
final Pattern patternWpName = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>", Pattern.CASE_INSENSITIVE);
final Pattern patternWpNote = Pattern.compile("colspan=\"6\">(.*)<\\/td>", Pattern.CASE_INSENSITIVE);
String wpList = page.substring(wpBegin);
wpEnd = wpList.indexOf("</p>");
if (wpEnd > -1 && wpEnd <= wpList.length()) {
wpList = wpList.substring(0, wpEnd);
}
if (wpList.indexOf("No additional waypoints to display.") == -1) {
wpEnd = wpList.indexOf("</table>");
wpList = wpList.substring(0, wpEnd);
wpBegin = wpList.indexOf("<tbody>");
wpEnd = wpList.indexOf("</tbody>");
if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) {
wpList = wpList.substring(wpBegin + 7, wpEnd);
}
final String[] wpItems = wpList.split("<tr");
String[] wp;
for (int j = 1; j < wpItems.length; j++) {
final cgWaypoint waypoint = new cgWaypoint();
wp = wpItems[j].split("<td");
// waypoint type
try {
final Matcher matcherWpType = patternWpType.matcher(wp[3]);
while (matcherWpType.find()) {
if (matcherWpType.groupCount() > 0) {
waypoint.type = matcherWpType.group(1);
if (waypoint.type != null) {
waypoint.type = waypoint.type.trim();
}
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint type");
}
// waypoint prefix
try {
final Matcher matcherWpPrefix = patternWpPrefixOrLookupOrLatlon.matcher(wp[4]);
while (matcherWpPrefix.find()) {
if (matcherWpPrefix.groupCount() > 1) {
waypoint.prefix = matcherWpPrefix.group(2);
if (waypoint.prefix != null) {
waypoint.prefix = waypoint.prefix.trim();
}
}
}
} catch (Exception e) {
// failed to parse prefix
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint prefix");
}
// waypoint lookup
try {
final Matcher matcherWpLookup = patternWpPrefixOrLookupOrLatlon.matcher(wp[5]);
while (matcherWpLookup.find()) {
if (matcherWpLookup.groupCount() > 1) {
waypoint.lookup = matcherWpLookup.group(2);
if (waypoint.lookup != null) {
waypoint.lookup = waypoint.lookup.trim();
}
}
}
} catch (Exception e) {
// failed to parse lookup
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint lookup");
}
// waypoint name
try {
final Matcher matcherWpName = patternWpName.matcher(wp[6]);
while (matcherWpName.find()) {
if (matcherWpName.groupCount() > 0) {
waypoint.name = matcherWpName.group(1);
if (waypoint.name != null) {
waypoint.name = waypoint.name.trim();
}
}
}
} catch (Exception e) {
// failed to parse name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint name");
}
// waypoint latitude and logitude
try {
final Matcher matcherWpLatLon = patternWpPrefixOrLookupOrLatlon.matcher(wp[7]);
while (matcherWpLatLon.find()) {
if (matcherWpLatLon.groupCount() > 1) {
waypoint.latlon = Html.fromHtml(matcherWpLatLon.group(2)).toString();
final HashMap<String, Object> tmp = cgBase.parseLatlon(waypoint.latlon);
if (tmp.size() > 0) {
waypoint.latitude = (Double) tmp.get("latitude");
waypoint.longitude = (Double) tmp.get("longitude");
waypoint.latitudeString = (String) tmp.get("latitudeString");
waypoint.longitudeString = (String) tmp.get("longitudeString");
}
}
}
} catch (Exception e) {
// failed to parse latitude and/or longitude
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint coordinates");
}
j++;
if (wpItems.length > j) {
wp = wpItems[j].split("<td");
}
// waypoint note
try {
final Matcher matcherWpNote = patternWpNote.matcher(wp[3]);
while (matcherWpNote.find()) {
if (matcherWpNote.groupCount() > 0) {
waypoint.note = matcherWpNote.group(1);
if (waypoint.note != null) {
waypoint.note = waypoint.note.trim();
}
}
}
} catch (Exception e) {
// failed to parse note
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint note");
}
if (cache.waypoints == null)
cache.waypoints = new ArrayList<cgWaypoint>();
cache.waypoints.add(waypoint);
}
}
}
if (cache.latitude != null && cache.longitude != null) {
cache.elevation = getElevation(cache.latitude, cache.longitude);
}
final cgRating rating = getRating(cache.guid, cache.geocode);
if (rating != null) {
cache.rating = rating.rating;
cache.votes = rating.votes;
cache.myVote = rating.myVote;
}
cache.updated = System.currentTimeMillis();
cache.detailedUpdate = System.currentTimeMillis();
cache.detailed = true;
caches.cacheList.add(cache);
return caches;
}
| public cgCacheWrap parseCache(String page, int reason) {
if (page == null || page.length() == 0) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: No page given");
return null;
}
final cgCacheWrap caches = new cgCacheWrap();
final cgCache cache = new cgCache();
if (page.indexOf("Cache is Unpublished") > -1) {
caches.error = "cache was unpublished";
return caches;
}
if (page.indexOf("Sorry, the owner of this listing has made it viewable to Premium Members only.") != -1) {
caches.error = "requested cache is for premium members only";
return caches;
}
if (page.indexOf("has chosen to make this cache listing visible to Premium Members only.") != -1) {
caches.error = "requested cache is for premium members only";
return caches;
}
if (page.indexOf("<li>This cache is temporarily unavailable.") != -1) {
cache.disabled = true;
} else {
cache.disabled = false;
}
if (page.indexOf("<li>This cache has been archived,") != -1) {
cache.archived = true;
} else {
cache.archived = false;
}
if (page.indexOf("<p class=\"Warning\">This is a Premium Member Only cache.</p>") != -1) {
cache.members = true;
} else {
cache.members = false;
}
cache.reason = reason;
// cache geocode
try {
final Matcher matcherGeocode = patternGeocode.matcher(page);
if (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
cache.geocode = getMatch(matcherGeocode.group(1));
}
}
} catch (Exception e) {
// failed to parse cache geocode
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache geocode");
}
// cache id
try {
final Matcher matcherCacheId = patternCacheId.matcher(page);
if (matcherCacheId.find()) {
if (matcherCacheId.groupCount() > 0) {
cache.cacheid = getMatch(matcherCacheId.group(1));
}
}
} catch (Exception e) {
// failed to parse cache id
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache id");
}
// cache guid
try {
final Matcher matcherCacheGuid = patternCacheGuid.matcher(page);
if (matcherCacheGuid.find()) {
if (matcherCacheGuid.groupCount() > 0) {
cache.guid = getMatch(matcherCacheGuid.group(1));
}
}
} catch (Exception e) {
// failed to parse cache guid
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache guid");
}
// name
try {
final Matcher matcherName = patternName.matcher(page);
if (matcherName.find()) {
if (matcherName.groupCount() > 0) {
cache.name = Html.fromHtml(matcherName.group(1)).toString();
}
}
} catch (Exception e) {
// failed to parse cache name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache name");
}
// owner real name
try {
final Matcher matcherOwnerReal = patternOwnerReal.matcher(page);
if (matcherOwnerReal.find()) {
if (matcherOwnerReal.groupCount() > 0) {
cache.ownerReal = URLDecoder.decode(matcherOwnerReal.group(1));
}
}
} catch (Exception e) {
// failed to parse owner real name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner real name");
}
final String username = settings.getUsername();
if (cache.ownerReal != null && username != null && cache.ownerReal.equalsIgnoreCase(username)) {
cache.own = true;
}
int pos = -1;
String tableInside = page;
pos = tableInside.indexOf("id=\"cacheDetails\"");
if (pos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"cacheDetails\" not found on page");
return null;
}
tableInside = tableInside.substring(pos);
pos = tableInside.indexOf("<div class=\"CacheInformationTable\"");
if (pos == -1) {
Log.e(cgSettings.tag, "cgeoBase.parseCache: ID \"CacheInformationTable\" not found on page");
return null;
}
tableInside = tableInside.substring(0, pos);
if (tableInside != null && tableInside.length() > 0) {
// cache terrain
try {
final Matcher matcherTerrain = patternTerrain.matcher(tableInside);
if (matcherTerrain.find()) {
if (matcherTerrain.groupCount() > 0) {
cache.terrain = new Float(Pattern.compile("_").matcher(matcherTerrain.group(1)).replaceAll("."));
}
}
} catch (Exception e) {
// failed to parse terrain
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache terrain");
}
// cache difficulty
try {
final Matcher matcherDifficulty = patternDifficulty.matcher(tableInside);
if (matcherDifficulty.find()) {
if (matcherDifficulty.groupCount() > 0) {
cache.difficulty = new Float(Pattern.compile("_").matcher(matcherDifficulty.group(1)).replaceAll("."));
}
}
} catch (Exception e) {
// failed to parse difficulty
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache difficulty");
}
// owner
try {
final Matcher matcherOwner = patternOwner.matcher(tableInside);
if (matcherOwner.find()) {
if (matcherOwner.groupCount() > 0) {
cache.owner = Html.fromHtml(matcherOwner.group(2)).toString();
}
}
} catch (Exception e) {
// failed to parse owner
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache owner");
}
// hidden
try {
final Matcher matcherHidden = patternHidden.matcher(tableInside);
if (matcherHidden.find()) {
if (matcherHidden.groupCount() > 0) {
cache.hidden = parseDate(matcherHidden.group(1));
}
}
} catch (Exception e) {
// failed to parse cache hidden date
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hidden date");
}
if (cache.hidden == null) {
// event date
try {
final Matcher matcherHiddenEvent = patternHiddenEvent.matcher(tableInside);
if (matcherHiddenEvent.find()) {
if (matcherHiddenEvent.groupCount() > 0) {
cache.hidden = parseDate(matcherHiddenEvent.group(1));
}
}
} catch (Exception e) {
// failed to parse cache event date
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache event date");
}
}
// favourite
try {
final Matcher matcherFavourite = patternFavourite.matcher(tableInside);
if (matcherFavourite.find()) {
if (matcherFavourite.groupCount() > 0) {
cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
}
}
} catch (Exception e) {
// failed to parse favourite count
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse favourite count");
}
// cache size
try {
final Matcher matcherSize = patternSize.matcher(tableInside);
if (matcherSize.find()) {
if (matcherSize.groupCount() > 0) {
cache.size = getMatch(matcherSize.group(1)).toLowerCase();
}
}
} catch (Exception e) {
// failed to parse size
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache size");
}
}
// cache found
try {
final Matcher matcherFound = patternFound.matcher(page);
if (matcherFound.find()) {
if (matcherFound.group() != null && matcherFound.group().length() > 0) {
cache.found = true;
}
}
} catch (Exception e) {
// failed to parse found
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse found");
}
// cache type
try {
final Matcher matcherType = patternType.matcher(page);
if (matcherType.find()) {
if (matcherType.groupCount() > 0) {
cache.type = cacheTypes.get(matcherType.group(1).toLowerCase());
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache type");
}
// on watchlist
try {
final Matcher matcher = patternOnWatchlist.matcher(page);
cache.onWatchlist = matcher.find();
} catch (Exception e) {
// failed to parse watchlist state
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse watchlist state");
}
// latitude and logitude
try {
final Matcher matcherLatLon = patternLatLon.matcher(page);
if (matcherLatLon.find()) {
if (matcherLatLon.groupCount() > 0) {
cache.latlon = getMatch(matcherLatLon.group(2)); // first is <b>
HashMap<String, Object> tmp = cgBase.parseLatlon(cache.latlon);
if (tmp.size() > 0) {
cache.latitude = (Double) tmp.get("latitude");
cache.longitude = (Double) tmp.get("longitude");
cache.latitudeString = (String) tmp.get("latitudeString");
cache.longitudeString = (String) tmp.get("longitudeString");
cache.reliableLatLon = true;
}
tmp = null;
}
}
} catch (Exception e) {
// failed to parse latitude and/or longitude
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache coordinates");
}
// cache location
try {
final Matcher matcherLocation = patternLocation.matcher(page);
if (matcherLocation.find()) {
if (matcherLocation.groupCount() > 0) {
cache.location = getMatch(matcherLocation.group(1));
}
}
} catch (Exception e) {
// failed to parse location
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache location");
}
// cache hint
try {
final Matcher matcherHint = patternHint.matcher(page);
if (matcherHint.find()) {
if (matcherHint.groupCount() > 2 && matcherHint.group(3) != null) {
// replace linebreak and paragraph tags
String hint = Pattern.compile("<(br|p)[^>]*>").matcher(matcherHint.group(3)).replaceAll("\n");
if (hint != null) {
cache.hint = hint.replaceAll(Pattern.quote("</p>"), "").trim();
}
}
}
} catch (Exception e) {
// failed to parse hint
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache hint");
}
checkFields(cache);
/*
// short info debug
Log.d(cgSettings.tag, "gc-code: " + cache.geocode);
Log.d(cgSettings.tag, "id: " + cache.cacheid);
Log.d(cgSettings.tag, "guid: " + cache.guid);
Log.d(cgSettings.tag, "name: " + cache.name);
Log.d(cgSettings.tag, "terrain: " + cache.terrain);
Log.d(cgSettings.tag, "difficulty: " + cache.difficulty);
Log.d(cgSettings.tag, "owner: " + cache.owner);
Log.d(cgSettings.tag, "owner (real): " + cache.ownerReal);
Log.d(cgSettings.tag, "hidden: " + dateOutShort.format(cache.hidden));
Log.d(cgSettings.tag, "favorite: " + cache.favouriteCnt);
Log.d(cgSettings.tag, "size: " + cache.size);
if (cache.found) {
Log.d(cgSettings.tag, "found!");
} else {
Log.d(cgSettings.tag, "not found");
}
Log.d(cgSettings.tag, "type: " + cache.type);
Log.d(cgSettings.tag, "latitude: " + String.format("%.6f", cache.latitude));
Log.d(cgSettings.tag, "longitude: " + String.format("%.6f", cache.longitude));
Log.d(cgSettings.tag, "location: " + cache.location);
Log.d(cgSettings.tag, "hint: " + cache.hint);
*/
// cache personal note
try {
final Matcher matcherPersonalNote = patternPersonalNote.matcher(page);
if (matcherPersonalNote.find()) {
if (matcherPersonalNote.groupCount() > 0) {
cache.personalNote = getMatch(matcherPersonalNote.group(1).trim());
}
}
} catch (Exception e) {
// failed to parse cache personal note
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache personal note");
}
// cache short description
try {
final Matcher matcherDescShort = patternDescShort.matcher(page);
if (matcherDescShort.find()) {
if (matcherDescShort.groupCount() > 0) {
cache.shortdesc = getMatch(matcherDescShort.group(1));
}
}
} catch (Exception e) {
// failed to parse short description
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache short description");
}
// cache description
try {
final Matcher matcherDesc = patternDesc.matcher(page);
if (matcherDesc.find()) {
if (matcherDesc.groupCount() > 0) {
cache.description = getMatch(matcherDesc.group(1));
}
}
} catch (Exception e) {
// failed to parse short description
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache description");
}
// cache attributes
try {
final Matcher matcherAttributes = patternAttributes.matcher(page);
while (matcherAttributes.find()) {
if (matcherAttributes.groupCount() > 0) {
final String attributesPre = matcherAttributes.group(1);
final Matcher matcherAttributesInside = patternAttributesInside.matcher(attributesPre);
while (matcherAttributesInside.find()) {
if (matcherAttributesInside.groupCount() > 1 && matcherAttributesInside.group(2).equalsIgnoreCase("blank") != true) {
if (cache.attributes == null) {
cache.attributes = new ArrayList<String>();
}
// by default, use the tooltip of the attribute
String attribute = matcherAttributesInside.group(2).toLowerCase();
// if the image name can be recognized, use the image name as attribute
String imageName = matcherAttributesInside.group(1).trim();
if (imageName.length() > 0) {
int start = imageName.lastIndexOf('/');
int end = imageName.lastIndexOf('.');
if (start >= 0 && end>= 0) {
attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase();
}
}
cache.attributes.add(attribute);
}
}
}
}
} catch (Exception e) {
// failed to parse cache attributes
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache attributes");
}
// cache spoilers
try {
final Matcher matcherSpoilers = patternSpoilers.matcher(page);
while (matcherSpoilers.find()) {
if (matcherSpoilers.groupCount() > 0) {
final String spoilersPre = matcherSpoilers.group(1);
final Matcher matcherSpoilersInside = patternSpoilersInside.matcher(spoilersPre);
while (matcherSpoilersInside.find()) {
if (matcherSpoilersInside.groupCount() > 0) {
final cgImage spoiler = new cgImage();
spoiler.url = matcherSpoilersInside.group(1);
if (matcherSpoilersInside.group(2) != null) {
spoiler.title = matcherSpoilersInside.group(2);
}
if (matcherSpoilersInside.group(4) != null) {
spoiler.description = matcherSpoilersInside.group(4);
}
if (cache.spoilers == null) {
cache.spoilers = new ArrayList<cgImage>();
}
cache.spoilers.add(spoiler);
}
}
}
}
} catch (Exception e) {
// failed to parse cache spoilers
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache spoilers");
}
// cache inventory
try {
cache.inventoryItems = 0;
final Matcher matcherInventory = patternInventory.matcher(page);
while (matcherInventory.find()) {
if (cache.inventory == null) {
cache.inventory = new ArrayList<cgTrackable>();
}
if (matcherInventory.groupCount() > 1) {
final String inventoryPre = matcherInventory.group(2);
if (inventoryPre != null && inventoryPre.length() > 0) {
final Matcher matcherInventoryInside = patternInventoryInside.matcher(inventoryPre);
while (matcherInventoryInside.find()) {
if (matcherInventoryInside.groupCount() > 0) {
final cgTrackable inventoryItem = new cgTrackable();
inventoryItem.guid = matcherInventoryInside.group(1);
inventoryItem.name = matcherInventoryInside.group(2);
cache.inventory.add(inventoryItem);
cache.inventoryItems++;
}
}
}
}
}
} catch (Exception e) {
// failed to parse cache inventory
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache inventory (2)");
}
// cache logs counts
try {
final Matcher matcherLogCounts = patternCountLogs.matcher(page);
while (matcherLogCounts.find()) {
if (matcherLogCounts.groupCount() > 0) {
final String[] logs = matcherLogCounts.group(1).split("<img");
final int logsCnt = logs.length;
for (int k = 1; k < logsCnt; k++) {
Integer type = null;
Integer count = null;
final Matcher matcherLog = patternCountLog.matcher(logs[k]);
if (matcherLog.find()) {
String typeStr = matcherLog.group(1);
String countStr = matcherLog.group(2);
if (typeStr != null && typeStr.length() > 0) {
if (logTypes.containsKey(typeStr.toLowerCase())) {
type = logTypes.get(typeStr.toLowerCase());
}
}
if (countStr != null && countStr.length() > 0) {
count = Integer.parseInt(countStr);
}
if (type != null && count != null) {
cache.logCounts.put(type, count);
}
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache log count");
}
// cache logs
try {
final Matcher matcherLogs = patternLogs.matcher(page);
while (matcherLogs.find()) {
if (matcherLogs.groupCount() > 0) {
final String[] logs = matcherLogs.group(1).split("</tr><tr>");
final int logsCnt = logs.length;
for (int k = 0; k < logsCnt; k++) {
final Matcher matcherLog = patternLog.matcher(logs[k]);
if (matcherLog.find()) {
final cgLog logDone = new cgLog();
String logTmp = matcherLog.group(10);
int day = -1;
try {
day = Integer.parseInt(matcherLog.group(3));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (day): " + e.toString());
}
int month = -1;
// January | February | March | April | May | June | July | August | September | October | November | December
if (matcherLog.group(2).equalsIgnoreCase("January")) {
month = 0;
} else if (matcherLog.group(2).equalsIgnoreCase("February")) {
month = 1;
} else if (matcherLog.group(2).equalsIgnoreCase("March")) {
month = 2;
} else if (matcherLog.group(2).equalsIgnoreCase("April")) {
month = 3;
} else if (matcherLog.group(2).equalsIgnoreCase("May")) {
month = 4;
} else if (matcherLog.group(2).equalsIgnoreCase("June")) {
month = 5;
} else if (matcherLog.group(2).equalsIgnoreCase("July")) {
month = 6;
} else if (matcherLog.group(2).equalsIgnoreCase("August")) {
month = 7;
} else if (matcherLog.group(2).equalsIgnoreCase("September")) {
month = 8;
} else if (matcherLog.group(2).equalsIgnoreCase("October")) {
month = 9;
} else if (matcherLog.group(2).equalsIgnoreCase("November")) {
month = 10;
} else if (matcherLog.group(2).equalsIgnoreCase("December")) {
month = 11;
} else {
Log.w(cgSettings.tag, "Failed to parse logs date (month).");
}
int year = -1;
final String yearPre = matcherLog.group(5);
if (yearPre == null) {
Calendar date = Calendar.getInstance();
year = date.get(Calendar.YEAR);
} else {
try {
year = Integer.parseInt(matcherLog.group(5));
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse logs date (year): " + e.toString());
}
}
long logDate;
if (year > 0 && month >= 0 && day > 0) {
Calendar date = Calendar.getInstance();
date.set(year, month, day, 12, 0, 0);
logDate = date.getTimeInMillis();
logDate = (logDate / 1000L) * 1000L;
} else {
logDate = 0;
}
if (logTypes.containsKey(matcherLog.group(1).toLowerCase())) {
logDone.type = logTypes.get(matcherLog.group(1).toLowerCase());
} else {
logDone.type = logTypes.get("icon_note");
}
logDone.author = Html.fromHtml(matcherLog.group(6)).toString();
logDone.date = logDate;
if (matcherLog.group(8) != null) {
logDone.found = new Integer(matcherLog.group(8));
}
final Matcher matcherImg = patternLogImgs.matcher(logs[k]);
while (matcherImg.find()) {
final cgImage logImage = new cgImage();
logImage.url = "http://img.geocaching.com/cache/log/" + matcherImg.group(1);
logImage.title = matcherImg.group(2);
if (logDone.logImages == null) {
logDone.logImages = new ArrayList<cgImage>();
}
logDone.logImages.add(logImage);
}
logDone.log = logTmp;
if (cache.logs == null) {
cache.logs = new ArrayList<cgLog>();
}
cache.logs.add(logDone);
}
}
}
}
} catch (Exception e) {
// failed to parse logs
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse cache logs");
}
int wpBegin = 0;
int wpEnd = 0;
wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">");
if (wpBegin != -1) { // parse waypoints
final Pattern patternWpType = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg", Pattern.CASE_INSENSITIVE);
final Pattern patternWpPrefixOrLookupOrLatlon = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>", Pattern.CASE_INSENSITIVE);
final Pattern patternWpName = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>", Pattern.CASE_INSENSITIVE);
final Pattern patternWpNote = Pattern.compile("colspan=\"6\">(.*)<\\/td>", Pattern.CASE_INSENSITIVE);
String wpList = page.substring(wpBegin);
wpEnd = wpList.indexOf("</p>");
if (wpEnd > -1 && wpEnd <= wpList.length()) {
wpList = wpList.substring(0, wpEnd);
}
if (wpList.indexOf("No additional waypoints to display.") == -1) {
wpEnd = wpList.indexOf("</table>");
wpList = wpList.substring(0, wpEnd);
wpBegin = wpList.indexOf("<tbody>");
wpEnd = wpList.indexOf("</tbody>");
if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) {
wpList = wpList.substring(wpBegin + 7, wpEnd);
}
final String[] wpItems = wpList.split("<tr");
String[] wp;
for (int j = 1; j < wpItems.length; j++) {
final cgWaypoint waypoint = new cgWaypoint();
wp = wpItems[j].split("<td");
// waypoint type
try {
final Matcher matcherWpType = patternWpType.matcher(wp[3]);
while (matcherWpType.find()) {
if (matcherWpType.groupCount() > 0) {
waypoint.type = matcherWpType.group(1);
if (waypoint.type != null) {
waypoint.type = waypoint.type.trim();
}
}
}
} catch (Exception e) {
// failed to parse type
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint type");
}
// waypoint prefix
try {
final Matcher matcherWpPrefix = patternWpPrefixOrLookupOrLatlon.matcher(wp[4]);
while (matcherWpPrefix.find()) {
if (matcherWpPrefix.groupCount() > 1) {
waypoint.prefix = matcherWpPrefix.group(2);
if (waypoint.prefix != null) {
waypoint.prefix = waypoint.prefix.trim();
}
}
}
} catch (Exception e) {
// failed to parse prefix
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint prefix");
}
// waypoint lookup
try {
final Matcher matcherWpLookup = patternWpPrefixOrLookupOrLatlon.matcher(wp[5]);
while (matcherWpLookup.find()) {
if (matcherWpLookup.groupCount() > 1) {
waypoint.lookup = matcherWpLookup.group(2);
if (waypoint.lookup != null) {
waypoint.lookup = waypoint.lookup.trim();
}
}
}
} catch (Exception e) {
// failed to parse lookup
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint lookup");
}
// waypoint name
try {
final Matcher matcherWpName = patternWpName.matcher(wp[6]);
while (matcherWpName.find()) {
if (matcherWpName.groupCount() > 0) {
waypoint.name = matcherWpName.group(1);
if (waypoint.name != null) {
waypoint.name = waypoint.name.trim();
}
}
}
} catch (Exception e) {
// failed to parse name
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint name");
}
// waypoint latitude and logitude
try {
final Matcher matcherWpLatLon = patternWpPrefixOrLookupOrLatlon.matcher(wp[7]);
while (matcherWpLatLon.find()) {
if (matcherWpLatLon.groupCount() > 1) {
waypoint.latlon = Html.fromHtml(matcherWpLatLon.group(2)).toString();
final HashMap<String, Object> tmp = cgBase.parseLatlon(waypoint.latlon);
if (tmp.size() > 0) {
waypoint.latitude = (Double) tmp.get("latitude");
waypoint.longitude = (Double) tmp.get("longitude");
waypoint.latitudeString = (String) tmp.get("latitudeString");
waypoint.longitudeString = (String) tmp.get("longitudeString");
}
}
}
} catch (Exception e) {
// failed to parse latitude and/or longitude
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint coordinates");
}
j++;
if (wpItems.length > j) {
wp = wpItems[j].split("<td");
}
// waypoint note
try {
final Matcher matcherWpNote = patternWpNote.matcher(wp[3]);
while (matcherWpNote.find()) {
if (matcherWpNote.groupCount() > 0) {
waypoint.note = matcherWpNote.group(1);
if (waypoint.note != null) {
waypoint.note = waypoint.note.trim();
}
}
}
} catch (Exception e) {
// failed to parse note
Log.w(cgSettings.tag, "cgeoBase.parseCache: Failed to parse waypoint note");
}
if (cache.waypoints == null)
cache.waypoints = new ArrayList<cgWaypoint>();
cache.waypoints.add(waypoint);
}
}
}
if (cache.latitude != null && cache.longitude != null) {
cache.elevation = getElevation(cache.latitude, cache.longitude);
}
final cgRating rating = getRating(cache.guid, cache.geocode);
if (rating != null) {
cache.rating = rating.rating;
cache.votes = rating.votes;
cache.myVote = rating.myVote;
}
cache.updated = System.currentTimeMillis();
cache.detailedUpdate = System.currentTimeMillis();
cache.detailed = true;
caches.cacheList.add(cache);
return caches;
}
|
diff --git a/obdalib/obdalib-owlapi3/src/main/java/it/unibz/krdb/obda/owlapi3/OWLAPI3IndividualTranslator.java b/obdalib/obdalib-owlapi3/src/main/java/it/unibz/krdb/obda/owlapi3/OWLAPI3IndividualTranslator.java
index db28a6810..8b999866d 100644
--- a/obdalib/obdalib-owlapi3/src/main/java/it/unibz/krdb/obda/owlapi3/OWLAPI3IndividualTranslator.java
+++ b/obdalib/obdalib-owlapi3/src/main/java/it/unibz/krdb/obda/owlapi3/OWLAPI3IndividualTranslator.java
@@ -1,134 +1,133 @@
package it.unibz.krdb.obda.owlapi3;
import it.unibz.krdb.obda.model.BNode;
import it.unibz.krdb.obda.model.Constant;
import it.unibz.krdb.obda.model.Predicate.COL_TYPE;
import it.unibz.krdb.obda.model.URIConstant;
import it.unibz.krdb.obda.model.ValueConstant;
import it.unibz.krdb.obda.ontology.Assertion;
import it.unibz.krdb.obda.ontology.ClassAssertion;
import it.unibz.krdb.obda.ontology.DataPropertyAssertion;
import it.unibz.krdb.obda.ontology.ObjectPropertyAssertion;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLIndividualAxiom;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLPropertyAssertionObject;
import org.semanticweb.owlapi.vocab.OWL2Datatype;
import uk.ac.manchester.cs.owl.owlapi.OWLDataFactoryImpl;
public class OWLAPI3IndividualTranslator {
private OWLDataFactory dataFactory = null;
public OWLAPI3IndividualTranslator() {
dataFactory = new OWLDataFactoryImpl();
}
public OWLIndividualAxiom translate(Assertion assertion) {
if (assertion instanceof ClassAssertion) {
ClassAssertion ca = (ClassAssertion) assertion;
IRI conceptIRI = IRI.create(ca.getConcept().getName().toString());
OWLClass description = dataFactory.getOWLClass(conceptIRI);
OWLIndividual object = (OWLNamedIndividual) translate(ca
.getObject());
return dataFactory.getOWLClassAssertionAxiom(description, object);
} else if (assertion instanceof ObjectPropertyAssertion) {
ObjectPropertyAssertion opa = (ObjectPropertyAssertion) assertion;
IRI roleIRI = IRI.create(opa.getRole().getName().toString());
OWLObjectProperty property = dataFactory
.getOWLObjectProperty(roleIRI);
OWLIndividual subject = (OWLNamedIndividual) translate(opa
.getFirstObject());
OWLIndividual object = (OWLNamedIndividual) translate(opa
.getSecondObject());
return dataFactory.getOWLObjectPropertyAssertionAxiom(property,
subject, object);
} else if (assertion instanceof DataPropertyAssertion) {
DataPropertyAssertion dpa = (DataPropertyAssertion) assertion;
IRI attributeIRI = IRI.create(dpa.getAttribute().getName().toString());
OWLDataProperty property = dataFactory
.getOWLDataProperty(attributeIRI);
OWLIndividual subject = (OWLNamedIndividual) translate(dpa
.getObject());
OWLLiteral object = (OWLLiteral) translate(dpa.getValue());
return dataFactory.getOWLDataPropertyAssertionAxiom(property,
subject, object);
}
return null;
}
/***
* Translates from assertion objects into
*
* @param constant
* @return
*/
public OWLPropertyAssertionObject translate(Constant constant) {
OWLPropertyAssertionObject result = null;
if (constant instanceof URIConstant) {
result = dataFactory.getOWLNamedIndividual(IRI
.create(((URIConstant) constant).getURI().toString()));
} else if (constant instanceof BNode) {
result = dataFactory.getOWLAnonymousIndividual(((BNode) constant)
.getName());
} else if (constant instanceof ValueConstant) {
ValueConstant v = (ValueConstant) constant;
String value = v.getValue();
if (value == null) {
result = null;
} else if (v.getType() == COL_TYPE.BOOLEAN) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_BOOLEAN);
} else if (v.getType() == COL_TYPE.DATETIME) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DATE_TIME);
} else if (v.getType() == COL_TYPE.DECIMAL) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DECIMAL);
} else if (v.getType() == COL_TYPE.DOUBLE) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DOUBLE);
} else if (v.getType() == COL_TYPE.INTEGER) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_INTEGER);
} else if (v.getType() == COL_TYPE.LITERAL) {
- if (v.getLanguage() == null || !v.getLanguage().equals("")) {
- result = dataFactory.getOWLLiteral(value, v.getLanguage());
- } else {
- result = dataFactory.getOWLLiteral(value,
- OWL2Datatype.RDF_PLAIN_LITERAL);
- }
+ result = dataFactory.getOWLLiteral(value,
+ OWL2Datatype.RDF_PLAIN_LITERAL);
+ } else if (v.getType() == COL_TYPE.LITERAL_LANG) {
+ result = dataFactory.getOWLLiteral(value,
+ v.getLanguage());
} else if (v.getType() == COL_TYPE.STRING) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_STRING);
} else {
throw new IllegalArgumentException(v.getType().toString());
}
} else if (constant == null) {
return null;
} else {
throw new IllegalArgumentException(constant.getClass().toString());
}
return result;
}
}
| true | true | public OWLPropertyAssertionObject translate(Constant constant) {
OWLPropertyAssertionObject result = null;
if (constant instanceof URIConstant) {
result = dataFactory.getOWLNamedIndividual(IRI
.create(((URIConstant) constant).getURI().toString()));
} else if (constant instanceof BNode) {
result = dataFactory.getOWLAnonymousIndividual(((BNode) constant)
.getName());
} else if (constant instanceof ValueConstant) {
ValueConstant v = (ValueConstant) constant;
String value = v.getValue();
if (value == null) {
result = null;
} else if (v.getType() == COL_TYPE.BOOLEAN) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_BOOLEAN);
} else if (v.getType() == COL_TYPE.DATETIME) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DATE_TIME);
} else if (v.getType() == COL_TYPE.DECIMAL) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DECIMAL);
} else if (v.getType() == COL_TYPE.DOUBLE) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DOUBLE);
} else if (v.getType() == COL_TYPE.INTEGER) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_INTEGER);
} else if (v.getType() == COL_TYPE.LITERAL) {
if (v.getLanguage() == null || !v.getLanguage().equals("")) {
result = dataFactory.getOWLLiteral(value, v.getLanguage());
} else {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.RDF_PLAIN_LITERAL);
}
} else if (v.getType() == COL_TYPE.STRING) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_STRING);
} else {
throw new IllegalArgumentException(v.getType().toString());
}
} else if (constant == null) {
return null;
} else {
throw new IllegalArgumentException(constant.getClass().toString());
}
return result;
}
| public OWLPropertyAssertionObject translate(Constant constant) {
OWLPropertyAssertionObject result = null;
if (constant instanceof URIConstant) {
result = dataFactory.getOWLNamedIndividual(IRI
.create(((URIConstant) constant).getURI().toString()));
} else if (constant instanceof BNode) {
result = dataFactory.getOWLAnonymousIndividual(((BNode) constant)
.getName());
} else if (constant instanceof ValueConstant) {
ValueConstant v = (ValueConstant) constant;
String value = v.getValue();
if (value == null) {
result = null;
} else if (v.getType() == COL_TYPE.BOOLEAN) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_BOOLEAN);
} else if (v.getType() == COL_TYPE.DATETIME) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DATE_TIME);
} else if (v.getType() == COL_TYPE.DECIMAL) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DECIMAL);
} else if (v.getType() == COL_TYPE.DOUBLE) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_DOUBLE);
} else if (v.getType() == COL_TYPE.INTEGER) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_INTEGER);
} else if (v.getType() == COL_TYPE.LITERAL) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.RDF_PLAIN_LITERAL);
} else if (v.getType() == COL_TYPE.LITERAL_LANG) {
result = dataFactory.getOWLLiteral(value,
v.getLanguage());
} else if (v.getType() == COL_TYPE.STRING) {
result = dataFactory.getOWLLiteral(value,
OWL2Datatype.XSD_STRING);
} else {
throw new IllegalArgumentException(v.getType().toString());
}
} else if (constant == null) {
return null;
} else {
throw new IllegalArgumentException(constant.getClass().toString());
}
return result;
}
|
diff --git a/src/helperclasses/AnnotationWriter.java b/src/helperclasses/AnnotationWriter.java
index 40fa044..1715ff7 100644
--- a/src/helperclasses/AnnotationWriter.java
+++ b/src/helperclasses/AnnotationWriter.java
@@ -1,188 +1,189 @@
package helperclasses;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import annotationclasses.DocInfoAnnotation;
import annotationclasses.EventAnnotation;
import annotationclasses.LinkInfoAnnotation;
import dataclasses.DocInfo;
import dataclasses.EventInfo;
import dataclasses.LinkInfo;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.time.TimeAnnotations.TimexAnnotation;
import edu.stanford.nlp.time.Timex;
import edu.stanford.nlp.time.XMLUtils;
import edu.stanford.nlp.util.CoreMap;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class AnnotationWriter {
public static final String HEADER = "<?xml version=\"1.0\" ?>\n"
+ "<TimeML xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:noNamespaceSchemaLocation=\"http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd\">\n\n";
public static final String FOOTER = "</TimeML>\n\n";
/*
* Taken from http://www.java2s.com/Code/Java/Data-Type/Returnstrueifspecifiedcharacterisapunctuationcharacter.htm
*/
private static boolean isPunctuation(char c) {
return c == ','
|| c == '.'
|| c == '!'
|| c == '?'
|| c == ':'
|| c == ';'
|| c == '"'
|| c == '\''
|| c == '`';
}
private static void writeText(Annotation annotation, BufferedWriter out,
ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException {
Element textElem = createTextElement(annotation, events, links);
String s = XMLUtils.nodeToString(textElem, false);
out.write(s + "\n");
}
private static Element createTextElement(Annotation annotation,
ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException {
// Link ID assignment happens here
int nextLinkID = 0;
// Keep track of whether we're inside a tag
String curType = "";
Timex curTimex = null;
Element element = XMLUtils.createElement("TEXT");
List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
int tid = 1;
for(CoreMap sentence: sentences) {
List<CoreLabel> tokens = sentence.get(TokensAnnotation.class);
for (CoreLabel token: tokens) {
// Get information from token
Timex timex = token.get(TimexAnnotation.class);
EventInfo event = token.get(EventAnnotation.class);
LinkInfo link = token.get(LinkInfoAnnotation.class);
String text = token.get(CoreAnnotations.OriginalTextAnnotation.class);
//TODO fix this, and in general have better whitespace recovery
String space = (isPunctuation(text.charAt(0)) ? "" : " ");
Node tokenNode = null;
// Handle if this is a timex
if (timex != null) {
if (!timex.equals(curTimex)) {
// TODO: use timex tid as is once fixed in SUTime
Element timexElem = timex.toXmlElement();
timexElem.setAttribute("tid", "t" + tid);
tid++;
tokenNode = timexElem;
curType = timex.timexType();
curTimex = timex;
}
// Handle if this is an event
- } else if (event != null && !curType.equals(event.currEventType)) {
+ } else if (event != null /*&& !curType.equals(event.currEventType)*/) {
+ // TODO: Handle events with multiple tokens?
Element eventElem = XMLUtils.createElement("EVENT");
eventElem.setAttribute("eid", event.currEventId);
eventElem.setAttribute("class", event.currEventType);
eventElem.setTextContent(text);
tokenNode = eventElem;
curType = event.currEventType;
curTimex = null;
events.add(event);
// Handle normal tokens
} else {
tokenNode = XMLUtils.createTextNode(space + text);
curType = "";
curTimex = null;
}
if (tokenNode != null) {
if (!curType.isEmpty()) {
element.appendChild(XMLUtils.createTextNode(" "));
}
element.appendChild(tokenNode);
}
// Handle links
if (link != null) {
link.id = "l" + (nextLinkID++);
links.add(link);
}
}
}
return element;
}
private static void writeEventInstances(ArrayList<EventInfo> events, BufferedWriter out)
throws IOException {
for (EventInfo event: events) {
out.write("<MAKEINSTANCE eventID=\"" + event.currEventId
+ "\" eiid=\"" + event.currEiid + "\" tense=\"" + event.tense
+ "\" aspect=\"" + event.aspect + "\" polarity=\"" + event.polarity
+ "\" pos=\"" + event.pos + "\"/>\n");
}
}
private static void writeTimexEventLinks(ArrayList<LinkInfo> links, BufferedWriter out)
throws IOException {
for (LinkInfo link: links) {
String instanceString = "";
if (link.time != null)
instanceString = "timeID=\"" + link.time.currTimeId + "\"";
else
instanceString = "eventInstanceID=\"" + link.eventInstance.currEiid + "\"";
out.write("<TLINK lid=\"" + link.id + "\" relType=\"" + link.type
+ "\" " + instanceString + " relatedToEventInstance=\"" + link.relatedTo.currEiid
+ "\" origin=\"USER\"/>\n"); //TODO fix origin
}
}
public static Element createElement(String tag, String text) {
Element elem = XMLUtils.createElement(tag);
elem.setTextContent(text);
return elem;
}
public static void writeElement(BufferedWriter out, String tag, String text) throws IOException {
Element elem = createElement(tag, text);
String s = XMLUtils.nodeToString(elem, false);
out.write(s + "\n");
}
public static void writeAnnotation(Annotation annotation, BufferedWriter out)
throws IOException {
ArrayList<EventInfo> events = new ArrayList<EventInfo>();
ArrayList<LinkInfo> links = new ArrayList<LinkInfo>();
// Get the auxiliary information associated with this document
DocInfo info = annotation.get(DocInfoAnnotation.class);
out.write(HEADER);
out.write("<DOCID>" + info.id + "</DOCID>\n\n");
out.write("<DCT>" + info.dct + "</DCT>\n\n");
writeElement(out, "TITLE", info.title);
writeElement(out, "EXTRAINFO", info.extra);
writeText(annotation, out, events, links);
writeEventInstances(events, out);
writeTimexEventLinks(links, out);
out.write(FOOTER);
}
}
| true | true | private static Element createTextElement(Annotation annotation,
ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException {
// Link ID assignment happens here
int nextLinkID = 0;
// Keep track of whether we're inside a tag
String curType = "";
Timex curTimex = null;
Element element = XMLUtils.createElement("TEXT");
List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
int tid = 1;
for(CoreMap sentence: sentences) {
List<CoreLabel> tokens = sentence.get(TokensAnnotation.class);
for (CoreLabel token: tokens) {
// Get information from token
Timex timex = token.get(TimexAnnotation.class);
EventInfo event = token.get(EventAnnotation.class);
LinkInfo link = token.get(LinkInfoAnnotation.class);
String text = token.get(CoreAnnotations.OriginalTextAnnotation.class);
//TODO fix this, and in general have better whitespace recovery
String space = (isPunctuation(text.charAt(0)) ? "" : " ");
Node tokenNode = null;
// Handle if this is a timex
if (timex != null) {
if (!timex.equals(curTimex)) {
// TODO: use timex tid as is once fixed in SUTime
Element timexElem = timex.toXmlElement();
timexElem.setAttribute("tid", "t" + tid);
tid++;
tokenNode = timexElem;
curType = timex.timexType();
curTimex = timex;
}
// Handle if this is an event
} else if (event != null && !curType.equals(event.currEventType)) {
Element eventElem = XMLUtils.createElement("EVENT");
eventElem.setAttribute("eid", event.currEventId);
eventElem.setAttribute("class", event.currEventType);
eventElem.setTextContent(text);
tokenNode = eventElem;
curType = event.currEventType;
curTimex = null;
events.add(event);
// Handle normal tokens
} else {
tokenNode = XMLUtils.createTextNode(space + text);
curType = "";
curTimex = null;
}
if (tokenNode != null) {
if (!curType.isEmpty()) {
element.appendChild(XMLUtils.createTextNode(" "));
}
element.appendChild(tokenNode);
}
// Handle links
if (link != null) {
link.id = "l" + (nextLinkID++);
links.add(link);
}
}
}
return element;
}
| private static Element createTextElement(Annotation annotation,
ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException {
// Link ID assignment happens here
int nextLinkID = 0;
// Keep track of whether we're inside a tag
String curType = "";
Timex curTimex = null;
Element element = XMLUtils.createElement("TEXT");
List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
int tid = 1;
for(CoreMap sentence: sentences) {
List<CoreLabel> tokens = sentence.get(TokensAnnotation.class);
for (CoreLabel token: tokens) {
// Get information from token
Timex timex = token.get(TimexAnnotation.class);
EventInfo event = token.get(EventAnnotation.class);
LinkInfo link = token.get(LinkInfoAnnotation.class);
String text = token.get(CoreAnnotations.OriginalTextAnnotation.class);
//TODO fix this, and in general have better whitespace recovery
String space = (isPunctuation(text.charAt(0)) ? "" : " ");
Node tokenNode = null;
// Handle if this is a timex
if (timex != null) {
if (!timex.equals(curTimex)) {
// TODO: use timex tid as is once fixed in SUTime
Element timexElem = timex.toXmlElement();
timexElem.setAttribute("tid", "t" + tid);
tid++;
tokenNode = timexElem;
curType = timex.timexType();
curTimex = timex;
}
// Handle if this is an event
} else if (event != null /*&& !curType.equals(event.currEventType)*/) {
// TODO: Handle events with multiple tokens?
Element eventElem = XMLUtils.createElement("EVENT");
eventElem.setAttribute("eid", event.currEventId);
eventElem.setAttribute("class", event.currEventType);
eventElem.setTextContent(text);
tokenNode = eventElem;
curType = event.currEventType;
curTimex = null;
events.add(event);
// Handle normal tokens
} else {
tokenNode = XMLUtils.createTextNode(space + text);
curType = "";
curTimex = null;
}
if (tokenNode != null) {
if (!curType.isEmpty()) {
element.appendChild(XMLUtils.createTextNode(" "));
}
element.appendChild(tokenNode);
}
// Handle links
if (link != null) {
link.id = "l" + (nextLinkID++);
links.add(link);
}
}
}
return element;
}
|
diff --git a/app/controllers/Account.java b/app/controllers/Account.java
index 00583f0..be8a13e 100644
--- a/app/controllers/Account.java
+++ b/app/controllers/Account.java
@@ -1,63 +1,63 @@
package controllers;
import static play.libs.Json.toJson;
import java.util.ArrayList;
import models.AccountModel;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import service.ConnectionManager;
import views.html.index;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
public class Account extends Controller{
private static ArrayList<AccountModel> amList;
public static Result searchAccount(){
Form<AccountModel> form = form(AccountModel.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(index.render("Please enter the account name", form));
}else{
AccountModel account = form.get();
PartnerConnection connection = ConnectionManager.getConnectionManager().getConnection();
System.out.println("connection : " + connection);
QueryResult result = null;
try {
System.out.println("before query : " + account.name);
result = connection.query("Select Id, Name, BillingCity, BillingState from Account where Name like '%" + account.name + "%'");
System.out.println("Records found for " + account.name +": "+result.getSize());
} catch (ConnectionException e) {
e.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("NullPointerException ");
}
if(result!=null){
SObject[] sObjList = result.getRecords();
amList = new ArrayList<AccountModel>();
for(int i=0; i<sObjList.length; i++){
SObject acc = sObjList[i];
AccountModel am = new AccountModel();
am.id = acc.getId();
- am.name = ""+acc.getField("Name");
- am.billingCity = ""+acc.getField("BillingCity");
- am.billingState = ""+acc.getField("BillingState");
+ am.name = ""+acc.getField("Name");
+ am.billingCity = (String) (acc.getField("BillingCity")!=null ? acc.getField("BillingCity") : "");
+ am.billingState = (String) (acc.getField("BillingState")!=null ? acc.getField("BillingState") : "");
System.out.println("adding to array : " + am.id + " " + am.name + " of " + am.billingCity + ", " + am.billingState);
amList.add(am);
}
}
}
return redirect(routes.Application.index2());
}
public static Result getAccounts(){
return ok(toJson(amList));
}
}
| true | true | public static Result searchAccount(){
Form<AccountModel> form = form(AccountModel.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(index.render("Please enter the account name", form));
}else{
AccountModel account = form.get();
PartnerConnection connection = ConnectionManager.getConnectionManager().getConnection();
System.out.println("connection : " + connection);
QueryResult result = null;
try {
System.out.println("before query : " + account.name);
result = connection.query("Select Id, Name, BillingCity, BillingState from Account where Name like '%" + account.name + "%'");
System.out.println("Records found for " + account.name +": "+result.getSize());
} catch (ConnectionException e) {
e.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("NullPointerException ");
}
if(result!=null){
SObject[] sObjList = result.getRecords();
amList = new ArrayList<AccountModel>();
for(int i=0; i<sObjList.length; i++){
SObject acc = sObjList[i];
AccountModel am = new AccountModel();
am.id = acc.getId();
am.name = ""+acc.getField("Name");
am.billingCity = ""+acc.getField("BillingCity");
am.billingState = ""+acc.getField("BillingState");
System.out.println("adding to array : " + am.id + " " + am.name + " of " + am.billingCity + ", " + am.billingState);
amList.add(am);
}
}
}
return redirect(routes.Application.index2());
}
| public static Result searchAccount(){
Form<AccountModel> form = form(AccountModel.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(index.render("Please enter the account name", form));
}else{
AccountModel account = form.get();
PartnerConnection connection = ConnectionManager.getConnectionManager().getConnection();
System.out.println("connection : " + connection);
QueryResult result = null;
try {
System.out.println("before query : " + account.name);
result = connection.query("Select Id, Name, BillingCity, BillingState from Account where Name like '%" + account.name + "%'");
System.out.println("Records found for " + account.name +": "+result.getSize());
} catch (ConnectionException e) {
e.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("NullPointerException ");
}
if(result!=null){
SObject[] sObjList = result.getRecords();
amList = new ArrayList<AccountModel>();
for(int i=0; i<sObjList.length; i++){
SObject acc = sObjList[i];
AccountModel am = new AccountModel();
am.id = acc.getId();
am.name = ""+acc.getField("Name");
am.billingCity = (String) (acc.getField("BillingCity")!=null ? acc.getField("BillingCity") : "");
am.billingState = (String) (acc.getField("BillingState")!=null ? acc.getField("BillingState") : "");
System.out.println("adding to array : " + am.id + " " + am.name + " of " + am.billingCity + ", " + am.billingState);
amList.add(am);
}
}
}
return redirect(routes.Application.index2());
}
|
diff --git a/src/com/untamedears/citadel/command/commands/JoinCommand.java b/src/com/untamedears/citadel/command/commands/JoinCommand.java
index 0f8654c..0929563 100644
--- a/src/com/untamedears/citadel/command/commands/JoinCommand.java
+++ b/src/com/untamedears/citadel/command/commands/JoinCommand.java
@@ -1,70 +1,71 @@
package com.untamedears.citadel.command.commands;
import static com.untamedears.citadel.Utility.sendMessage;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.untamedears.citadel.Citadel;
import com.untamedears.citadel.GroupManager;
import com.untamedears.citadel.MemberManager;
import com.untamedears.citadel.command.PlayerCommand;
import com.untamedears.citadel.entity.Faction;
/**
* User: JonnyD
* Date: 7/18/12
* Time: 11:57 PM
*/
public class JoinCommand extends PlayerCommand {
public JoinCommand() {
super("Join Group");
setDescription("Joins a group");
setUsage("/ctjoin �8<group-name> <password>");
setArgumentRange(2,2);
setIdentifiers(new String[] {"ctjoin", "ctj"});
}
public boolean execute(CommandSender sender, String[] args) {
String groupName = args[0];
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String playerName = sender.getName();
if(group.isFounder(playerName)){
sendMessage(sender, ChatColor.RED, "You are already owner of the group %s", groupName);
return true;
}
if(group.isMember(playerName)){
sendMessage(sender, ChatColor.RED, "You are already a member of the group %s", groupName);
return true;
}
if(group.isModerator(playerName)){
sendMessage(sender, ChatColor.RED, "You are already a moderator of the group %s", groupName);
}
if(group.getPassword() == null
|| group.getPassword().isEmpty()
|| group.getPassword().equalsIgnoreCase("")
|| group.getPassword().equalsIgnoreCase("NULL")){
sendMessage(sender, ChatColor.RED, "Group is not joinable");
return true;
}
String password = args[1];
if(!group.getPassword().equalsIgnoreCase(password)){
sendMessage(sender, ChatColor.RED, "Incorrect password");
return true;
}
groupManager.addMemberToGroup(groupName, playerName);
sendMessage(sender, ChatColor.GREEN, "You have joined %s", groupName);
MemberManager memberManager = Citadel.getMemberManager();
- if(memberManager.isOnline(playerName)){
- sendMessage(memberManager.getOnlinePlayer(group.getFounder()), ChatColor.YELLOW, "%s has joined %s", playerName, groupName);
+ String founderName = group.getFounder();
+ if(memberManager.isOnline(founderName)){
+ sendMessage(memberManager.getOnlinePlayer(founderName), ChatColor.YELLOW, "%s has joined %s", playerName, groupName);
}
return true;
}
}
| true | true | public boolean execute(CommandSender sender, String[] args) {
String groupName = args[0];
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String playerName = sender.getName();
if(group.isFounder(playerName)){
sendMessage(sender, ChatColor.RED, "You are already owner of the group %s", groupName);
return true;
}
if(group.isMember(playerName)){
sendMessage(sender, ChatColor.RED, "You are already a member of the group %s", groupName);
return true;
}
if(group.isModerator(playerName)){
sendMessage(sender, ChatColor.RED, "You are already a moderator of the group %s", groupName);
}
if(group.getPassword() == null
|| group.getPassword().isEmpty()
|| group.getPassword().equalsIgnoreCase("")
|| group.getPassword().equalsIgnoreCase("NULL")){
sendMessage(sender, ChatColor.RED, "Group is not joinable");
return true;
}
String password = args[1];
if(!group.getPassword().equalsIgnoreCase(password)){
sendMessage(sender, ChatColor.RED, "Incorrect password");
return true;
}
groupManager.addMemberToGroup(groupName, playerName);
sendMessage(sender, ChatColor.GREEN, "You have joined %s", groupName);
MemberManager memberManager = Citadel.getMemberManager();
if(memberManager.isOnline(playerName)){
sendMessage(memberManager.getOnlinePlayer(group.getFounder()), ChatColor.YELLOW, "%s has joined %s", playerName, groupName);
}
return true;
}
| public boolean execute(CommandSender sender, String[] args) {
String groupName = args[0];
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String playerName = sender.getName();
if(group.isFounder(playerName)){
sendMessage(sender, ChatColor.RED, "You are already owner of the group %s", groupName);
return true;
}
if(group.isMember(playerName)){
sendMessage(sender, ChatColor.RED, "You are already a member of the group %s", groupName);
return true;
}
if(group.isModerator(playerName)){
sendMessage(sender, ChatColor.RED, "You are already a moderator of the group %s", groupName);
}
if(group.getPassword() == null
|| group.getPassword().isEmpty()
|| group.getPassword().equalsIgnoreCase("")
|| group.getPassword().equalsIgnoreCase("NULL")){
sendMessage(sender, ChatColor.RED, "Group is not joinable");
return true;
}
String password = args[1];
if(!group.getPassword().equalsIgnoreCase(password)){
sendMessage(sender, ChatColor.RED, "Incorrect password");
return true;
}
groupManager.addMemberToGroup(groupName, playerName);
sendMessage(sender, ChatColor.GREEN, "You have joined %s", groupName);
MemberManager memberManager = Citadel.getMemberManager();
String founderName = group.getFounder();
if(memberManager.isOnline(founderName)){
sendMessage(memberManager.getOnlinePlayer(founderName), ChatColor.YELLOW, "%s has joined %s", playerName, groupName);
}
return true;
}
|
diff --git a/src/com/teamglokk/muni/commands/OfficerCommand.java b/src/com/teamglokk/muni/commands/OfficerCommand.java
index 3077a83..496bf65 100644
--- a/src/com/teamglokk/muni/commands/OfficerCommand.java
+++ b/src/com/teamglokk/muni/commands/OfficerCommand.java
@@ -1,502 +1,504 @@
/*
* Muni
* Copyright (C) 2013 bobbshields <https://github.com/xiebozhi/Muni> and 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Binary releases are available freely at <http://dev.bukkit.org/server-mods/muni/>.
*/
package com.teamglokk.muni.commands;
import com.teamglokk.muni.Citizen;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.teamglokk.muni.Muni;
import com.teamglokk.muni.Town;
import org.bukkit.ChatColor;
/**
* Handler for the /town command.
* @author BobbShields
*/
public class OfficerCommand implements CommandExecutor {
private Muni plugin;
private Player officer;
public OfficerCommand (Muni instance){
plugin = instance;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
String [] args = plugin.trimSplit(split);
if (!(sender instanceof Player)) {
sender.sendMessage("You cannot send deputy or mayor commands from the console");
return true;
}
officer = (Player) sender;
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy") ){
officer.sendMessage("You do not have permission to run /deputy subcommands");
return true;
}
if (args.length == 0){ //tested and working - 18 Feb 13
displayHelp(sender, command.getName() );
return true;
} else if (args[0].equalsIgnoreCase("help") ) { //tested and working - 18 Feb 13
displayHelp(sender, command.getName() );
return true;
} else if (args[0].equalsIgnoreCase("invite")) { //tested and working - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if (temp.invite( args[1],officer) ){
temp.messageOfficers("An invitation to "+args[1]+" was sent by "+officer.getName() );
if (plugin.isOnline(args[1]) ) {
plugin.getServer().getPlayer(args[1]).sendMessage("You have been invited to "
+temp.getName()+". Do /town accept OR /town leave");
}
}
return true;
} else if (args[0].equalsIgnoreCase("decline")) { //not tested - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("/deputy decline <applicant>");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
temp.declineApplication( args[1],officer );
return true;
} else if (args[0].equalsIgnoreCase("accept") ) { //tested and working - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("/deputy accept <applicant>");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
temp.acceptApplication(args[1], officer);
return true;
} else if (args[0].equalsIgnoreCase("checkTaxes")) {
Town temp = plugin.getTownFromCitizen(officer.getName() );
temp.checkTaxes(officer, args[1] );
return true;
} else if (args[0].equalsIgnoreCase("setTax")) {
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ||
!plugin.econwrapper.hasPerm(officer, "muni.mayor") ) {
officer.sendMessage("You do not have permission to set the taxs");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
try {
if (temp.isOfficer(officer ) ){
temp.setTaxRate( plugin.parseD( args[1] ) );
temp.announce(officer.getName()+" has set the tax rate for "+temp.getName()+ " to "+ args[1] );
} else{ officer.sendMessage("You are not an officer of "+temp.getName() ); }
return true;
} catch (Exception ex) {
officer.sendMessage("You should write an actual number next time");
return true;
}
} else if (args[0].equalsIgnoreCase("setItemTax")) {
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ||
!plugin.econwrapper.hasPerm(officer, "muni.mayor") ) {
officer.sendMessage("You do not have permission to set the taxs");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
try {
if (temp.isOfficer(officer ) ){
temp.setItemTaxRate( plugin.parseI( args[1] ) );
temp.announce(officer.getName()+" has set the item tax rate for "+temp.getName()+ " to "+ args[1] );
} else{ officer.sendMessage("You are not an officer of "+temp.getName() ); }
return true;
} catch (Exception ex) {
officer.sendMessage("You should write an actual number next time");
return true;
}
} else if (args[0].equalsIgnoreCase("kick")) { //Worked on bugs - 19 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.removeCitizen(args[1], officer ) ){
}
return true;
} else if (args[0].equalsIgnoreCase("resign")) {
if (args.length != 1) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) {
temp.resignMayor(officer);
return true;
} else if ( temp.isDeputy(officer) ) {
temp.resignDeputy(officer);
return true;
}
} else if (args[0].equalsIgnoreCase("announce")) {
if (args.length == 1) {
officer.sendMessage("/deputy announce <YOUR MSG HERE>");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isOfficer(officer) ) {
String msg = ChatColor.DARK_AQUA+"["+temp.getName()+"] "+ChatColor.YELLOW;
for (int i =1; i<args.length; i++ ){
msg = msg + args[i] +" ";
}
temp.announce(msg);
return true;
}
} else if (args[0].equalsIgnoreCase("bank")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
switch (args.length){
case 1:
if (plugin.isCitizen(officer) ) {
plugin.getTown(plugin.getTownName( officer.getName() ) ).checkTownBank(officer);
} else {officer.sendMessage("You are not part of a town"); }
break;
case 2:
temp.checkTownBank(officer);
break;
case 3:
if (args[1].equalsIgnoreCase("deposit") || args[1].equalsIgnoreCase("d") ){
double amount = plugin.parseD( args[2] );
if (temp.tb_deposit(officer, amount ) ) {
plugin.out(officer,"You have deposited "+amount+" into your town's bank" );
plugin.out(officer,"Your personal balance is now: "+plugin.econwrapper.getBalance(officer) );
temp.checkTownBank(officer);
}
else {
plugin.out(officer,"You don't have enough to deposit");
}
return true;
} else if (args[1].equalsIgnoreCase("withdraw") || args[1].equalsIgnoreCase("w") ){
if ( !plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ) {
officer.sendMessage("You do not have permission to withdraw from the town bank");
return true;
}
double amount = plugin.parseD( args[2] );
if (temp.tb_withdraw(officer, amount) ) {
plugin.out(officer,"You have withdrawn "+amount+" from your town's bank" );
plugin.out(officer,"Your personal balance is now: "+plugin.econwrapper.getBalance(officer) );
temp.checkTownBank(officer);
} else {
plugin.out( sender,"The town bank didn't have enough to withdraw" );
}
} else if (args[1].equalsIgnoreCase("check") || args[1].equalsIgnoreCase("c") ){
temp.checkTownBank(officer);
} else {
- plugin.out(sender,"/town bank - ERROR (subcommand not recognized)");
+ plugin.out(sender,"/deputy bank - ERROR (subcommand not recognized)");
+ plugin.out(sender,"/deputy bank (check|withdraw|deposit)");
}
break;
default:
plugin.out(sender,"Invalid number of parameters");
return false;
}
return true;
}else if (args[0].equalsIgnoreCase("itembank")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
switch (args.length){
case 1:
plugin.getTown(plugin.getTownName( officer.getName() ) ).checkTownItemBank(officer);
break;
case 2:
temp.checkTownBank(officer);
break;
case 3:
if (args[1].equalsIgnoreCase("deposit") || args[1].equalsIgnoreCase("d") ){
int amount = plugin.parseI( args[2] );
if (temp.tb_depositItems(officer, amount ) ) {
plugin.out(officer,"You have deposited "+amount+" into your town's bank" );
temp.checkTownItemBank(officer);
}
else {
plugin.out(officer,"You don't have enough to deposit");
}
return true;
} else if (args[1].equalsIgnoreCase("withdraw") || args[1].equalsIgnoreCase("w") ){
if ( !plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ) {
officer.sendMessage("You do not have permission to withdraw from the town bank");
return true;
}
int amount = plugin.parseI( args[2] );
if (temp.tb_withdrawItems(officer, amount) ) {
plugin.out(officer,"You have withdrawn "+amount+" "+plugin.econwrapper.getRankupItemName()+
" from your town's bank" );
temp.checkTownBank(officer);
} else {
plugin.out( sender,"The town bank didn't have enough to withdraw" );
}
} else if (args[1].equalsIgnoreCase("check") || args[1].equalsIgnoreCase("c") ){
temp.checkTownBank(officer);
} else {
- plugin.out(sender,"/town bank - ERROR (subcommand not recognized)");
+ plugin.out(sender,"/deputy itemBank - ERROR (subcommand not recognized)");
+ plugin.out(sender,"/deputy itemBank (check|withdraw|deposit)");
}
break;
default:
plugin.out(sender,"Invalid number of parameters");
return false;
}
return true;
} else if ( args[0].equalsIgnoreCase("makePlot") || args[0].equalsIgnoreCase("makeSubRegion") ) {
if (args.length == 1) {
officer.sendMessage("This command will make a pre-sized plot around your location as the center");
officer.sendMessage("/deputy makePlot list");
officer.sendMessage("/deputy makePlot <type>");
return true;
}
if ( args[1].equalsIgnoreCase( "list" ) ){
officer.sendMessage("You may choose from the following types.");
officer.sendMessage("(if your current town rank allows it)");
officer.sendMessage("restaurant");
officer.sendMessage("hospital");
officer.sendMessage("arena");
officer.sendMessage("outpost");
officer.sendMessage("embassy");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
boolean test = false;
if ( temp.isOfficer(officer) ) {
if ( args[1].equalsIgnoreCase( "restaurant" ) ){
if (temp.paymentFromTB(plugin.getRestaurantCost(), 0, officer.getName(), "restaurant creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "restaurant" ) < plugin.townRanks[temp.getRank()].getRestaurants() ){
test = plugin.wgwrapper.makeRestaurant(temp, officer, temp.getName()+"_r");
} else { officer.sendMessage("Your town already has the max number of restaurants"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "hospital" ) ){
if (temp.paymentFromTB(plugin.getHospitalCost(), 0, officer.getName(), "hospital creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "hospital" ) < plugin.townRanks[temp.getRank()].getHospitals() ){
test = plugin.wgwrapper.makeHospital(temp, officer, temp.getName()+"_h");
} else { officer.sendMessage("Your town already has the max number of hospitals"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "arena" ) ){
if (temp.paymentFromTB(plugin.getArenaCost(), 0, officer.getName(), "arena creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "arena" ) < plugin.townRanks[temp.getRank()].getArenas() ){
test = plugin.wgwrapper.makeArena(temp, officer, temp.getName()+"_a");
} else { officer.sendMessage("Your town already has the max number of arenas"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "outpost" ) ){
if (temp.paymentFromTB(plugin.getOutpostCost(), 0, officer.getName(), "outpost creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "outpost" ) < plugin.townRanks[temp.getRank()].getOutposts() ){
test = plugin.wgwrapper.makeOutpost(temp, officer, temp.getName()+"_o");
} else { officer.sendMessage("Your town already has the max number of outposts"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "embassy" ) ){
if (temp.paymentFromTB(plugin.getEmbassyCost(), 0, officer.getName(), "embassy creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "embassy" ) < plugin.townRanks[temp.getRank()].getEmbassies() ){
test = plugin.wgwrapper.makeEmbassy(temp, officer, temp.getName()+"_e");
} else { officer.sendMessage("Your town already has the max number of embassies"); return true; }
} else { officer.sendMessage("Not enough money in the town bank. "); return true; }
}
if (test) {
officer.sendMessage("The sub-region was created successfully");
} else {
officer.sendMessage("There was a problem creating the sub-region");
}
}
return true;
}
// Mayor-only commands from here on out
if (!plugin.econwrapper.hasPerm(officer, "muni.mayor")){
officer.sendMessage("You do not have permission to do /mayor subcommands");
return true;
}
if (args[0].equalsIgnoreCase("makeBorder")) {
if (args.length == 1) {
officer.sendMessage("This makes the 25x25 town border centered at your current location");
officer.sendMessage("/mayor makeBorder confirm");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) { // NPE when no town
if ( args[1].equalsIgnoreCase( "confirm" ) ){
if ( plugin.wgwrapper.makeTownBorder(officer, temp ) > 0 ){
plugin.getServer().broadcastMessage("The "+temp.getName()+" town border has been created!");
} else {
officer.sendMessage("There was a problem ");
}
} else { officer.sendMessage("You must do /mayor makeBorder confirm"); }
}
return true;
} else if (args[0].equalsIgnoreCase("found") ||
args[0].equalsIgnoreCase("charter") ||args[0].equalsIgnoreCase("add")) {
if (args.length == 1 || args.length > 3) {
officer.sendMessage("/mayor found <TownName>");
return true;
}
if (plugin.isCitizen(officer) ){
officer.sendMessage("You are already a member of another town.");
return true;
}
if (plugin.isTown(args[1]) ){
officer.sendMessage("That town already exists. Please choose another name");
return true;
}
if ( args.length == 2 ) {
officer.sendMessage("Are you sure you want to name your town "+args[1]+"?");
officer.sendMessage("It is permanent and you may not change it later!!!");
officer.sendMessage("It cannot contain spaces. Be sure your capitalization is how you want it");
officer.sendMessage("To confirm do /mayor found "+args[1]+" confirm");
return true;
}
if ( args.length != 3) { return true; }
if (!args[2].equalsIgnoreCase("confirm") ){
return true;
}
if (plugin.econwrapper.pay(officer, plugin.townRanks[1].getMoneyCost(),
plugin.townRanks[1].getItemCost(), "Found: "+args[1] ) ){
Town t = new Town( plugin, args[1], officer.getName(),officer.getWorld().getName() );
plugin.towns.put(t.getName(), t );
plugin.allCitizens.put(officer.getName(), t.getName() );
t.admin_makeMayor(officer.getName() );
t.saveToDB();
officer.sendMessage("You have founded "+t.getName());
plugin.getServer().broadcastMessage(t.getName()+" is now a "+
t.getTitle()+" thanks to its new mayor " +t.getMayor()+"!" );
} else { officer.sendMessage("Could not start the town due to insufficent resources" ); }
return true;
} else if ( args[0].equalsIgnoreCase("renameTown") ) {
if (args.length == 1) {
officer.sendMessage("This command will rename your town");
officer.sendMessage("/mayor renameTown <newName>");
return true;
}
if ( args.length == 2 ){
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) {
//temp.renameTown(args[1]);
officer.sendMessage("Town names are currently permanent. Delete your town and re-make");
}
} else { officer.sendMessage("/mayor renameTown <newName>"); }
return true;
} else if (args[0].equalsIgnoreCase("delete")
|| args[0].equalsIgnoreCase("disband")) {
if (args.length == 1 ) {
officer.sendMessage("To confirm town deletion, do /mayor delete confirm");
return true;
}
if (args[1].equalsIgnoreCase("confirm") ){
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
plugin.wgwrapper.removeTown(temp.getName());
temp.removeAllTownCits(); //NPE somewhere
plugin.removeTown(temp.getName() ); //NPE somewhere
plugin.wgwrapper.deleteAllRegions(temp);
plugin.getServer().broadcastMessage(temp.getName()+
" and all its citizens were removed by the mayor, "+ officer.getName()+"!" );
} else { officer.sendMessage("To confirm town deletion, do /mayor delete confirm"); }
return true;
} else if (args[0].equalsIgnoreCase("deputize")) { // buggy but working on it - 19 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
if (!plugin.isCitizen(officer) ){
officer.sendMessage("You are not a citizen anywhere");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) ); //throwing NPE - 19 Feb 13
temp.makeDeputy( args[1] ,officer);
return true;
} else if (args[0].equalsIgnoreCase("rankup")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.rankup(officer) ){
plugin.getServer().broadcastMessage(temp.getName()+" has been ranked to "+
temp.getTitle()+" by " + officer.getName() );
}
displayHelp( officer, args[0] );
return true;
} else if (args[0].equalsIgnoreCase("expand")) {
if (args.length == 1 || args.length >3){
officer.sendMessage("You must specify a direction");
officer.sendMessage("north, south, east, or west");
officer.sendMessage("n,s,e,w");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
Double price = plugin.getExpansionCostMultiplier()*(temp.getExpansions()+1);
try {
if (!args[2].equalsIgnoreCase("confirm") ){
officer.sendMessage("The expansion will cost the town "+price+" "+
plugin.econwrapper.getCurrNamePlural()+".");
officer.sendMessage("To confirm do /mayor expand <direction> confirm ");
return true;
}
}
catch (ArrayIndexOutOfBoundsException ex ){
officer.sendMessage("To confirm do /mayor expand <direction> confirm ");
return true;
}
if ( temp.isMayor(officer) ){
if (temp.paymentFromTB(price, 0) ){
int area = plugin.wgwrapper.expandRegion(officer.getWorld().getName(),
temp.getName(), args[1], 10);
if ( area > 0 ){
temp.incrementExpansions();
temp.messageOfficers(price+" "+plugin.econwrapper.getCurrNamePlural()
+" has been deducted from the town bank for border expansion");
officer.sendMessage("The new area is "+area );
plugin.getServer().broadcastMessage(temp.getName()+" has expanded its borders ");
//log transaction here
} else { officer.sendMessage("You must specify {n,s,e,w}"); }
}
}
return true;
} else {
officer.sendMessage("[Muni] Input not understood.");
displayHelp( officer, args[0] );
return true;
}
}
private void displayHelp(CommandSender sender, String subcmd){
if (subcmd.equalsIgnoreCase("deputy") ){
plugin.out(sender, "Muni Deputy Help. You can do these commands:",ChatColor.LIGHT_PURPLE);
plugin.out(sender, "/deputy invite <playerName>");
plugin.out(sender, "/deputy accept <playerName");
plugin.out(sender, "/deputy decline <playerName>");
plugin.out(sender, "/deputy kick <playerName>");
plugin.out(sender, "/deputy resign");
plugin.out(sender, "/deputy makePlot <optional:list>");
plugin.out(sender, "/deputy setTax <money>");
plugin.out(sender, "/deputy setItemTax <sponges>");
plugin.out(sender, "**/deputy bank deposit/withdraw <amount>");
plugin.out(sender, "**/deputy itemBank deposit/withdraw <amount>");
plugin.out(sender, "** (with perm) ");
} else if (subcmd.equalsIgnoreCase("mayor") ){
plugin.out(sender, "Muni Mayor Help. You can do these commands:",ChatColor.LIGHT_PURPLE);
plugin.out(sender, "/mayor found <newTownName>");
plugin.out(sender, "/mayor makeBorder");
plugin.out(sender, "/mayor expand <dir> (dir = n, s, e, w)");
plugin.out(sender, "/mayor deputize <citizen>");
plugin.out(sender, "/mayor resign");
plugin.out(sender, "/mayor delete");
plugin.out(sender, "/mayor rankup");
plugin.out(sender, "***Mayors may also do all the deputy commands (/deputy help)");
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
String [] args = plugin.trimSplit(split);
if (!(sender instanceof Player)) {
sender.sendMessage("You cannot send deputy or mayor commands from the console");
return true;
}
officer = (Player) sender;
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy") ){
officer.sendMessage("You do not have permission to run /deputy subcommands");
return true;
}
if (args.length == 0){ //tested and working - 18 Feb 13
displayHelp(sender, command.getName() );
return true;
} else if (args[0].equalsIgnoreCase("help") ) { //tested and working - 18 Feb 13
displayHelp(sender, command.getName() );
return true;
} else if (args[0].equalsIgnoreCase("invite")) { //tested and working - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if (temp.invite( args[1],officer) ){
temp.messageOfficers("An invitation to "+args[1]+" was sent by "+officer.getName() );
if (plugin.isOnline(args[1]) ) {
plugin.getServer().getPlayer(args[1]).sendMessage("You have been invited to "
+temp.getName()+". Do /town accept OR /town leave");
}
}
return true;
} else if (args[0].equalsIgnoreCase("decline")) { //not tested - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("/deputy decline <applicant>");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
temp.declineApplication( args[1],officer );
return true;
} else if (args[0].equalsIgnoreCase("accept") ) { //tested and working - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("/deputy accept <applicant>");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
temp.acceptApplication(args[1], officer);
return true;
} else if (args[0].equalsIgnoreCase("checkTaxes")) {
Town temp = plugin.getTownFromCitizen(officer.getName() );
temp.checkTaxes(officer, args[1] );
return true;
} else if (args[0].equalsIgnoreCase("setTax")) {
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ||
!plugin.econwrapper.hasPerm(officer, "muni.mayor") ) {
officer.sendMessage("You do not have permission to set the taxs");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
try {
if (temp.isOfficer(officer ) ){
temp.setTaxRate( plugin.parseD( args[1] ) );
temp.announce(officer.getName()+" has set the tax rate for "+temp.getName()+ " to "+ args[1] );
} else{ officer.sendMessage("You are not an officer of "+temp.getName() ); }
return true;
} catch (Exception ex) {
officer.sendMessage("You should write an actual number next time");
return true;
}
} else if (args[0].equalsIgnoreCase("setItemTax")) {
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ||
!plugin.econwrapper.hasPerm(officer, "muni.mayor") ) {
officer.sendMessage("You do not have permission to set the taxs");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
try {
if (temp.isOfficer(officer ) ){
temp.setItemTaxRate( plugin.parseI( args[1] ) );
temp.announce(officer.getName()+" has set the item tax rate for "+temp.getName()+ " to "+ args[1] );
} else{ officer.sendMessage("You are not an officer of "+temp.getName() ); }
return true;
} catch (Exception ex) {
officer.sendMessage("You should write an actual number next time");
return true;
}
} else if (args[0].equalsIgnoreCase("kick")) { //Worked on bugs - 19 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.removeCitizen(args[1], officer ) ){
}
return true;
} else if (args[0].equalsIgnoreCase("resign")) {
if (args.length != 1) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) {
temp.resignMayor(officer);
return true;
} else if ( temp.isDeputy(officer) ) {
temp.resignDeputy(officer);
return true;
}
} else if (args[0].equalsIgnoreCase("announce")) {
if (args.length == 1) {
officer.sendMessage("/deputy announce <YOUR MSG HERE>");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isOfficer(officer) ) {
String msg = ChatColor.DARK_AQUA+"["+temp.getName()+"] "+ChatColor.YELLOW;
for (int i =1; i<args.length; i++ ){
msg = msg + args[i] +" ";
}
temp.announce(msg);
return true;
}
} else if (args[0].equalsIgnoreCase("bank")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
switch (args.length){
case 1:
if (plugin.isCitizen(officer) ) {
plugin.getTown(plugin.getTownName( officer.getName() ) ).checkTownBank(officer);
} else {officer.sendMessage("You are not part of a town"); }
break;
case 2:
temp.checkTownBank(officer);
break;
case 3:
if (args[1].equalsIgnoreCase("deposit") || args[1].equalsIgnoreCase("d") ){
double amount = plugin.parseD( args[2] );
if (temp.tb_deposit(officer, amount ) ) {
plugin.out(officer,"You have deposited "+amount+" into your town's bank" );
plugin.out(officer,"Your personal balance is now: "+plugin.econwrapper.getBalance(officer) );
temp.checkTownBank(officer);
}
else {
plugin.out(officer,"You don't have enough to deposit");
}
return true;
} else if (args[1].equalsIgnoreCase("withdraw") || args[1].equalsIgnoreCase("w") ){
if ( !plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ) {
officer.sendMessage("You do not have permission to withdraw from the town bank");
return true;
}
double amount = plugin.parseD( args[2] );
if (temp.tb_withdraw(officer, amount) ) {
plugin.out(officer,"You have withdrawn "+amount+" from your town's bank" );
plugin.out(officer,"Your personal balance is now: "+plugin.econwrapper.getBalance(officer) );
temp.checkTownBank(officer);
} else {
plugin.out( sender,"The town bank didn't have enough to withdraw" );
}
} else if (args[1].equalsIgnoreCase("check") || args[1].equalsIgnoreCase("c") ){
temp.checkTownBank(officer);
} else {
plugin.out(sender,"/town bank - ERROR (subcommand not recognized)");
}
break;
default:
plugin.out(sender,"Invalid number of parameters");
return false;
}
return true;
}else if (args[0].equalsIgnoreCase("itembank")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
switch (args.length){
case 1:
plugin.getTown(plugin.getTownName( officer.getName() ) ).checkTownItemBank(officer);
break;
case 2:
temp.checkTownBank(officer);
break;
case 3:
if (args[1].equalsIgnoreCase("deposit") || args[1].equalsIgnoreCase("d") ){
int amount = plugin.parseI( args[2] );
if (temp.tb_depositItems(officer, amount ) ) {
plugin.out(officer,"You have deposited "+amount+" into your town's bank" );
temp.checkTownItemBank(officer);
}
else {
plugin.out(officer,"You don't have enough to deposit");
}
return true;
} else if (args[1].equalsIgnoreCase("withdraw") || args[1].equalsIgnoreCase("w") ){
if ( !plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ) {
officer.sendMessage("You do not have permission to withdraw from the town bank");
return true;
}
int amount = plugin.parseI( args[2] );
if (temp.tb_withdrawItems(officer, amount) ) {
plugin.out(officer,"You have withdrawn "+amount+" "+plugin.econwrapper.getRankupItemName()+
" from your town's bank" );
temp.checkTownBank(officer);
} else {
plugin.out( sender,"The town bank didn't have enough to withdraw" );
}
} else if (args[1].equalsIgnoreCase("check") || args[1].equalsIgnoreCase("c") ){
temp.checkTownBank(officer);
} else {
plugin.out(sender,"/town bank - ERROR (subcommand not recognized)");
}
break;
default:
plugin.out(sender,"Invalid number of parameters");
return false;
}
return true;
} else if ( args[0].equalsIgnoreCase("makePlot") || args[0].equalsIgnoreCase("makeSubRegion") ) {
if (args.length == 1) {
officer.sendMessage("This command will make a pre-sized plot around your location as the center");
officer.sendMessage("/deputy makePlot list");
officer.sendMessage("/deputy makePlot <type>");
return true;
}
if ( args[1].equalsIgnoreCase( "list" ) ){
officer.sendMessage("You may choose from the following types.");
officer.sendMessage("(if your current town rank allows it)");
officer.sendMessage("restaurant");
officer.sendMessage("hospital");
officer.sendMessage("arena");
officer.sendMessage("outpost");
officer.sendMessage("embassy");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
boolean test = false;
if ( temp.isOfficer(officer) ) {
if ( args[1].equalsIgnoreCase( "restaurant" ) ){
if (temp.paymentFromTB(plugin.getRestaurantCost(), 0, officer.getName(), "restaurant creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "restaurant" ) < plugin.townRanks[temp.getRank()].getRestaurants() ){
test = plugin.wgwrapper.makeRestaurant(temp, officer, temp.getName()+"_r");
} else { officer.sendMessage("Your town already has the max number of restaurants"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "hospital" ) ){
if (temp.paymentFromTB(plugin.getHospitalCost(), 0, officer.getName(), "hospital creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "hospital" ) < plugin.townRanks[temp.getRank()].getHospitals() ){
test = plugin.wgwrapper.makeHospital(temp, officer, temp.getName()+"_h");
} else { officer.sendMessage("Your town already has the max number of hospitals"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "arena" ) ){
if (temp.paymentFromTB(plugin.getArenaCost(), 0, officer.getName(), "arena creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "arena" ) < plugin.townRanks[temp.getRank()].getArenas() ){
test = plugin.wgwrapper.makeArena(temp, officer, temp.getName()+"_a");
} else { officer.sendMessage("Your town already has the max number of arenas"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "outpost" ) ){
if (temp.paymentFromTB(plugin.getOutpostCost(), 0, officer.getName(), "outpost creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "outpost" ) < plugin.townRanks[temp.getRank()].getOutposts() ){
test = plugin.wgwrapper.makeOutpost(temp, officer, temp.getName()+"_o");
} else { officer.sendMessage("Your town already has the max number of outposts"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "embassy" ) ){
if (temp.paymentFromTB(plugin.getEmbassyCost(), 0, officer.getName(), "embassy creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "embassy" ) < plugin.townRanks[temp.getRank()].getEmbassies() ){
test = plugin.wgwrapper.makeEmbassy(temp, officer, temp.getName()+"_e");
} else { officer.sendMessage("Your town already has the max number of embassies"); return true; }
} else { officer.sendMessage("Not enough money in the town bank. "); return true; }
}
if (test) {
officer.sendMessage("The sub-region was created successfully");
} else {
officer.sendMessage("There was a problem creating the sub-region");
}
}
return true;
}
// Mayor-only commands from here on out
if (!plugin.econwrapper.hasPerm(officer, "muni.mayor")){
officer.sendMessage("You do not have permission to do /mayor subcommands");
return true;
}
if (args[0].equalsIgnoreCase("makeBorder")) {
if (args.length == 1) {
officer.sendMessage("This makes the 25x25 town border centered at your current location");
officer.sendMessage("/mayor makeBorder confirm");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) { // NPE when no town
if ( args[1].equalsIgnoreCase( "confirm" ) ){
if ( plugin.wgwrapper.makeTownBorder(officer, temp ) > 0 ){
plugin.getServer().broadcastMessage("The "+temp.getName()+" town border has been created!");
} else {
officer.sendMessage("There was a problem ");
}
} else { officer.sendMessage("You must do /mayor makeBorder confirm"); }
}
return true;
} else if (args[0].equalsIgnoreCase("found") ||
args[0].equalsIgnoreCase("charter") ||args[0].equalsIgnoreCase("add")) {
if (args.length == 1 || args.length > 3) {
officer.sendMessage("/mayor found <TownName>");
return true;
}
if (plugin.isCitizen(officer) ){
officer.sendMessage("You are already a member of another town.");
return true;
}
if (plugin.isTown(args[1]) ){
officer.sendMessage("That town already exists. Please choose another name");
return true;
}
if ( args.length == 2 ) {
officer.sendMessage("Are you sure you want to name your town "+args[1]+"?");
officer.sendMessage("It is permanent and you may not change it later!!!");
officer.sendMessage("It cannot contain spaces. Be sure your capitalization is how you want it");
officer.sendMessage("To confirm do /mayor found "+args[1]+" confirm");
return true;
}
if ( args.length != 3) { return true; }
if (!args[2].equalsIgnoreCase("confirm") ){
return true;
}
if (plugin.econwrapper.pay(officer, plugin.townRanks[1].getMoneyCost(),
plugin.townRanks[1].getItemCost(), "Found: "+args[1] ) ){
Town t = new Town( plugin, args[1], officer.getName(),officer.getWorld().getName() );
plugin.towns.put(t.getName(), t );
plugin.allCitizens.put(officer.getName(), t.getName() );
t.admin_makeMayor(officer.getName() );
t.saveToDB();
officer.sendMessage("You have founded "+t.getName());
plugin.getServer().broadcastMessage(t.getName()+" is now a "+
t.getTitle()+" thanks to its new mayor " +t.getMayor()+"!" );
} else { officer.sendMessage("Could not start the town due to insufficent resources" ); }
return true;
} else if ( args[0].equalsIgnoreCase("renameTown") ) {
if (args.length == 1) {
officer.sendMessage("This command will rename your town");
officer.sendMessage("/mayor renameTown <newName>");
return true;
}
if ( args.length == 2 ){
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) {
//temp.renameTown(args[1]);
officer.sendMessage("Town names are currently permanent. Delete your town and re-make");
}
} else { officer.sendMessage("/mayor renameTown <newName>"); }
return true;
} else if (args[0].equalsIgnoreCase("delete")
|| args[0].equalsIgnoreCase("disband")) {
if (args.length == 1 ) {
officer.sendMessage("To confirm town deletion, do /mayor delete confirm");
return true;
}
if (args[1].equalsIgnoreCase("confirm") ){
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
plugin.wgwrapper.removeTown(temp.getName());
temp.removeAllTownCits(); //NPE somewhere
plugin.removeTown(temp.getName() ); //NPE somewhere
plugin.wgwrapper.deleteAllRegions(temp);
plugin.getServer().broadcastMessage(temp.getName()+
" and all its citizens were removed by the mayor, "+ officer.getName()+"!" );
} else { officer.sendMessage("To confirm town deletion, do /mayor delete confirm"); }
return true;
} else if (args[0].equalsIgnoreCase("deputize")) { // buggy but working on it - 19 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
if (!plugin.isCitizen(officer) ){
officer.sendMessage("You are not a citizen anywhere");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) ); //throwing NPE - 19 Feb 13
temp.makeDeputy( args[1] ,officer);
return true;
} else if (args[0].equalsIgnoreCase("rankup")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.rankup(officer) ){
plugin.getServer().broadcastMessage(temp.getName()+" has been ranked to "+
temp.getTitle()+" by " + officer.getName() );
}
displayHelp( officer, args[0] );
return true;
} else if (args[0].equalsIgnoreCase("expand")) {
if (args.length == 1 || args.length >3){
officer.sendMessage("You must specify a direction");
officer.sendMessage("north, south, east, or west");
officer.sendMessage("n,s,e,w");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
Double price = plugin.getExpansionCostMultiplier()*(temp.getExpansions()+1);
try {
if (!args[2].equalsIgnoreCase("confirm") ){
officer.sendMessage("The expansion will cost the town "+price+" "+
plugin.econwrapper.getCurrNamePlural()+".");
officer.sendMessage("To confirm do /mayor expand <direction> confirm ");
return true;
}
}
catch (ArrayIndexOutOfBoundsException ex ){
officer.sendMessage("To confirm do /mayor expand <direction> confirm ");
return true;
}
if ( temp.isMayor(officer) ){
if (temp.paymentFromTB(price, 0) ){
int area = plugin.wgwrapper.expandRegion(officer.getWorld().getName(),
temp.getName(), args[1], 10);
if ( area > 0 ){
temp.incrementExpansions();
temp.messageOfficers(price+" "+plugin.econwrapper.getCurrNamePlural()
+" has been deducted from the town bank for border expansion");
officer.sendMessage("The new area is "+area );
plugin.getServer().broadcastMessage(temp.getName()+" has expanded its borders ");
//log transaction here
} else { officer.sendMessage("You must specify {n,s,e,w}"); }
}
}
return true;
} else {
officer.sendMessage("[Muni] Input not understood.");
displayHelp( officer, args[0] );
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
String [] args = plugin.trimSplit(split);
if (!(sender instanceof Player)) {
sender.sendMessage("You cannot send deputy or mayor commands from the console");
return true;
}
officer = (Player) sender;
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy") ){
officer.sendMessage("You do not have permission to run /deputy subcommands");
return true;
}
if (args.length == 0){ //tested and working - 18 Feb 13
displayHelp(sender, command.getName() );
return true;
} else if (args[0].equalsIgnoreCase("help") ) { //tested and working - 18 Feb 13
displayHelp(sender, command.getName() );
return true;
} else if (args[0].equalsIgnoreCase("invite")) { //tested and working - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if (temp.invite( args[1],officer) ){
temp.messageOfficers("An invitation to "+args[1]+" was sent by "+officer.getName() );
if (plugin.isOnline(args[1]) ) {
plugin.getServer().getPlayer(args[1]).sendMessage("You have been invited to "
+temp.getName()+". Do /town accept OR /town leave");
}
}
return true;
} else if (args[0].equalsIgnoreCase("decline")) { //not tested - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("/deputy decline <applicant>");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
temp.declineApplication( args[1],officer );
return true;
} else if (args[0].equalsIgnoreCase("accept") ) { //tested and working - 18 Feb 13
if (args.length != 2) {
officer.sendMessage("/deputy accept <applicant>");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
temp.acceptApplication(args[1], officer);
return true;
} else if (args[0].equalsIgnoreCase("checkTaxes")) {
Town temp = plugin.getTownFromCitizen(officer.getName() );
temp.checkTaxes(officer, args[1] );
return true;
} else if (args[0].equalsIgnoreCase("setTax")) {
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ||
!plugin.econwrapper.hasPerm(officer, "muni.mayor") ) {
officer.sendMessage("You do not have permission to set the taxs");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
try {
if (temp.isOfficer(officer ) ){
temp.setTaxRate( plugin.parseD( args[1] ) );
temp.announce(officer.getName()+" has set the tax rate for "+temp.getName()+ " to "+ args[1] );
} else{ officer.sendMessage("You are not an officer of "+temp.getName() ); }
return true;
} catch (Exception ex) {
officer.sendMessage("You should write an actual number next time");
return true;
}
} else if (args[0].equalsIgnoreCase("setItemTax")) {
if (!plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ||
!plugin.econwrapper.hasPerm(officer, "muni.mayor") ) {
officer.sendMessage("You do not have permission to set the taxs");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
try {
if (temp.isOfficer(officer ) ){
temp.setItemTaxRate( plugin.parseI( args[1] ) );
temp.announce(officer.getName()+" has set the item tax rate for "+temp.getName()+ " to "+ args[1] );
} else{ officer.sendMessage("You are not an officer of "+temp.getName() ); }
return true;
} catch (Exception ex) {
officer.sendMessage("You should write an actual number next time");
return true;
}
} else if (args[0].equalsIgnoreCase("kick")) { //Worked on bugs - 19 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.removeCitizen(args[1], officer ) ){
}
return true;
} else if (args[0].equalsIgnoreCase("resign")) {
if (args.length != 1) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) {
temp.resignMayor(officer);
return true;
} else if ( temp.isDeputy(officer) ) {
temp.resignDeputy(officer);
return true;
}
} else if (args[0].equalsIgnoreCase("announce")) {
if (args.length == 1) {
officer.sendMessage("/deputy announce <YOUR MSG HERE>");
return false;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isOfficer(officer) ) {
String msg = ChatColor.DARK_AQUA+"["+temp.getName()+"] "+ChatColor.YELLOW;
for (int i =1; i<args.length; i++ ){
msg = msg + args[i] +" ";
}
temp.announce(msg);
return true;
}
} else if (args[0].equalsIgnoreCase("bank")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
switch (args.length){
case 1:
if (plugin.isCitizen(officer) ) {
plugin.getTown(plugin.getTownName( officer.getName() ) ).checkTownBank(officer);
} else {officer.sendMessage("You are not part of a town"); }
break;
case 2:
temp.checkTownBank(officer);
break;
case 3:
if (args[1].equalsIgnoreCase("deposit") || args[1].equalsIgnoreCase("d") ){
double amount = plugin.parseD( args[2] );
if (temp.tb_deposit(officer, amount ) ) {
plugin.out(officer,"You have deposited "+amount+" into your town's bank" );
plugin.out(officer,"Your personal balance is now: "+plugin.econwrapper.getBalance(officer) );
temp.checkTownBank(officer);
}
else {
plugin.out(officer,"You don't have enough to deposit");
}
return true;
} else if (args[1].equalsIgnoreCase("withdraw") || args[1].equalsIgnoreCase("w") ){
if ( !plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ) {
officer.sendMessage("You do not have permission to withdraw from the town bank");
return true;
}
double amount = plugin.parseD( args[2] );
if (temp.tb_withdraw(officer, amount) ) {
plugin.out(officer,"You have withdrawn "+amount+" from your town's bank" );
plugin.out(officer,"Your personal balance is now: "+plugin.econwrapper.getBalance(officer) );
temp.checkTownBank(officer);
} else {
plugin.out( sender,"The town bank didn't have enough to withdraw" );
}
} else if (args[1].equalsIgnoreCase("check") || args[1].equalsIgnoreCase("c") ){
temp.checkTownBank(officer);
} else {
plugin.out(sender,"/deputy bank - ERROR (subcommand not recognized)");
plugin.out(sender,"/deputy bank (check|withdraw|deposit)");
}
break;
default:
plugin.out(sender,"Invalid number of parameters");
return false;
}
return true;
}else if (args[0].equalsIgnoreCase("itembank")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
switch (args.length){
case 1:
plugin.getTown(plugin.getTownName( officer.getName() ) ).checkTownItemBank(officer);
break;
case 2:
temp.checkTownBank(officer);
break;
case 3:
if (args[1].equalsIgnoreCase("deposit") || args[1].equalsIgnoreCase("d") ){
int amount = plugin.parseI( args[2] );
if (temp.tb_depositItems(officer, amount ) ) {
plugin.out(officer,"You have deposited "+amount+" into your town's bank" );
temp.checkTownItemBank(officer);
}
else {
plugin.out(officer,"You don't have enough to deposit");
}
return true;
} else if (args[1].equalsIgnoreCase("withdraw") || args[1].equalsIgnoreCase("w") ){
if ( !plugin.econwrapper.hasPerm(officer, "muni.deputy.changetax") ) {
officer.sendMessage("You do not have permission to withdraw from the town bank");
return true;
}
int amount = plugin.parseI( args[2] );
if (temp.tb_withdrawItems(officer, amount) ) {
plugin.out(officer,"You have withdrawn "+amount+" "+plugin.econwrapper.getRankupItemName()+
" from your town's bank" );
temp.checkTownBank(officer);
} else {
plugin.out( sender,"The town bank didn't have enough to withdraw" );
}
} else if (args[1].equalsIgnoreCase("check") || args[1].equalsIgnoreCase("c") ){
temp.checkTownBank(officer);
} else {
plugin.out(sender,"/deputy itemBank - ERROR (subcommand not recognized)");
plugin.out(sender,"/deputy itemBank (check|withdraw|deposit)");
}
break;
default:
plugin.out(sender,"Invalid number of parameters");
return false;
}
return true;
} else if ( args[0].equalsIgnoreCase("makePlot") || args[0].equalsIgnoreCase("makeSubRegion") ) {
if (args.length == 1) {
officer.sendMessage("This command will make a pre-sized plot around your location as the center");
officer.sendMessage("/deputy makePlot list");
officer.sendMessage("/deputy makePlot <type>");
return true;
}
if ( args[1].equalsIgnoreCase( "list" ) ){
officer.sendMessage("You may choose from the following types.");
officer.sendMessage("(if your current town rank allows it)");
officer.sendMessage("restaurant");
officer.sendMessage("hospital");
officer.sendMessage("arena");
officer.sendMessage("outpost");
officer.sendMessage("embassy");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
boolean test = false;
if ( temp.isOfficer(officer) ) {
if ( args[1].equalsIgnoreCase( "restaurant" ) ){
if (temp.paymentFromTB(plugin.getRestaurantCost(), 0, officer.getName(), "restaurant creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "restaurant" ) < plugin.townRanks[temp.getRank()].getRestaurants() ){
test = plugin.wgwrapper.makeRestaurant(temp, officer, temp.getName()+"_r");
} else { officer.sendMessage("Your town already has the max number of restaurants"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "hospital" ) ){
if (temp.paymentFromTB(plugin.getHospitalCost(), 0, officer.getName(), "hospital creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "hospital" ) < plugin.townRanks[temp.getRank()].getHospitals() ){
test = plugin.wgwrapper.makeHospital(temp, officer, temp.getName()+"_h");
} else { officer.sendMessage("Your town already has the max number of hospitals"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "arena" ) ){
if (temp.paymentFromTB(plugin.getArenaCost(), 0, officer.getName(), "arena creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "arena" ) < plugin.townRanks[temp.getRank()].getArenas() ){
test = plugin.wgwrapper.makeArena(temp, officer, temp.getName()+"_a");
} else { officer.sendMessage("Your town already has the max number of arenas"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "outpost" ) ){
if (temp.paymentFromTB(plugin.getOutpostCost(), 0, officer.getName(), "outpost creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "outpost" ) < plugin.townRanks[temp.getRank()].getOutposts() ){
test = plugin.wgwrapper.makeOutpost(temp, officer, temp.getName()+"_o");
} else { officer.sendMessage("Your town already has the max number of outposts"); return true; }
} else { officer.sendMessage("Not enough money in the town bank."); return true; }
} else if ( args[1].equalsIgnoreCase( "embassy" ) ){
if (temp.paymentFromTB(plugin.getEmbassyCost(), 0, officer.getName(), "embassy creation") ){
if (plugin.dbwrapper.getNumSubRegions(temp, "embassy" ) < plugin.townRanks[temp.getRank()].getEmbassies() ){
test = plugin.wgwrapper.makeEmbassy(temp, officer, temp.getName()+"_e");
} else { officer.sendMessage("Your town already has the max number of embassies"); return true; }
} else { officer.sendMessage("Not enough money in the town bank. "); return true; }
}
if (test) {
officer.sendMessage("The sub-region was created successfully");
} else {
officer.sendMessage("There was a problem creating the sub-region");
}
}
return true;
}
// Mayor-only commands from here on out
if (!plugin.econwrapper.hasPerm(officer, "muni.mayor")){
officer.sendMessage("You do not have permission to do /mayor subcommands");
return true;
}
if (args[0].equalsIgnoreCase("makeBorder")) {
if (args.length == 1) {
officer.sendMessage("This makes the 25x25 town border centered at your current location");
officer.sendMessage("/mayor makeBorder confirm");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) { // NPE when no town
if ( args[1].equalsIgnoreCase( "confirm" ) ){
if ( plugin.wgwrapper.makeTownBorder(officer, temp ) > 0 ){
plugin.getServer().broadcastMessage("The "+temp.getName()+" town border has been created!");
} else {
officer.sendMessage("There was a problem ");
}
} else { officer.sendMessage("You must do /mayor makeBorder confirm"); }
}
return true;
} else if (args[0].equalsIgnoreCase("found") ||
args[0].equalsIgnoreCase("charter") ||args[0].equalsIgnoreCase("add")) {
if (args.length == 1 || args.length > 3) {
officer.sendMessage("/mayor found <TownName>");
return true;
}
if (plugin.isCitizen(officer) ){
officer.sendMessage("You are already a member of another town.");
return true;
}
if (plugin.isTown(args[1]) ){
officer.sendMessage("That town already exists. Please choose another name");
return true;
}
if ( args.length == 2 ) {
officer.sendMessage("Are you sure you want to name your town "+args[1]+"?");
officer.sendMessage("It is permanent and you may not change it later!!!");
officer.sendMessage("It cannot contain spaces. Be sure your capitalization is how you want it");
officer.sendMessage("To confirm do /mayor found "+args[1]+" confirm");
return true;
}
if ( args.length != 3) { return true; }
if (!args[2].equalsIgnoreCase("confirm") ){
return true;
}
if (plugin.econwrapper.pay(officer, plugin.townRanks[1].getMoneyCost(),
plugin.townRanks[1].getItemCost(), "Found: "+args[1] ) ){
Town t = new Town( plugin, args[1], officer.getName(),officer.getWorld().getName() );
plugin.towns.put(t.getName(), t );
plugin.allCitizens.put(officer.getName(), t.getName() );
t.admin_makeMayor(officer.getName() );
t.saveToDB();
officer.sendMessage("You have founded "+t.getName());
plugin.getServer().broadcastMessage(t.getName()+" is now a "+
t.getTitle()+" thanks to its new mayor " +t.getMayor()+"!" );
} else { officer.sendMessage("Could not start the town due to insufficent resources" ); }
return true;
} else if ( args[0].equalsIgnoreCase("renameTown") ) {
if (args.length == 1) {
officer.sendMessage("This command will rename your town");
officer.sendMessage("/mayor renameTown <newName>");
return true;
}
if ( args.length == 2 ){
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.isMayor(officer) ) {
//temp.renameTown(args[1]);
officer.sendMessage("Town names are currently permanent. Delete your town and re-make");
}
} else { officer.sendMessage("/mayor renameTown <newName>"); }
return true;
} else if (args[0].equalsIgnoreCase("delete")
|| args[0].equalsIgnoreCase("disband")) {
if (args.length == 1 ) {
officer.sendMessage("To confirm town deletion, do /mayor delete confirm");
return true;
}
if (args[1].equalsIgnoreCase("confirm") ){
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
plugin.wgwrapper.removeTown(temp.getName());
temp.removeAllTownCits(); //NPE somewhere
plugin.removeTown(temp.getName() ); //NPE somewhere
plugin.wgwrapper.deleteAllRegions(temp);
plugin.getServer().broadcastMessage(temp.getName()+
" and all its citizens were removed by the mayor, "+ officer.getName()+"!" );
} else { officer.sendMessage("To confirm town deletion, do /mayor delete confirm"); }
return true;
} else if (args[0].equalsIgnoreCase("deputize")) { // buggy but working on it - 19 Feb 13
if (args.length != 2) {
officer.sendMessage("Incorrect number of parameters");
return false;
}
if (!plugin.isCitizen(officer) ){
officer.sendMessage("You are not a citizen anywhere");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) ); //throwing NPE - 19 Feb 13
temp.makeDeputy( args[1] ,officer);
return true;
} else if (args[0].equalsIgnoreCase("rankup")) {
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
if ( temp.rankup(officer) ){
plugin.getServer().broadcastMessage(temp.getName()+" has been ranked to "+
temp.getTitle()+" by " + officer.getName() );
}
displayHelp( officer, args[0] );
return true;
} else if (args[0].equalsIgnoreCase("expand")) {
if (args.length == 1 || args.length >3){
officer.sendMessage("You must specify a direction");
officer.sendMessage("north, south, east, or west");
officer.sendMessage("n,s,e,w");
return true;
}
Town temp = plugin.getTown( plugin.getTownName( officer.getName() ) );
Double price = plugin.getExpansionCostMultiplier()*(temp.getExpansions()+1);
try {
if (!args[2].equalsIgnoreCase("confirm") ){
officer.sendMessage("The expansion will cost the town "+price+" "+
plugin.econwrapper.getCurrNamePlural()+".");
officer.sendMessage("To confirm do /mayor expand <direction> confirm ");
return true;
}
}
catch (ArrayIndexOutOfBoundsException ex ){
officer.sendMessage("To confirm do /mayor expand <direction> confirm ");
return true;
}
if ( temp.isMayor(officer) ){
if (temp.paymentFromTB(price, 0) ){
int area = plugin.wgwrapper.expandRegion(officer.getWorld().getName(),
temp.getName(), args[1], 10);
if ( area > 0 ){
temp.incrementExpansions();
temp.messageOfficers(price+" "+plugin.econwrapper.getCurrNamePlural()
+" has been deducted from the town bank for border expansion");
officer.sendMessage("The new area is "+area );
plugin.getServer().broadcastMessage(temp.getName()+" has expanded its borders ");
//log transaction here
} else { officer.sendMessage("You must specify {n,s,e,w}"); }
}
}
return true;
} else {
officer.sendMessage("[Muni] Input not understood.");
displayHelp( officer, args[0] );
return true;
}
}
|
diff --git a/src/main/java/org/waarp/openr66/client/spooledService/SpooledEngine.java b/src/main/java/org/waarp/openr66/client/spooledService/SpooledEngine.java
index 1a712faa..b8c8dc56 100644
--- a/src/main/java/org/waarp/openr66/client/spooledService/SpooledEngine.java
+++ b/src/main/java/org/waarp/openr66/client/spooledService/SpooledEngine.java
@@ -1,110 +1,110 @@
/**
This file is part of Waarp Project.
Copyright 2009, Frederic Bregier, and individual contributors by the @author
tags. See the COPYRIGHT.txt in the distribution for a full listing of
individual contributors.
All Waarp Project 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 3 of the License, or
(at your option) any later version.
Waarp 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 Waarp . If not, see <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.client.spooledService;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Properties;
import org.waarp.common.future.WaarpFuture;
import org.waarp.common.logging.WaarpInternalLogger;
import org.waarp.common.logging.WaarpInternalLoggerFactory;
import org.waarp.common.service.EngineAbstract;
import org.waarp.common.utility.SystemPropertyUtil;
import org.waarp.openr66.client.SpooledDirectoryTransfer;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.configuration.R66SystemProperties;
import org.waarp.openr66.protocol.utils.R66ShutdownHook;
/**
* Engine used to start and stop the SpooledDirectory service
* @author Frederic Bregier
*
*/
public class SpooledEngine extends EngineAbstract {
/**
* Internal Logger
*/
private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory
.getLogger(SpooledEngine.class);
public static WaarpFuture closeFuture = new WaarpFuture(true);
@Override
public void run() {
String config = SystemPropertyUtil.get(R66SystemProperties.OPENR66_CONFIGFILE);
if (config == null) {
logger.error("Cannot find "+R66SystemProperties.OPENR66_CONFIGFILE+" parameter for SpooledEngine");
closeFuture.cancel();
shutdown();
return;
}
Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(config));
ArrayList<String> array = new ArrayList<String>();
for (Object okey : prop.keySet()) {
String key = (String) okey;
String val = prop.getProperty(key);
if (key.equals("xmlfile")) {
- if (val != null) {
+ if (val != null && ! val.trim().isEmpty()) {
array.add(0, val);
} else {
throw new Exception("Initialization in error: missing xmlfile");
}
} else {
- array.add(key);
- if (val != null) {
+ array.add("-"+key);
+ if (val != null && ! val.trim().isEmpty()) {
array.add(val);
}
}
}
if (! SpooledDirectoryTransfer.initialize((String[]) array.toArray(), false)) {
throw new Exception("Initialization in error");
}
} catch (Throwable e) {
logger.error("Cannot start SpooledDirectory", e);
closeFuture.cancel();
shutdown();
return;
}
logger.warn("SpooledDirectory Service started with "+config);
}
@Override
public void shutdown() {
R66ShutdownHook.terminate(false);
closeFuture.setSuccess();
logger.info("SpooledDirectory Service stopped");
}
@Override
public boolean isShutdown() {
return closeFuture.isDone();
}
@Override
public boolean waitShutdown() throws InterruptedException {
closeFuture.await();
return closeFuture.isSuccess();
}
}
| false | true | public void run() {
String config = SystemPropertyUtil.get(R66SystemProperties.OPENR66_CONFIGFILE);
if (config == null) {
logger.error("Cannot find "+R66SystemProperties.OPENR66_CONFIGFILE+" parameter for SpooledEngine");
closeFuture.cancel();
shutdown();
return;
}
Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(config));
ArrayList<String> array = new ArrayList<String>();
for (Object okey : prop.keySet()) {
String key = (String) okey;
String val = prop.getProperty(key);
if (key.equals("xmlfile")) {
if (val != null) {
array.add(0, val);
} else {
throw new Exception("Initialization in error: missing xmlfile");
}
} else {
array.add(key);
if (val != null) {
array.add(val);
}
}
}
if (! SpooledDirectoryTransfer.initialize((String[]) array.toArray(), false)) {
throw new Exception("Initialization in error");
}
} catch (Throwable e) {
logger.error("Cannot start SpooledDirectory", e);
closeFuture.cancel();
shutdown();
return;
}
logger.warn("SpooledDirectory Service started with "+config);
}
| public void run() {
String config = SystemPropertyUtil.get(R66SystemProperties.OPENR66_CONFIGFILE);
if (config == null) {
logger.error("Cannot find "+R66SystemProperties.OPENR66_CONFIGFILE+" parameter for SpooledEngine");
closeFuture.cancel();
shutdown();
return;
}
Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(config));
ArrayList<String> array = new ArrayList<String>();
for (Object okey : prop.keySet()) {
String key = (String) okey;
String val = prop.getProperty(key);
if (key.equals("xmlfile")) {
if (val != null && ! val.trim().isEmpty()) {
array.add(0, val);
} else {
throw new Exception("Initialization in error: missing xmlfile");
}
} else {
array.add("-"+key);
if (val != null && ! val.trim().isEmpty()) {
array.add(val);
}
}
}
if (! SpooledDirectoryTransfer.initialize((String[]) array.toArray(), false)) {
throw new Exception("Initialization in error");
}
} catch (Throwable e) {
logger.error("Cannot start SpooledDirectory", e);
closeFuture.cancel();
shutdown();
return;
}
logger.warn("SpooledDirectory Service started with "+config);
}
|
diff --git a/src/main/java/de/jacobs1/jmxcollector/Main.java b/src/main/java/de/jacobs1/jmxcollector/Main.java
index 5d61126..1a30b50 100644
--- a/src/main/java/de/jacobs1/jmxcollector/Main.java
+++ b/src/main/java/de/jacobs1/jmxcollector/Main.java
@@ -1,393 +1,393 @@
package de.jacobs1.jmxcollector;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.ConnectException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.apache.log4j.Logger;
import org.rrd4j.ConsolFun;
import org.rrd4j.DsType;
import org.rrd4j.core.RrdDb;
import org.rrd4j.core.RrdDbPool;
import org.rrd4j.core.RrdDef;
import org.rrd4j.core.Sample;
import org.rrd4j.graph.RrdGraph;
import org.rrd4j.graph.RrdGraphDef;
public class Main {
private static final Logger LOG = Logger.getLogger(Main.class);
private static final Map<Connection, MBeanServerConnection> mBeanServerConnections =
new ConcurrentHashMap<Connection, MBeanServerConnection>();
private static final AtomicLong updateCount = new AtomicLong();
public static void graph(final String rrdPath, final String dsName, final String outPath) throws Exception {
RrdGraphDef graphDef = new RrdGraphDef();
graphDef.setTimeSpan(-3600, -1);
graphDef.setVerticalLabel("req/s");
graphDef.datasource("req", rrdPath, dsName, ConsolFun.AVERAGE);
graphDef.line("req", new Color(0xFF, 0, 0), null, 2);
graphDef.gprint("req", ConsolFun.MIN, "%10.2lf/s MIN");
graphDef.gprint("req", ConsolFun.AVERAGE, "%10.2lf/s AVG");
graphDef.gprint("req", ConsolFun.MAX, "%10.2lf/s MAX");
graphDef.setFilename(outPath);
// graphDef.setBase(1);
RrdGraph graph = new RrdGraph(graphDef);
BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
graph.render(bi.getGraphics());
}
/* For simplicity, we declare "throws Exception".
*Real programs will usually want finer-grained exception handling. */
public static void main(final String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Usage: jmxcollector <CONFIGFILE>");
return;
}
if (args.length >= 4 && args[0].equals("graph")) {
graph(args[1], args[2], args[3]);
return;
}
run(args[0]);
}
/**
* old style properties based config.
*
* @param configFile
* @param datasources
*
* @return
*
* @throws IOException
* @throws MalformedObjectNameException
*/
private static int loadConfigFromProperties(final String configFile, final List<DataSource> datasources)
throws IOException, MalformedObjectNameException {
final List<Connection> connections = new ArrayList<Connection>();
final Properties props = new Properties();
final FileReader fr = new FileReader(configFile);
props.load(fr);
fr.close();
String val;
int i;
i = 1;
while ((val = props.getProperty("connection." + i + ".host")) != null) {
Connection conn = new Connection();
conn.setHost(val);
conn.setPort(props.getProperty("connection." + i + ".port"));
conn.setUser(props.getProperty("connection." + i + ".user"));
conn.setPassword(props.getProperty("connection." + i + ".password"));
connections.add(conn);
i++;
}
i = 1;
while ((val = props.getProperty("datasource." + i + ".connection")) != null) {
DataSource ds = new DataSource();
ds.setConnection(connections.get(Integer.valueOf(val) - 1));
ds.setBeanName(new ObjectName(props.getProperty("datasource." + i + ".bean")));
ds.setAttributeName(props.getProperty("datasource." + i + ".attribute"));
String[] parts = props.getProperty("datasource." + i + ".rrd").split(":", 2);
ds.setRrdPath(parts[0]);
ds.setRrdDSName(parts[1]);
datasources.add(ds);
i++;
}
return connections.size();
}
private static String stripQuotes(String str) {
if (str.startsWith("\"")) {
str = str.substring(1);
}
if (str.endsWith("\"")) {
str = str.substring(0, str.length() - 1);
}
return str;
}
private static String replaceVariables(final String inp, final Connection conn) {
return inp.replaceAll("%h", conn.getHost()).replaceAll("%4p",
conn.getPort().substring(conn.getPort().length() - 4));
}
private static int loadConfigFromConfigFile(final String configFile, final List<DataSource> datasources)
throws IOException, MalformedObjectNameException {
int numberOfConnections = 0;
final FileReader fr = new FileReader(configFile);
final BufferedReader br = new BufferedReader(fr);
String line;
String[] parts;
Connection conn = null;
DataSource ds;
while ((line = br.readLine()) != null) {
if (line.trim().startsWith("#") || line.trim().isEmpty()) {
// comment
continue;
}
if (!line.startsWith(" ") && !line.startsWith("\t")) {
line = line.trim();
// connection definition
parts = line.split("[@:]", 4);
conn = new Connection();
conn.setHost(parts[2]);
conn.setPort(parts[3]);
conn.setUser(parts[0]);
conn.setPassword(parts[1]);
numberOfConnections++;
} else {
line = line.trim();
// datasource definition (uses most recently defined connection)
parts = line.split("\\s*=\\s*", 2);
ds = new DataSource();
ds.setConnection(conn);
if (parts[1].startsWith("GAUGE:")) {
ds.setRrdDSType(DsType.GAUGE);
parts[1] = parts[1].substring(6);
} else {
ds.setRrdDSType(DsType.DERIVE);
}
final int dot = parts[1].lastIndexOf('.');
ds.setBeanName(new ObjectName(replaceVariables(stripQuotes(parts[1].substring(0, dot)), conn)));
ds.setAttributeName(parts[1].substring(dot + 1));
final String[] pathDSName = parts[0].split(":", 2);
ds.setRrdPath(replaceVariables(pathDSName[0], conn));
ds.setRrdDSName(pathDSName[1]);
datasources.add(ds);
}
}
fr.close();
return numberOfConnections;
}
public static void run(final String configFile) throws IOException, MalformedObjectNameException, MBeanException,
AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
final List<DataSource> datasources = new ArrayList<DataSource>();
int numberOfConnections;
if (configFile.endsWith(".properties")) {
numberOfConnections = loadConfigFromProperties(configFile, datasources);
} else {
numberOfConnections = loadConfigFromConfigFile(configFile, datasources);
}
LOG.info("Loaded config from " + configFile + " with " + numberOfConnections + " connections and "
+ datasources.size() + " datasources");
for (DataSource ds : datasources) {
createRrdFile(ds.getRrdPath(), ds.getRrdDSName(), ds.getRrdDSType());
}
final RrdDbPool pool = RrdDbPool.getInstance();
pool.setCapacity(datasources.size() * 2);
for (DataSource dataSource : datasources) {
dataSource.setRrdDb(pool.requestRrdDb(dataSource.getRrdPath()));
}
final long interval = 2000;
int j;
- ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(datasources.size(),
+ ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(numberOfConnections,
new DaemonThreadFactory("Updater"));
j = 1;
for (final DataSource dataSource : datasources) {
final int dataSourceId = j;
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
final long currentCount = updateCount.incrementAndGet();
final MBeanServerConnection mbsc = getMBeanServerConnection(dataSource.getConnection());
if (mbsc == null) {
return;
}
Object attr = null;
try {
attr = mbsc.getAttribute(dataSource.getBeanName(), dataSource.getAttributeName());
} catch (ConnectException ce) {
LOG.error("ConnectException while trying to get attribute " + dataSource.getAttributeName()
+ " from " + dataSource.getBeanName().getCanonicalName(), ce);
// remove connection to force reconnect
mBeanServerConnections.remove(dataSource.getConnection());
return;
} catch (InstanceNotFoundException infe) {
LOG.error("InstanceNotFoundException while trying to get attribute "
+ dataSource.getAttributeName() + " from "
+ dataSource.getBeanName().getCanonicalName(), infe);
return;
}
final RrdDb rrd = dataSource.getRrdDb();
final Sample sample;
sample = rrd.createSample();
double val = 0;
if (attr instanceof Integer) {
val = (Integer) attr;
} else if (attr instanceof Long) {
val = ((Long) attr).intValue();
} else if (attr instanceof Float) {
val = ((Float) attr);
} else if (attr instanceof Double) {
val = ((Double) attr);
} else {
throw new IllegalArgumentException("Unsupported type " + attr + " for attribute "
+ dataSource.getAttributeName() + " for datasource " + dataSourceId);
}
sample.setValue(dataSource.getRrdDSName(), val);
try {
sample.update();
} catch (IllegalArgumentException iae) {
LOG.error("Dropping sample of datasource " + dataSourceId, iae);
}
} catch (final Throwable ex) {
// catch all. never fail. that would cancel the scheduler.
LOG.error("Unexpected exception while trying to update from datasource " + dataSourceId, ex);
}
}
};
- executor.scheduleAtFixedRate(updater, 0, interval, TimeUnit.MILLISECONDS);
+ executor.scheduleWithFixedDelay(updater, 0, interval, TimeUnit.MILLISECONDS);
j++;
}
int i = 0;
while (true) {
sleep(60000);
LOG.info("Heartbeat " + i + " (" + updateCount.get() + " updates)");
i++;
}
}
private static MBeanServerConnection getMBeanServerConnection(final Connection conn) throws IOException {
MBeanServerConnection mbsc = mBeanServerConnections.get(conn);
if (mbsc == null) {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + conn.getHost() + ":"
+ conn.getPort() + "/jmxrmi");
Map<String, Object> env = new HashMap<String, Object>();
if (conn.getUser() != null) {
String[] credentials = new String[] {conn.getUser(), conn.getPassword()};
env.put("jmx.remote.credentials", credentials);
}
try {
LOG.info("Trying to connect to " + conn.getHost() + ":" + conn.getPort());
JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
LOG.info("Trying to get an MBeanServerConnection");
mbsc = jmxc.getMBeanServerConnection();
mBeanServerConnections.put(conn, mbsc);
} catch (IOException ioe) {
LOG.error("Failed to connect to JMX service URL " + url, ioe);
return null;
}
}
return mbsc;
}
private static void createRrdFile(final String path, final String dsName, final DsType dsType) throws IOException {
final RrdDbPool pool = RrdDbPool.getInstance();
if (!(new File(path)).exists()) {
LOG.info("Creating new RRD file " + path);
RrdDef def = new RrdDef(path, 2);
def.addDatasource(dsName, dsType, 90, 0, Double.NaN);
// 2sec resolution for the last 4 hours
def.addArchive(ConsolFun.AVERAGE, 0.5, 1, 30 * 60 * 4);
// 10sec resolution for the last 24 hours
def.addArchive(ConsolFun.AVERAGE, 0.5, 5, 600 * 24);
// 1min resolution for the last week
def.addArchive(ConsolFun.AVERAGE, 0.5, 30, 60 * 24 * 7);
// 1 hour resolution for the last 365 days
def.addArchive(ConsolFun.AVERAGE, 0.5, 30 * 60, 24 * 365);
RrdDb rrd = pool.requestRrdDb(def);
pool.release(rrd);
}
}
private static void sleep(final long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
LOG.error("Sleep was interrupted", e);
}
}
}
| false | true | public static void run(final String configFile) throws IOException, MalformedObjectNameException, MBeanException,
AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
final List<DataSource> datasources = new ArrayList<DataSource>();
int numberOfConnections;
if (configFile.endsWith(".properties")) {
numberOfConnections = loadConfigFromProperties(configFile, datasources);
} else {
numberOfConnections = loadConfigFromConfigFile(configFile, datasources);
}
LOG.info("Loaded config from " + configFile + " with " + numberOfConnections + " connections and "
+ datasources.size() + " datasources");
for (DataSource ds : datasources) {
createRrdFile(ds.getRrdPath(), ds.getRrdDSName(), ds.getRrdDSType());
}
final RrdDbPool pool = RrdDbPool.getInstance();
pool.setCapacity(datasources.size() * 2);
for (DataSource dataSource : datasources) {
dataSource.setRrdDb(pool.requestRrdDb(dataSource.getRrdPath()));
}
final long interval = 2000;
int j;
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(datasources.size(),
new DaemonThreadFactory("Updater"));
j = 1;
for (final DataSource dataSource : datasources) {
final int dataSourceId = j;
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
final long currentCount = updateCount.incrementAndGet();
final MBeanServerConnection mbsc = getMBeanServerConnection(dataSource.getConnection());
if (mbsc == null) {
return;
}
Object attr = null;
try {
attr = mbsc.getAttribute(dataSource.getBeanName(), dataSource.getAttributeName());
} catch (ConnectException ce) {
LOG.error("ConnectException while trying to get attribute " + dataSource.getAttributeName()
+ " from " + dataSource.getBeanName().getCanonicalName(), ce);
// remove connection to force reconnect
mBeanServerConnections.remove(dataSource.getConnection());
return;
} catch (InstanceNotFoundException infe) {
LOG.error("InstanceNotFoundException while trying to get attribute "
+ dataSource.getAttributeName() + " from "
+ dataSource.getBeanName().getCanonicalName(), infe);
return;
}
final RrdDb rrd = dataSource.getRrdDb();
final Sample sample;
sample = rrd.createSample();
double val = 0;
if (attr instanceof Integer) {
val = (Integer) attr;
} else if (attr instanceof Long) {
val = ((Long) attr).intValue();
} else if (attr instanceof Float) {
val = ((Float) attr);
} else if (attr instanceof Double) {
val = ((Double) attr);
} else {
throw new IllegalArgumentException("Unsupported type " + attr + " for attribute "
+ dataSource.getAttributeName() + " for datasource " + dataSourceId);
}
sample.setValue(dataSource.getRrdDSName(), val);
try {
sample.update();
} catch (IllegalArgumentException iae) {
LOG.error("Dropping sample of datasource " + dataSourceId, iae);
}
} catch (final Throwable ex) {
// catch all. never fail. that would cancel the scheduler.
LOG.error("Unexpected exception while trying to update from datasource " + dataSourceId, ex);
}
}
};
executor.scheduleAtFixedRate(updater, 0, interval, TimeUnit.MILLISECONDS);
j++;
}
int i = 0;
while (true) {
sleep(60000);
LOG.info("Heartbeat " + i + " (" + updateCount.get() + " updates)");
i++;
}
}
| public static void run(final String configFile) throws IOException, MalformedObjectNameException, MBeanException,
AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
final List<DataSource> datasources = new ArrayList<DataSource>();
int numberOfConnections;
if (configFile.endsWith(".properties")) {
numberOfConnections = loadConfigFromProperties(configFile, datasources);
} else {
numberOfConnections = loadConfigFromConfigFile(configFile, datasources);
}
LOG.info("Loaded config from " + configFile + " with " + numberOfConnections + " connections and "
+ datasources.size() + " datasources");
for (DataSource ds : datasources) {
createRrdFile(ds.getRrdPath(), ds.getRrdDSName(), ds.getRrdDSType());
}
final RrdDbPool pool = RrdDbPool.getInstance();
pool.setCapacity(datasources.size() * 2);
for (DataSource dataSource : datasources) {
dataSource.setRrdDb(pool.requestRrdDb(dataSource.getRrdPath()));
}
final long interval = 2000;
int j;
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(numberOfConnections,
new DaemonThreadFactory("Updater"));
j = 1;
for (final DataSource dataSource : datasources) {
final int dataSourceId = j;
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
final long currentCount = updateCount.incrementAndGet();
final MBeanServerConnection mbsc = getMBeanServerConnection(dataSource.getConnection());
if (mbsc == null) {
return;
}
Object attr = null;
try {
attr = mbsc.getAttribute(dataSource.getBeanName(), dataSource.getAttributeName());
} catch (ConnectException ce) {
LOG.error("ConnectException while trying to get attribute " + dataSource.getAttributeName()
+ " from " + dataSource.getBeanName().getCanonicalName(), ce);
// remove connection to force reconnect
mBeanServerConnections.remove(dataSource.getConnection());
return;
} catch (InstanceNotFoundException infe) {
LOG.error("InstanceNotFoundException while trying to get attribute "
+ dataSource.getAttributeName() + " from "
+ dataSource.getBeanName().getCanonicalName(), infe);
return;
}
final RrdDb rrd = dataSource.getRrdDb();
final Sample sample;
sample = rrd.createSample();
double val = 0;
if (attr instanceof Integer) {
val = (Integer) attr;
} else if (attr instanceof Long) {
val = ((Long) attr).intValue();
} else if (attr instanceof Float) {
val = ((Float) attr);
} else if (attr instanceof Double) {
val = ((Double) attr);
} else {
throw new IllegalArgumentException("Unsupported type " + attr + " for attribute "
+ dataSource.getAttributeName() + " for datasource " + dataSourceId);
}
sample.setValue(dataSource.getRrdDSName(), val);
try {
sample.update();
} catch (IllegalArgumentException iae) {
LOG.error("Dropping sample of datasource " + dataSourceId, iae);
}
} catch (final Throwable ex) {
// catch all. never fail. that would cancel the scheduler.
LOG.error("Unexpected exception while trying to update from datasource " + dataSourceId, ex);
}
}
};
executor.scheduleWithFixedDelay(updater, 0, interval, TimeUnit.MILLISECONDS);
j++;
}
int i = 0;
while (true) {
sleep(60000);
LOG.info("Heartbeat " + i + " (" + updateCount.get() + " updates)");
i++;
}
}
|
diff --git a/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/common/internal/impl/XMLResourceImpl.java b/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/common/internal/impl/XMLResourceImpl.java
index d97c7c457..9f2a204f3 100644
--- a/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/common/internal/impl/XMLResourceImpl.java
+++ b/plugins/org.eclipse.jst.j2ee.core/mofj2ee/org/eclipse/jst/j2ee/common/internal/impl/XMLResourceImpl.java
@@ -1,333 +1,333 @@
/*******************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and others.
* 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jst.j2ee.common.internal.impl;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import org.eclipse.core.internal.resources.Workspace;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.jst.j2ee.application.Application;
import org.eclipse.jst.j2ee.internal.J2EEVersionConstants;
import org.eclipse.jst.j2ee.internal.common.J2EEVersionResource;
import org.eclipse.jst.j2ee.internal.common.XMLResource;
import org.eclipse.jst.j2ee.internal.xml.J2EEXmlDtDEntityResolver;
import org.eclipse.wst.common.internal.emf.resource.Renderer;
import org.eclipse.wst.common.internal.emf.resource.TranslatorResource;
import org.eclipse.wst.common.internal.emf.resource.TranslatorResourceImpl;
import org.eclipse.wst.common.internal.emfworkbench.WorkbenchResourceHelper;
import org.xml.sax.EntityResolver;
public abstract class XMLResourceImpl extends TranslatorResourceImpl implements XMLResource,J2EEVersionResource {
/** Indicator to determine if this resource was loaded as an alt-dd (from an ear),
* default is false */
protected boolean isAlt = false;
/** The application which declared the alt-dd for this resource; exists only if this resource is and
* alt dd */
protected Application application;
protected boolean isNew = true;
private Boolean needsSync = new Boolean(true);
private static class RootVersionAdapter extends AdapterImpl {
/* (non-Javadoc)
* @see org.eclipse.emf.common.notify.impl.AdapterImpl#isAdapterForType(java.lang.Object)
*/
@Override
public boolean isAdapterForType(Object type) {
return super.isAdapterForType(type);
}
/* (non-Javadoc)
* @see org.eclipse.emf.common.notify.impl.AdapterImpl#notifyChanged(org.eclipse.emf.common.notify.Notification)
*/
@Override
public void notifyChanged(Notification msg) {
if (msg.getFeatureID(null) == RESOURCE__CONTENTS &&
msg.getEventType() == Notification.ADD) {
((XMLResourceImpl)msg.getNotifier()).syncVersionOfRootObject();
((Notifier)msg.getNotifier()).eAdapters().remove(this);
}
}
}
/**
* @deprecated since 4/29/2003 - used for compatibility
* Subclasses should be using the Renderers and translator framework
*/
public XMLResourceImpl() {
super();
}
/**
* @deprecated since 4/29/2003 - used for compatibility
* Subclasses should be using the Renderers and translator framework
*/
public XMLResourceImpl(URI uri) {
super(uri);
}
public XMLResourceImpl(URI uri, Renderer aRenderer) {
super(uri, aRenderer);
}
public XMLResourceImpl(Renderer aRenderer) {
super(aRenderer);
}
/* (non-Javadoc)
* @see com.ibm.etools.emf2xml.impl.TranslatorResourceImpl#initializeContents()
*/
@Override
protected void initializeContents() {
super.initializeContents();
eAdapters().add(new RootVersionAdapter());
}
/**
* Is this a resource loaded as an alternate deployment descriptor?
*/
public boolean isAlt() {
return isAlt;
}
public void setApplication(Application newApplication) {
application = newApplication;
}
/**
* Is this a resource loaded as an alternate deployment descriptor?
*/
public void setIsAlt(boolean isAlternateDD) {
isAlt = isAlternateDD;
}
/* (non-Javadoc)
* @see com.ibm.etools.emf2xml.impl.TranslatorResourceImpl#getDefaultVersionID()
*/
@Override
protected int getDefaultVersionID() {
return J2EE_1_4_ID;
}
/* (non-Javadoc)
* @see com.ibm.etools.emf2xml.TranslatorResource#setDoctypeValues(java.lang.String, java.lang.String)
* This is setting the module version on the resource, where values are different that the J2EE version, this will be overridden
*/
@Override
public void setDoctypeValues(String publicId, String systemId) {
int version = J2EE_1_4_ID;
if (systemId == null)
version = J2EE_1_4_ID;
else if (systemId.equals(getJ2EE_1_3_SystemID()) || systemId.equals(getJ2EE_Alt_1_3_SystemID()))
version = J2EE_1_3_ID;
else if (systemId.equals(getJ2EE_1_2_SystemID()) || systemId.equals(getJ2EE_Alt_1_2_SystemID()))
version = J2EE_1_2_ID;
super.setDoctypeValues(publicId, systemId);
//Only set if versionID not set if version is 14
if ((version != J2EE_1_4_ID) || (version == J2EE_1_4_ID && getModuleVersionID() == 0))
setJ2EEVersionID(version);
}
/* (non-Javadoc)
* @see com.ibm.etools.emf2xml.TranslatorResource#usesDTD()
*/
@Override
public boolean usesDTD() {
return (getVersionID() == J2EE_1_2_ID) || (getVersionID() == J2EE_1_3_ID);
}
/* (non-Javadoc)
* @see com.ibm.etools.emf2xml.TranslatorResource#setVersionID(int)
* @deprecated, Use setJ2EEVersionID() to set module version based on j2ee version
**/
@Override
public void setVersionID(int id) {
setJ2EEVersionID(id);
}
protected void primSetVersionID(int id) {
super.setVersionID(id);
}
protected void primSetDoctypeValues(String aPublicId, String aSystemId) {
super.setDoctypeValues(aPublicId,aSystemId);
}
/*
* Sets the module version based on the J2EE version
*/
public abstract void setJ2EEVersionID(int id);
/*
* Sets the module version directly
* */
public abstract void setModuleVersionID(int id);
/**
* @deprecated
* (non-Javadoc)
* @see org.eclipse.jst.j2ee.internal.XMLResource#isJ2EE1_3()
*/
public boolean isJ2EE1_3() {
return getVersionID() == J2EE_1_3_ID;
}
/**
* @deprecated use {@link TranslatorResource#setVersionID(int)},
* {@link TranslatorResource#setDoctypeValues(String, String)}
* Sets the system id of the XML document.
* @see J2EEVersionConstants
*/
public void setPublicId(String id) {
setDoctypeValues(id, getSystemId());
}
/**
* @deprecated use {@link TranslatorResource#setVersionID(int)},
* {@link TranslatorResource#setDoctypeValues(String, String)}
* Sets the public id of the XML document.
* @see J2EEVersionConstants
*/
public void setSystemId(String id) {
setDoctypeValues(getPublicId(), id);
}
@Override
protected String getDefaultPublicId() {
switch (getVersionID()) {
case (J2EE_1_2_ID) :
return getJ2EE_1_2_PublicID();
case (J2EE_1_3_ID) :
return getJ2EE_1_3_PublicID();
default :
return null;
}
}
@Override
protected String getDefaultSystemId() {
switch (getVersionID()) {
case (J2EE_1_2_ID) :
return getJ2EE_1_2_SystemID();
case (J2EE_1_3_ID) :
return getJ2EE_1_3_SystemID();
default :
return null;
}
}
public abstract String getJ2EE_1_2_PublicID();
public abstract String getJ2EE_1_2_SystemID();
/**
* By default just return the proper 1.2 system ID, subclasses may override
* @return alternate string for system ID
*/
public String getJ2EE_Alt_1_2_SystemID() {
return getJ2EE_1_2_SystemID();
}
public abstract String getJ2EE_1_3_PublicID();
public abstract String getJ2EE_1_3_SystemID();
/**
* By default just return the proper 1.3 system ID, subclasses may override
* @return alternate string for system ID
*/
public String getJ2EE_Alt_1_3_SystemID() {
return getJ2EE_1_3_SystemID();
}
@Override
public NotificationChain basicSetResourceSet(ResourceSet aResourceSet, NotificationChain notifications) {
if (aResourceSet == null && this.resourceSet != null)
preDelete();
return super.basicSetResourceSet(aResourceSet, notifications);
}
public Application getApplication() {
return application;
}
/**
* @deprecated - use getJ2EEVersionID() and getModuleVersionID()
*/
@Override
public int getVersionID() {
return getJ2EEVersionID();
}
@Override
public EntityResolver getEntityResolver() {
return J2EEXmlDtDEntityResolver.INSTANCE;
}
/* All subclasses will derive this value based on their module version
*/
public abstract int getJ2EEVersionID();
/* This will be computed during loads of the resource
*/
public int getModuleVersionID() {
return super.getVersionID();
}
protected abstract void syncVersionOfRootObject();
protected String getModuleVersionString() {
int ver = getModuleVersionID();
return new BigDecimal(String.valueOf(ver)).movePointLeft(1).toString();
}
@Override
public void loadExisting(Map options) throws IOException {
boolean localNeedsSync = false;
synchronized (needsSync) {
localNeedsSync = needsSync;
}
if (localNeedsSync) { // Only check sync once for life of this model
IFile file = WorkbenchResourceHelper.getFile(this);
if (!file.isSynchronized(IResource.DEPTH_ZERO))
{
try {
Workspace workspace = (Workspace)file.getWorkspace();
if (workspace.getElementTree().isImmutable())
{
workspace.newWorkingTree();
}
- ((org.eclipse.core.internal.resources.Resource)file).getLocalManager().refresh(file, IResource.DEPTH_ZERO, true, null);
+ ((org.eclipse.core.internal.resources.Resource)file).getLocalManager().refresh(file.getProject(), IResource.DEPTH_INFINITE, true, null);
} catch (CoreException e) {
throw new org.eclipse.emf.ecore.resource.Resource.IOWrappedException(e);
}
}
synchronized (needsSync) {
needsSync = new Boolean(false);
}
}
super.loadExisting(options);
}
}
| true | true | public void loadExisting(Map options) throws IOException {
boolean localNeedsSync = false;
synchronized (needsSync) {
localNeedsSync = needsSync;
}
if (localNeedsSync) { // Only check sync once for life of this model
IFile file = WorkbenchResourceHelper.getFile(this);
if (!file.isSynchronized(IResource.DEPTH_ZERO))
{
try {
Workspace workspace = (Workspace)file.getWorkspace();
if (workspace.getElementTree().isImmutable())
{
workspace.newWorkingTree();
}
((org.eclipse.core.internal.resources.Resource)file).getLocalManager().refresh(file, IResource.DEPTH_ZERO, true, null);
} catch (CoreException e) {
throw new org.eclipse.emf.ecore.resource.Resource.IOWrappedException(e);
}
}
synchronized (needsSync) {
needsSync = new Boolean(false);
}
}
super.loadExisting(options);
}
| public void loadExisting(Map options) throws IOException {
boolean localNeedsSync = false;
synchronized (needsSync) {
localNeedsSync = needsSync;
}
if (localNeedsSync) { // Only check sync once for life of this model
IFile file = WorkbenchResourceHelper.getFile(this);
if (!file.isSynchronized(IResource.DEPTH_ZERO))
{
try {
Workspace workspace = (Workspace)file.getWorkspace();
if (workspace.getElementTree().isImmutable())
{
workspace.newWorkingTree();
}
((org.eclipse.core.internal.resources.Resource)file).getLocalManager().refresh(file.getProject(), IResource.DEPTH_INFINITE, true, null);
} catch (CoreException e) {
throw new org.eclipse.emf.ecore.resource.Resource.IOWrappedException(e);
}
}
synchronized (needsSync) {
needsSync = new Boolean(false);
}
}
super.loadExisting(options);
}
|
diff --git a/src/com/dmdirc/addons/lagdisplay/ServerInfoDialog.java b/src/com/dmdirc/addons/lagdisplay/ServerInfoDialog.java
index a0efd1640..c84891a64 100644
--- a/src/com/dmdirc/addons/lagdisplay/ServerInfoDialog.java
+++ b/src/com/dmdirc/addons/lagdisplay/ServerInfoDialog.java
@@ -1,150 +1,150 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.dmdirc.addons.lagdisplay;
import com.dmdirc.Server;
import com.dmdirc.Main;
import com.dmdirc.ServerManager;
import com.dmdirc.ServerState;
import com.dmdirc.ui.swing.MainFrame;
import com.dmdirc.ui.swing.SwingController;
import com.dmdirc.ui.swing.components.StandardDialog;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import net.miginfocom.swing.MigLayout;
/**
* Shows information about all connected servers.
*
* @author chris
*/
public class ServerInfoDialog extends StandardDialog {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** The parent JPanel. */
private final JPanel parent;
/**
* Creates a new ServerInfoDialog.
*
* @param ldp The {@link LagDisplayPlugin} we're using for info
* @param parent The {@link JPanel} to use for positioning
*/
public ServerInfoDialog(final LagDisplayPlugin ldp, final JPanel parent) {
super((MainFrame) Main.getUI().getMainWindow(), false);
this.parent = parent;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
- setTitle("Reverse buffer search");
+ setTitle("Server info");
final JPanel panel = new JPanel();
panel.setLayout(new MigLayout("ins 3 5 7 5, gap 10 5"));
final List<Server> servers = ServerManager.getServerManager().getServers();
if (servers.isEmpty()) {
panel.add(new JLabel("No open servers."));
} else {
for (Server server : servers) {
panel.add(new JLabel(server.getName()));
- panel.add(new JLabel(server.getNetwork(), JLabel.CENTER), "grow");
+ panel.add(new JLabel(server.getState() == ServerState.CONNECTED ? server.getNetwork() : "---", JLabel.CENTER), "grow");
panel.add(new JLabel(server.getState() == ServerState.CONNECTED ? ldp.getTime(server) : "---", JLabel.RIGHT), "grow, wrap");
}
}
panel.setBackground(UIManager.getColor("ToolTip.background"));
panel.setForeground(UIManager.getColor("ToolTip.foreground"));
add(panel);
setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
setResizable(false);
pack();
final Point point = parent.getLocationOnScreen();
point.translate(parent.getWidth() / 2 - this.getWidth() / 2, - this.getHeight());
final int maxX = SwingController.getMainFrame().getLocationOnScreen().x
+ SwingController.getMainFrame().getWidth() - 10 - getWidth();
point.x = Math.min(maxX, point.x);
setLocation(point);
panel.setBorder(new GappedEtchedBorder());
}
/**
* An {@link EtchedBorder} that leaves a gap in the bottom where the
* lag display panel is.
*/
private class GappedEtchedBorder extends EtchedBorder {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void paintBorder(final Component c, final Graphics g,
final int x, final int y, final int width, final int height) {
int w = width;
int h = height;
g.translate(x, y);
g.setColor(etchType == LOWERED? getShadowColor(c) : getHighlightColor(c));
g.drawLine(0, 0, w-1, 0);
g.drawLine(0, h-1, parent.getLocationOnScreen().x - getLocationOnScreen().x, h-1);
g.drawLine(parent.getWidth() + parent.getLocationOnScreen().x - getLocationOnScreen().x - 2, h-1, w-1, h-1);
g.drawLine(0, 0, 0, h-1);
g.drawLine(w-1, 0, w-1, h-1);
g.translate(-x, -y);
}
}
}
| false | true | public ServerInfoDialog(final LagDisplayPlugin ldp, final JPanel parent) {
super((MainFrame) Main.getUI().getMainWindow(), false);
this.parent = parent;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Reverse buffer search");
final JPanel panel = new JPanel();
panel.setLayout(new MigLayout("ins 3 5 7 5, gap 10 5"));
final List<Server> servers = ServerManager.getServerManager().getServers();
if (servers.isEmpty()) {
panel.add(new JLabel("No open servers."));
} else {
for (Server server : servers) {
panel.add(new JLabel(server.getName()));
panel.add(new JLabel(server.getNetwork(), JLabel.CENTER), "grow");
panel.add(new JLabel(server.getState() == ServerState.CONNECTED ? ldp.getTime(server) : "---", JLabel.RIGHT), "grow, wrap");
}
}
panel.setBackground(UIManager.getColor("ToolTip.background"));
panel.setForeground(UIManager.getColor("ToolTip.foreground"));
add(panel);
setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
setResizable(false);
pack();
final Point point = parent.getLocationOnScreen();
point.translate(parent.getWidth() / 2 - this.getWidth() / 2, - this.getHeight());
final int maxX = SwingController.getMainFrame().getLocationOnScreen().x
+ SwingController.getMainFrame().getWidth() - 10 - getWidth();
point.x = Math.min(maxX, point.x);
setLocation(point);
panel.setBorder(new GappedEtchedBorder());
}
| public ServerInfoDialog(final LagDisplayPlugin ldp, final JPanel parent) {
super((MainFrame) Main.getUI().getMainWindow(), false);
this.parent = parent;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Server info");
final JPanel panel = new JPanel();
panel.setLayout(new MigLayout("ins 3 5 7 5, gap 10 5"));
final List<Server> servers = ServerManager.getServerManager().getServers();
if (servers.isEmpty()) {
panel.add(new JLabel("No open servers."));
} else {
for (Server server : servers) {
panel.add(new JLabel(server.getName()));
panel.add(new JLabel(server.getState() == ServerState.CONNECTED ? server.getNetwork() : "---", JLabel.CENTER), "grow");
panel.add(new JLabel(server.getState() == ServerState.CONNECTED ? ldp.getTime(server) : "---", JLabel.RIGHT), "grow, wrap");
}
}
panel.setBackground(UIManager.getColor("ToolTip.background"));
panel.setForeground(UIManager.getColor("ToolTip.foreground"));
add(panel);
setUndecorated(true);
setFocusableWindowState(false);
setFocusable(false);
setResizable(false);
pack();
final Point point = parent.getLocationOnScreen();
point.translate(parent.getWidth() / 2 - this.getWidth() / 2, - this.getHeight());
final int maxX = SwingController.getMainFrame().getLocationOnScreen().x
+ SwingController.getMainFrame().getWidth() - 10 - getWidth();
point.x = Math.min(maxX, point.x);
setLocation(point);
panel.setBorder(new GappedEtchedBorder());
}
|
diff --git a/client/src/test/java/redis/client/Issue19Test.java b/client/src/test/java/redis/client/Issue19Test.java
index 6190e2c..a274c23 100644
--- a/client/src/test/java/redis/client/Issue19Test.java
+++ b/client/src/test/java/redis/client/Issue19Test.java
@@ -1,39 +1,44 @@
package redis.client;
import com.google.common.base.Charsets;
import com.google.common.util.concurrent.ListenableFuture;
import org.junit.Test;
import redis.Command;
import redis.reply.Reply;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
/**
* https://github.com/spullara/redis-protocol/issues/19
*/
public class Issue19Test {
@Test
public void testExecuteSyntaxError() throws IOException, InterruptedException, ExecutionException {
RedisClient client = new RedisClient("localhost", 6379);
client.multi();
String name = "ZADD";
// Wrong number of arguments for zadd command
Command cmd = new Command(name.getBytes(Charsets.UTF_8),"foo");
ListenableFuture<? extends Reply> f = client.pipeline(name, cmd);
try {
- Future<Boolean> exec = client.exec();
- exec.get();
- f.get();
+ // Fixed in 2.6.5
+ if (client.version < 20605) {
+ Future<Boolean> exec = client.exec();
+ exec.get();
+ f.get();
+ } else {
+ f.get();
+ }
fail("Should have gotten an error");
} catch (ExecutionException re) {
Throwable cause = re.getCause();
assertTrue(cause instanceof RedisException);
assertTrue(cause.getMessage().startsWith("ERR wrong number"));
}
}
}
| true | true | public void testExecuteSyntaxError() throws IOException, InterruptedException, ExecutionException {
RedisClient client = new RedisClient("localhost", 6379);
client.multi();
String name = "ZADD";
// Wrong number of arguments for zadd command
Command cmd = new Command(name.getBytes(Charsets.UTF_8),"foo");
ListenableFuture<? extends Reply> f = client.pipeline(name, cmd);
try {
Future<Boolean> exec = client.exec();
exec.get();
f.get();
fail("Should have gotten an error");
} catch (ExecutionException re) {
Throwable cause = re.getCause();
assertTrue(cause instanceof RedisException);
assertTrue(cause.getMessage().startsWith("ERR wrong number"));
}
}
| public void testExecuteSyntaxError() throws IOException, InterruptedException, ExecutionException {
RedisClient client = new RedisClient("localhost", 6379);
client.multi();
String name = "ZADD";
// Wrong number of arguments for zadd command
Command cmd = new Command(name.getBytes(Charsets.UTF_8),"foo");
ListenableFuture<? extends Reply> f = client.pipeline(name, cmd);
try {
// Fixed in 2.6.5
if (client.version < 20605) {
Future<Boolean> exec = client.exec();
exec.get();
f.get();
} else {
f.get();
}
fail("Should have gotten an error");
} catch (ExecutionException re) {
Throwable cause = re.getCause();
assertTrue(cause instanceof RedisException);
assertTrue(cause.getMessage().startsWith("ERR wrong number"));
}
}
|
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java
index 987594c886..71c8f8c8d9 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java
@@ -1,507 +1,507 @@
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.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CannedTokenStream;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockPayloadAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.English;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.util._TestUtil;
// TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs.
// not all codecs store prx separate...
// TODO: fix sep codec to index offsets so we can greatly reduce this list!
@SuppressCodecs({"MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom"})
public class TestPostingsOffsets extends LuceneTestCase {
IndexWriterConfig iwc;
public void setUp() throws Exception {
super.setUp();
iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
}
public void testBasic() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorPositions(random().nextBoolean());
ft.setStoreTermVectorOffsets(random().nextBoolean());
}
Token[] tokens = new Token[] {
makeToken("a", 1, 0, 6),
makeToken("b", 1, 8, 9),
makeToken("a", 1, 9, 17),
makeToken("c", 1, 19, 50),
};
doc.add(new Field("content", new CannedTokenStream(tokens), ft));
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("a"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(2, dp.freq());
assertEquals(0, dp.nextPosition());
assertEquals(0, dp.startOffset());
assertEquals(6, dp.endOffset());
assertEquals(2, dp.nextPosition());
assertEquals(9, dp.startOffset());
assertEquals(17, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("b"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(1, dp.freq());
assertEquals(1, dp.nextPosition());
assertEquals(8, dp.startOffset());
assertEquals(9, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("c"), true);
assertNotNull(dp);
assertEquals(0, dp.nextDoc());
assertEquals(1, dp.freq());
assertEquals(3, dp.nextPosition());
assertEquals(19, dp.startOffset());
assertEquals(50, dp.endOffset());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
r.close();
dir.close();
}
public void testSkipping() throws Exception {
doTestNumbers(false);
}
public void testPayloads() throws Exception {
doTestNumbers(true);
}
public void doTestNumbers(boolean withPayloads) throws Exception {
Directory dir = newDirectory();
Analyzer analyzer = withPayloads ? new MockPayloadAnalyzer() : new MockAnalyzer(random());
iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
iwc.setMergePolicy(newLogMergePolicy()); // will rely on docids a bit for skipping
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
int numDocs = atLeast(500);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(new Field("numbers", English.intToEnglish(i), ft));
doc.add(new Field("oddeven", (i % 2) == 0 ? "even" : "odd", ft));
doc.add(new StringField("id", "" + i, Field.Store.NO));
w.addDocument(doc);
}
IndexReader reader = w.getReader();
w.close();
String terms[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "hundred" };
for (String term : terms) {
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef(term), true);
int doc;
while((doc = dp.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
String storedNumbers = reader.document(doc).get("numbers");
int freq = dp.freq();
for (int i = 0; i < freq; i++) {
dp.nextPosition();
int start = dp.startOffset();
assert start >= 0;
int end = dp.endOffset();
assert end >= 0 && end >= start;
// check that the offsets correspond to the term in the src text
assertTrue(storedNumbers.substring(start, end).equals(term));
if (withPayloads) {
// check that we have a payload and it starts with "pos"
assertTrue(dp.hasPayload());
BytesRef payload = dp.getPayload();
assertTrue(payload.utf8ToString().startsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
}
// check we can skip correctly
int numSkippingTests = atLeast(50);
for (int j = 0; j < numSkippingTests; j++) {
int num = _TestUtil.nextInt(random(), 100, Math.min(numDocs-1, 999));
DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef("hundred"), true);
int doc = dp.advance(num);
assertEquals(num, doc);
int freq = dp.freq();
for (int i = 0; i < freq; i++) {
String storedNumbers = reader.document(doc).get("numbers");
dp.nextPosition();
int start = dp.startOffset();
assert start >= 0;
int end = dp.endOffset();
assert end >= 0 && end >= start;
// check that the offsets correspond to the term in the src text
assertTrue(storedNumbers.substring(start, end).equals("hundred"));
if (withPayloads) {
// check that we have a payload and it starts with "pos"
assertTrue(dp.hasPayload());
BytesRef payload = dp.getPayload();
assertTrue(payload.utf8ToString().startsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
// check that other fields (without offsets) work correctly
for (int i = 0; i < numDocs; i++) {
DocsEnum dp = MultiFields.getTermDocsEnum(reader, null, "id", new BytesRef("" + i), false);
assertEquals(i, dp.nextDoc());
assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc());
}
reader.close();
dir.close();
}
public void testRandom() throws Exception {
// token -> docID -> tokens
final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>();
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
final int numDocs = atLeast(20);
//final int numDocs = atLeast(5);
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
// TODO: randomize what IndexOptions we use; also test
// changing this up in one IW buffered segment...:
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
for(int docCount=0;docCount<numDocs;docCount++) {
Document doc = new Document();
doc.add(new IntField("id", docCount, Field.Store.NO));
List<Token> tokens = new ArrayList<Token>();
final int numTokens = atLeast(100);
//final int numTokens = atLeast(20);
int pos = -1;
int offset = 0;
//System.out.println("doc id=" + docCount);
for(int tokenCount=0;tokenCount<numTokens;tokenCount++) {
final String text;
if (random().nextBoolean()) {
text = "a";
} else if (random().nextBoolean()) {
text = "b";
} else if (random().nextBoolean()) {
text = "c";
} else {
text = "d";
}
int posIncr = random().nextBoolean() ? 1 : random().nextInt(5);
if (tokenCount == 0 && posIncr == 0) {
posIncr = 1;
}
final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5);
final int tokenOffset = random().nextInt(5);
final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset);
if (!actualTokens.containsKey(text)) {
actualTokens.put(text, new HashMap<Integer,List<Token>>());
}
final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text);
if (!postingsByDoc.containsKey(docCount)) {
postingsByDoc.put(docCount, new ArrayList<Token>());
}
postingsByDoc.get(docCount).add(token);
tokens.add(token);
pos += posIncr;
// stuff abs position into type:
token.setType(""+pos);
offset += offIncr + tokenOffset;
//System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")");
}
doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft));
w.addDocument(doc);
}
final DirectoryReader r = w.getReader();
w.close();
final String[] terms = new String[] {"a", "b", "c", "d"};
for(IndexReader reader : r.getSequentialSubReaders()) {
// TODO: improve this
AtomicReader sub = (AtomicReader) reader;
//System.out.println("\nsub=" + sub);
final TermsEnum termsEnum = sub.fields().terms("content").iterator(null);
DocsEnum docs = null;
DocsAndPositionsEnum docsAndPositions = null;
DocsAndPositionsEnum docsAndPositionsAndOffsets = null;
final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false);
for(String term : terms) {
//System.out.println(" term=" + term);
if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) {
docs = termsEnum.docs(null, docs, true);
assertNotNull(docs);
int doc;
//System.out.println(" doc/freq");
while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docs.freq());
}
docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false);
assertNotNull(docsAndPositions);
//System.out.println(" doc/freq/pos");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
}
}
docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true);
assertNotNull(docsAndPositionsAndOffsets);
//System.out.println(" doc/freq/pos/offs");
- while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+ while((doc = docsAndPositionsAndOffsets.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
- assertEquals(expected.size(), docsAndPositions.freq());
+ assertEquals(expected.size(), docsAndPositionsAndOffsets.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
- assertEquals(pos, docsAndPositions.nextPosition());
- assertEquals(token.startOffset(), docsAndPositions.startOffset());
- assertEquals(token.endOffset(), docsAndPositions.endOffset());
+ assertEquals(pos, docsAndPositionsAndOffsets.nextPosition());
+ assertEquals(token.startOffset(), docsAndPositionsAndOffsets.startOffset());
+ assertEquals(token.endOffset(), docsAndPositionsAndOffsets.endOffset());
}
}
}
}
// TODO: test advance:
}
r.close();
dir.close();
}
public void testWithUnindexedFields() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter riw = new RandomIndexWriter(random(), dir, iwc);
for (int i = 0; i < 100; i++) {
Document doc = new Document();
// ensure at least one doc is indexed with offsets
if (i < 99 && random().nextInt(2) == 0) {
// stored only
FieldType ft = new FieldType();
ft.setIndexed(false);
ft.setStored(true);
doc.add(new Field("foo", "boo!", ft));
} else {
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
// store some term vectors for the checkindex cross-check
ft.setStoreTermVectors(true);
ft.setStoreTermVectorPositions(true);
ft.setStoreTermVectorOffsets(true);
}
doc.add(new Field("foo", "bar", ft));
}
riw.addDocument(doc);
}
CompositeReader ir = riw.getReader();
SlowCompositeReaderWrapper slow = new SlowCompositeReaderWrapper(ir);
FieldInfos fis = slow.getFieldInfos();
assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, fis.fieldInfo("foo").getIndexOptions());
slow.close();
ir.close();
riw.close();
dir.close();
}
public void testAddFieldTwice() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter iw = new RandomIndexWriter(random(), dir);
Document doc = new Document();
FieldType customType3 = new FieldType(TextField.TYPE_STORED);
customType3.setStoreTermVectors(true);
customType3.setStoreTermVectorPositions(true);
customType3.setStoreTermVectorOffsets(true);
customType3.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
doc.add(new Field("content3", "here is more content with aaa aaa aaa", customType3));
doc.add(new Field("content3", "here is more content with aaa aaa aaa", customType3));
iw.addDocument(doc);
iw.close();
dir.close(); // checkindex
}
// NOTE: the next two tests aren't that good as we need an EvilToken...
public void testNegativeOffsets() throws Exception {
try {
checkTokens(new Token[] {
makeToken("foo", 1, -1, -1)
});
fail();
} catch (IllegalArgumentException expected) {
//expected
}
}
public void testIllegalOffsets() throws Exception {
try {
checkTokens(new Token[] {
makeToken("foo", 1, 1, 0)
});
fail();
} catch (IllegalArgumentException expected) {
//expected
}
}
public void testBackwardsOffsets() throws Exception {
try {
checkTokens(new Token[] {
makeToken("foo", 1, 0, 3),
makeToken("foo", 1, 4, 7),
makeToken("foo", 0, 3, 6)
});
fail();
} catch (IllegalArgumentException expected) {
// expected
}
}
public void testStackedTokens() throws Exception {
checkTokens(new Token[] {
makeToken("foo", 1, 0, 3),
makeToken("foo", 0, 0, 3),
makeToken("foo", 0, 0, 3)
});
}
public void testLegalbutVeryLargeOffsets() throws Exception {
Directory dir = newDirectory();
IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, null));
Document doc = new Document();
Token t1 = new Token("foo", 0, Integer.MAX_VALUE-500);
if (random().nextBoolean()) {
t1.setPayload(new BytesRef("test"));
}
Token t2 = new Token("foo", Integer.MAX_VALUE-500, Integer.MAX_VALUE);
TokenStream tokenStream = new CannedTokenStream(
new Token[] { t1, t2 }
);
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
// store some term vectors for the checkindex cross-check
ft.setStoreTermVectors(true);
ft.setStoreTermVectorPositions(true);
ft.setStoreTermVectorOffsets(true);
Field field = new Field("foo", tokenStream, ft);
doc.add(field);
iw.addDocument(doc);
iw.close();
dir.close();
}
// TODO: more tests with other possibilities
private void checkTokens(Token[] tokens) throws IOException {
Directory dir = newDirectory();
RandomIndexWriter riw = new RandomIndexWriter(random(), dir, iwc);
boolean success = false;
try {
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
// store some term vectors for the checkindex cross-check
ft.setStoreTermVectors(true);
ft.setStoreTermVectorPositions(true);
ft.setStoreTermVectorOffsets(true);
Document doc = new Document();
doc.add(new Field("body", new CannedTokenStream(tokens), ft));
riw.addDocument(doc);
success = true;
} finally {
if (success) {
IOUtils.close(riw, dir);
} else {
IOUtils.closeWhileHandlingException(riw, dir);
}
}
}
private Token makeToken(String text, int posIncr, int startOffset, int endOffset) {
final Token t = new Token();
t.append(text);
t.setPositionIncrement(posIncr);
t.setOffset(startOffset, endOffset);
return t;
}
}
| false | true | public void testRandom() throws Exception {
// token -> docID -> tokens
final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>();
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
final int numDocs = atLeast(20);
//final int numDocs = atLeast(5);
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
// TODO: randomize what IndexOptions we use; also test
// changing this up in one IW buffered segment...:
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
for(int docCount=0;docCount<numDocs;docCount++) {
Document doc = new Document();
doc.add(new IntField("id", docCount, Field.Store.NO));
List<Token> tokens = new ArrayList<Token>();
final int numTokens = atLeast(100);
//final int numTokens = atLeast(20);
int pos = -1;
int offset = 0;
//System.out.println("doc id=" + docCount);
for(int tokenCount=0;tokenCount<numTokens;tokenCount++) {
final String text;
if (random().nextBoolean()) {
text = "a";
} else if (random().nextBoolean()) {
text = "b";
} else if (random().nextBoolean()) {
text = "c";
} else {
text = "d";
}
int posIncr = random().nextBoolean() ? 1 : random().nextInt(5);
if (tokenCount == 0 && posIncr == 0) {
posIncr = 1;
}
final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5);
final int tokenOffset = random().nextInt(5);
final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset);
if (!actualTokens.containsKey(text)) {
actualTokens.put(text, new HashMap<Integer,List<Token>>());
}
final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text);
if (!postingsByDoc.containsKey(docCount)) {
postingsByDoc.put(docCount, new ArrayList<Token>());
}
postingsByDoc.get(docCount).add(token);
tokens.add(token);
pos += posIncr;
// stuff abs position into type:
token.setType(""+pos);
offset += offIncr + tokenOffset;
//System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")");
}
doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft));
w.addDocument(doc);
}
final DirectoryReader r = w.getReader();
w.close();
final String[] terms = new String[] {"a", "b", "c", "d"};
for(IndexReader reader : r.getSequentialSubReaders()) {
// TODO: improve this
AtomicReader sub = (AtomicReader) reader;
//System.out.println("\nsub=" + sub);
final TermsEnum termsEnum = sub.fields().terms("content").iterator(null);
DocsEnum docs = null;
DocsAndPositionsEnum docsAndPositions = null;
DocsAndPositionsEnum docsAndPositionsAndOffsets = null;
final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false);
for(String term : terms) {
//System.out.println(" term=" + term);
if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) {
docs = termsEnum.docs(null, docs, true);
assertNotNull(docs);
int doc;
//System.out.println(" doc/freq");
while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docs.freq());
}
docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false);
assertNotNull(docsAndPositions);
//System.out.println(" doc/freq/pos");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
}
}
docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true);
assertNotNull(docsAndPositionsAndOffsets);
//System.out.println(" doc/freq/pos/offs");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
assertEquals(token.startOffset(), docsAndPositions.startOffset());
assertEquals(token.endOffset(), docsAndPositions.endOffset());
}
}
}
}
// TODO: test advance:
}
r.close();
dir.close();
}
| public void testRandom() throws Exception {
// token -> docID -> tokens
final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>();
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
final int numDocs = atLeast(20);
//final int numDocs = atLeast(5);
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
// TODO: randomize what IndexOptions we use; also test
// changing this up in one IW buffered segment...:
ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
if (random().nextBoolean()) {
ft.setStoreTermVectors(true);
ft.setStoreTermVectorOffsets(random().nextBoolean());
ft.setStoreTermVectorPositions(random().nextBoolean());
}
for(int docCount=0;docCount<numDocs;docCount++) {
Document doc = new Document();
doc.add(new IntField("id", docCount, Field.Store.NO));
List<Token> tokens = new ArrayList<Token>();
final int numTokens = atLeast(100);
//final int numTokens = atLeast(20);
int pos = -1;
int offset = 0;
//System.out.println("doc id=" + docCount);
for(int tokenCount=0;tokenCount<numTokens;tokenCount++) {
final String text;
if (random().nextBoolean()) {
text = "a";
} else if (random().nextBoolean()) {
text = "b";
} else if (random().nextBoolean()) {
text = "c";
} else {
text = "d";
}
int posIncr = random().nextBoolean() ? 1 : random().nextInt(5);
if (tokenCount == 0 && posIncr == 0) {
posIncr = 1;
}
final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5);
final int tokenOffset = random().nextInt(5);
final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset);
if (!actualTokens.containsKey(text)) {
actualTokens.put(text, new HashMap<Integer,List<Token>>());
}
final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text);
if (!postingsByDoc.containsKey(docCount)) {
postingsByDoc.put(docCount, new ArrayList<Token>());
}
postingsByDoc.get(docCount).add(token);
tokens.add(token);
pos += posIncr;
// stuff abs position into type:
token.setType(""+pos);
offset += offIncr + tokenOffset;
//System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")");
}
doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft));
w.addDocument(doc);
}
final DirectoryReader r = w.getReader();
w.close();
final String[] terms = new String[] {"a", "b", "c", "d"};
for(IndexReader reader : r.getSequentialSubReaders()) {
// TODO: improve this
AtomicReader sub = (AtomicReader) reader;
//System.out.println("\nsub=" + sub);
final TermsEnum termsEnum = sub.fields().terms("content").iterator(null);
DocsEnum docs = null;
DocsAndPositionsEnum docsAndPositions = null;
DocsAndPositionsEnum docsAndPositionsAndOffsets = null;
final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false);
for(String term : terms) {
//System.out.println(" term=" + term);
if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) {
docs = termsEnum.docs(null, docs, true);
assertNotNull(docs);
int doc;
//System.out.println(" doc/freq");
while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docs.freq());
}
docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false);
assertNotNull(docsAndPositions);
//System.out.println(" doc/freq/pos");
while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositions.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositions.nextPosition());
}
}
docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true);
assertNotNull(docsAndPositionsAndOffsets);
//System.out.println(" doc/freq/pos/offs");
while((doc = docsAndPositionsAndOffsets.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]);
//System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq");
assertNotNull(expected);
assertEquals(expected.size(), docsAndPositionsAndOffsets.freq());
for(Token token : expected) {
int pos = Integer.parseInt(token.type());
//System.out.println(" pos=" + pos);
assertEquals(pos, docsAndPositionsAndOffsets.nextPosition());
assertEquals(token.startOffset(), docsAndPositionsAndOffsets.startOffset());
assertEquals(token.endOffset(), docsAndPositionsAndOffsets.endOffset());
}
}
}
}
// TODO: test advance:
}
r.close();
dir.close();
}
|
diff --git a/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java b/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java
index d85f854..59629ee 100644
--- a/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java
+++ b/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java
@@ -1,415 +1,422 @@
package com.lebelw.Tickets.commands;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.iConomy.*;
import com.iConomy.system.Holdings;
import com.lebelw.Tickets.TConfig;
import com.lebelw.Tickets.TDatabase;
import com.lebelw.Tickets.TLogger;
import com.lebelw.Tickets.TPermissions;
import com.lebelw.Tickets.TTools;
import com.lebelw.Tickets.Tickets;
import com.lebelw.Tickets.extras.DataManager;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @description Handles a command.
* @author Tagette
*/
public class TemplateCmd implements CommandExecutor {
private final Tickets plugin;
DataManager dbm = TDatabase.dbm;
Player target;
int currentticket, ticketarg, amount;
public TemplateCmd(Tickets instance) {
plugin = instance;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean handled = false;
if (is(label, "ticket")) {
if (args == null || args.length == 0) {
handled = true;
if (isPlayer(sender)){
String name = getName(sender);
try{
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'");
if (result != null && result.next()){
sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN));
}
else
sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED));
sendMessage(sender,colorizeText("/ticket help for help",ChatColor.YELLOW));
} catch (SQLException se) {
TLogger.error(se.getMessage());
}
}
}
else {
//Is the first argument give?
if (is(args[0],"help")){
handled = true;
sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN)
+ " version " + colorizeText(Tickets.version, ChatColor.GREEN) + ".");
sendMessage(sender, "Commands:");
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.check", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket <Name>",ChatColor.YELLOW) +" - See semeone's else ticket amount");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
}
+ if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.buy", getPlayer(sender).isOp())){
+ sendMessage(sender,colorizeText("/ticket buy <Amount>",ChatColor.YELLOW) +" - Buy tickets with money.");
+ }
}
else if (is(args[0],"send")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
if (args.length == 1 || args.length == 2){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
return handled;
}
if (!TTools.isInt(args[1])){
if (TTools.isInt(args[2])){
String sendername = ((Player)sender).getName();
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
if (sendername == name){
sendMessage(sender,colorizeText("You can't send ticket(s) to yourself!",ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(sendername)){
currentticket = getPlayerTicket(sendername);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
if (givePlayerTicket(name,ticketarg)){
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}
}else{
sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else {
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
else if(is(args[0],"give")){
handled = true;
//We check the guy permission
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (givePlayerTicket(name,ticketarg)){
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
//Is the first argument take?
else if (is(args[0],"buy")){
handled = true;
- if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
+ if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.buy", getPlayer(sender).isOp())){
+ if (args.length == 1){
+ sendMessage(sender,colorizeText("/ticket buy <Amount>",ChatColor.YELLOW) +" - Buy tickets (No argument gives the cost)");
+ return handled;
+ }
if (plugin.iConomy != null){
if (args[1] != null){
if (TTools.isInt(args[1])){
String name = ((Player)sender).getName();
double amount = Double.parseDouble(args[1]);
int tickets = Integer.parseInt(args[1]);
if (iConomy.hasAccount(name)){
Holdings balance = iConomy.getAccount(name).getHoldings();
double price = amount * TConfig.cost;
if(balance.hasEnough(price)){
if (givePlayerTicket(name,tickets)){
balance.subtract(price);
sendMessage(sender,colorizeText("You just bought ",ChatColor.GREEN) + tickets + colorizeText(" for ",ChatColor.GREEN) + iConomy.format(price));
}
}else{
sendMessage(sender,colorizeText("You don't have enough money! You need ",ChatColor.RED) + colorizeText(iConomy.format(price),ChatColor.WHITE));
}
}else {
sendMessage(sender,colorizeText("You don't have any accounts!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Cost for 1 ticket:",ChatColor.YELLOW) + colorizeText(iConomy.format(TConfig.cost),ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("iConomy must be loaded!",ChatColor.RED));
}
}
}
else if(is(args[0],"take")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been removed from "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText(ticketarg +" ticket(s) has been removed by "+ ((Player)sender).getName() + ".",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
//We check if we want to look at semeone else ticket
}else{
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.check", getPlayer(sender).isOp())){
String name = args[0];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage() + " Type /ticket help for help.",ChatColor.RED));
return handled;
}
int ticket = getPlayerTicket(name);
sendMessage(sender,colorizeText(name + " currently have ",ChatColor.GREEN) + ticket + colorizeText(" ticket(s)",ChatColor.GREEN));
}else{
sendMessage(sender,colorizeText("Type /ticket help for help.",ChatColor.YELLOW));
return handled;
}
}
}
}
return handled;
}
// Simplifies and shortens the if statements for commands.
private boolean is(String entered, String label) {
return entered.equalsIgnoreCase(label);
}
// Checks if the current user is actually a player.
private boolean isPlayer(CommandSender sender) {
return sender != null && sender instanceof Player;
}
// Checks if the current user is actually a player and sends a message to that player.
private boolean sendMessage(CommandSender sender, String message) {
boolean sent = false;
if (isPlayer(sender)) {
Player player = (Player) sender;
player.sendMessage(message);
sent = true;
}
return sent;
}
private boolean sendLog(CommandSender sender, String message) {
boolean sent = false;
if (!isPlayer(sender)) {
TLogger.info(message);
sent = true;
}
return sent;
}
// Checks if the current user is actually a player and returns the name of that player.
private String getName(CommandSender sender) {
String name = "";
if (isPlayer(sender)) {
Player player = (Player) sender;
name = player.getName();
}
return name;
}
// Gets the player if the current user is actually a player.
private Player getPlayer(CommandSender sender) {
Player player = null;
if (isPlayer(sender)) {
player = (Player) sender;
}
return player;
}
private String colorizeText(String text, ChatColor color) {
return color + text + ChatColor.WHITE;
}
/*
* Checks if a player account exists
*
* @param name The full name of the player.
*/
private boolean checkIfPlayerExists(String name)
{
ResultSet result = dbm.query("SELECT id FROM players WHERE name = '" + name + "'");
try {
if (result != null && result.next()){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
TLogger.warning(e.getMessage());
return false;
}
return false;
}
/*
* Get the amount of tickets a player have
*
* @param name The full name of the player.
*/
private int getPlayerTicket(String name){
if (checkIfPlayerExists(name)){
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name = '" + name + "'");
try {
if (result != null && result.next()){
return result.getInt("Ticket");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
TLogger.warning(e.getMessage());
return 0;
}
}else {
return 0;
}
return 0;
}
/*
* Create a player ticket account
*
* @param name The full name of the player.
*/
private boolean createPlayerTicketAccount(String name){
if (!checkIfPlayerExists(name)){
if(dbm.insert("INSERT INTO players(name) VALUES('" + name + "')")){
return true;
}else{
return false;
}
}else{
return false;
}
}
private boolean givePlayerTicket(String name, Integer amount){
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket + amount;
return dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
if (createPlayerTicketAccount(name)){
return dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
return false;
}
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean handled = false;
if (is(label, "ticket")) {
if (args == null || args.length == 0) {
handled = true;
if (isPlayer(sender)){
String name = getName(sender);
try{
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'");
if (result != null && result.next()){
sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN));
}
else
sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED));
sendMessage(sender,colorizeText("/ticket help for help",ChatColor.YELLOW));
} catch (SQLException se) {
TLogger.error(se.getMessage());
}
}
}
else {
//Is the first argument give?
if (is(args[0],"help")){
handled = true;
sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN)
+ " version " + colorizeText(Tickets.version, ChatColor.GREEN) + ".");
sendMessage(sender, "Commands:");
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.check", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket <Name>",ChatColor.YELLOW) +" - See semeone's else ticket amount");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
}
}
else if (is(args[0],"send")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
if (args.length == 1 || args.length == 2){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
return handled;
}
if (!TTools.isInt(args[1])){
if (TTools.isInt(args[2])){
String sendername = ((Player)sender).getName();
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
if (sendername == name){
sendMessage(sender,colorizeText("You can't send ticket(s) to yourself!",ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(sendername)){
currentticket = getPlayerTicket(sendername);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
if (givePlayerTicket(name,ticketarg)){
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}
}else{
sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else {
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
else if(is(args[0],"give")){
handled = true;
//We check the guy permission
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (givePlayerTicket(name,ticketarg)){
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
//Is the first argument take?
else if (is(args[0],"buy")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
if (plugin.iConomy != null){
if (args[1] != null){
if (TTools.isInt(args[1])){
String name = ((Player)sender).getName();
double amount = Double.parseDouble(args[1]);
int tickets = Integer.parseInt(args[1]);
if (iConomy.hasAccount(name)){
Holdings balance = iConomy.getAccount(name).getHoldings();
double price = amount * TConfig.cost;
if(balance.hasEnough(price)){
if (givePlayerTicket(name,tickets)){
balance.subtract(price);
sendMessage(sender,colorizeText("You just bought ",ChatColor.GREEN) + tickets + colorizeText(" for ",ChatColor.GREEN) + iConomy.format(price));
}
}else{
sendMessage(sender,colorizeText("You don't have enough money! You need ",ChatColor.RED) + colorizeText(iConomy.format(price),ChatColor.WHITE));
}
}else {
sendMessage(sender,colorizeText("You don't have any accounts!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Cost for 1 ticket:",ChatColor.YELLOW) + colorizeText(iConomy.format(TConfig.cost),ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("iConomy must be loaded!",ChatColor.RED));
}
}
}
else if(is(args[0],"take")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been removed from "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText(ticketarg +" ticket(s) has been removed by "+ ((Player)sender).getName() + ".",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
//We check if we want to look at semeone else ticket
}else{
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.check", getPlayer(sender).isOp())){
String name = args[0];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage() + " Type /ticket help for help.",ChatColor.RED));
return handled;
}
int ticket = getPlayerTicket(name);
sendMessage(sender,colorizeText(name + " currently have ",ChatColor.GREEN) + ticket + colorizeText(" ticket(s)",ChatColor.GREEN));
}else{
sendMessage(sender,colorizeText("Type /ticket help for help.",ChatColor.YELLOW));
return handled;
}
}
}
}
return handled;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean handled = false;
if (is(label, "ticket")) {
if (args == null || args.length == 0) {
handled = true;
if (isPlayer(sender)){
String name = getName(sender);
try{
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'");
if (result != null && result.next()){
sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN));
}
else
sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED));
sendMessage(sender,colorizeText("/ticket help for help",ChatColor.YELLOW));
} catch (SQLException se) {
TLogger.error(se.getMessage());
}
}
}
else {
//Is the first argument give?
if (is(args[0],"help")){
handled = true;
sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN)
+ " version " + colorizeText(Tickets.version, ChatColor.GREEN) + ".");
sendMessage(sender, "Commands:");
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.check", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket <Name>",ChatColor.YELLOW) +" - See semeone's else ticket amount");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.buy", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket buy <Amount>",ChatColor.YELLOW) +" - Buy tickets with money.");
}
}
else if (is(args[0],"send")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
if (args.length == 1 || args.length == 2){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
return handled;
}
if (!TTools.isInt(args[1])){
if (TTools.isInt(args[2])){
String sendername = ((Player)sender).getName();
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
if (sendername == name){
sendMessage(sender,colorizeText("You can't send ticket(s) to yourself!",ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(sendername)){
currentticket = getPlayerTicket(sendername);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
if (givePlayerTicket(name,ticketarg)){
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}
}else{
sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else {
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
else if(is(args[0],"give")){
handled = true;
//We check the guy permission
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (givePlayerTicket(name,ticketarg)){
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
//Is the first argument take?
else if (is(args[0],"buy")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.buy", getPlayer(sender).isOp())){
if (args.length == 1){
sendMessage(sender,colorizeText("/ticket buy <Amount>",ChatColor.YELLOW) +" - Buy tickets (No argument gives the cost)");
return handled;
}
if (plugin.iConomy != null){
if (args[1] != null){
if (TTools.isInt(args[1])){
String name = ((Player)sender).getName();
double amount = Double.parseDouble(args[1]);
int tickets = Integer.parseInt(args[1]);
if (iConomy.hasAccount(name)){
Holdings balance = iConomy.getAccount(name).getHoldings();
double price = amount * TConfig.cost;
if(balance.hasEnough(price)){
if (givePlayerTicket(name,tickets)){
balance.subtract(price);
sendMessage(sender,colorizeText("You just bought ",ChatColor.GREEN) + tickets + colorizeText(" for ",ChatColor.GREEN) + iConomy.format(price));
}
}else{
sendMessage(sender,colorizeText("You don't have enough money! You need ",ChatColor.RED) + colorizeText(iConomy.format(price),ChatColor.WHITE));
}
}else {
sendMessage(sender,colorizeText("You don't have any accounts!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Cost for 1 ticket:",ChatColor.YELLOW) + colorizeText(iConomy.format(TConfig.cost),ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("iConomy must be loaded!",ChatColor.RED));
}
}
}
else if(is(args[0],"take")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been removed from "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText(ticketarg +" ticket(s) has been removed by "+ ((Player)sender).getName() + ".",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
//We check if we want to look at semeone else ticket
}else{
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.check", getPlayer(sender).isOp())){
String name = args[0];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage() + " Type /ticket help for help.",ChatColor.RED));
return handled;
}
int ticket = getPlayerTicket(name);
sendMessage(sender,colorizeText(name + " currently have ",ChatColor.GREEN) + ticket + colorizeText(" ticket(s)",ChatColor.GREEN));
}else{
sendMessage(sender,colorizeText("Type /ticket help for help.",ChatColor.YELLOW));
return handled;
}
}
}
}
return handled;
}
|
diff --git a/src/main/java/com/googlecode/gwtphonegap/client/inappbrowser/js/InAppBrowserReferenceJsImpl.java b/src/main/java/com/googlecode/gwtphonegap/client/inappbrowser/js/InAppBrowserReferenceJsImpl.java
index 39805a0..4f0681f 100644
--- a/src/main/java/com/googlecode/gwtphonegap/client/inappbrowser/js/InAppBrowserReferenceJsImpl.java
+++ b/src/main/java/com/googlecode/gwtphonegap/client/inappbrowser/js/InAppBrowserReferenceJsImpl.java
@@ -1,122 +1,122 @@
/*
* Copyright 2013 Daniel Kurka
*
* 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.googlecode.gwtphonegap.client.inappbrowser.js;
import com.google.gwt.core.client.JavaScriptObject;
import com.googlecode.gwtphonegap.client.inappbrowser.InAppBrowserCallback;
import com.googlecode.gwtphonegap.client.inappbrowser.InAppBrowserReferenceBaseImpl;
public class InAppBrowserReferenceJsImpl extends InAppBrowserReferenceBaseImpl {
private final JavaScriptObject jsWindowRef;
public InAppBrowserReferenceJsImpl(JavaScriptObject jsWindowRef) {
this.jsWindowRef = jsWindowRef;
}
@Override
public native void close() /*-{
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
ref.close();
}-*/;
@Override
protected native void addJavaScriptHandlers() /*-{
var that = this;
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var loadStart = function(event) {
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadStartEvent(Ljava/lang/String;)(event.url);
};
var loadStop = function(event) {
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadStopEvent(Ljava/lang/String;)(event.url);
};
var loadError = function(event){
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadErrorEvent(Ljava/lang/String;)(event.url);
}
var exit = function(event) {
ref.removeEventListener("loadstart", loadStart);
ref.removeEventListener("loadstop", loadStop);
- ref.removeEventListener("loaderror",loadError);
+ ref.removeEventListener("loaderror",loadError);
ref.removeEventListener("exit", exit);
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireExitEvent()();
};
ref.addEventListener("loadstart", loadStart);
ref.addEventListener("loadstop", loadStop);
- ref.addEventListener("loaderror",loadError);
+ ref.addEventListener("loaderror",loadError);
ref.addEventListener("exit", exit);
}-*/;
@Override
public native void show() /*-{
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
ref.show();
}-*/;
@Override
public native void executeScript(String code, InAppBrowserCallback callback) /*-{
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var script = {code: code};
var c = function(){
callback.@com.googlecode.gwtphonegap.client.inappbrowser.InAppBrowserCallback::done()();
};
ref.executeScript(script, $entry(c));
}-*/;
@Override
public native void executeScriptFromUrl(String url, InAppBrowserCallback callback) /*-{
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var script = {file: url};
var c = function(){
callback.@com.googlecode.gwtphonegap.client.inappbrowser.InAppBrowserCallback::done()();
};
ref.executeScript(script, $entry(c));
}-*/;
@Override
public native void injectCss(String css, InAppBrowserCallback callback) /*-{
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var script = {code: css};
var c = function(){
callback.@com.googlecode.gwtphonegap.client.inappbrowser.InAppBrowserCallback::done()();
};
ref.insertCSS(script, $entry(c));
}-*/;
@Override
public native void injectCssFromUrl(String url, InAppBrowserCallback callback) /*-{
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var script = {file: url};
var c = function(){
callback.@com.googlecode.gwtphonegap.client.inappbrowser.InAppBrowserCallback::done()();
};
ref.insertCSS(script, $entry(c));
}-*/;
}
| false | true | protected native void addJavaScriptHandlers() /*-{
var that = this;
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var loadStart = function(event) {
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadStartEvent(Ljava/lang/String;)(event.url);
};
var loadStop = function(event) {
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadStopEvent(Ljava/lang/String;)(event.url);
};
var loadError = function(event){
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadErrorEvent(Ljava/lang/String;)(event.url);
}
var exit = function(event) {
ref.removeEventListener("loadstart", loadStart);
ref.removeEventListener("loadstop", loadStop);
ref.removeEventListener("loaderror",loadError);
ref.removeEventListener("exit", exit);
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireExitEvent()();
};
ref.addEventListener("loadstart", loadStart);
ref.addEventListener("loadstop", loadStop);
ref.addEventListener("loaderror",loadError);
ref.addEventListener("exit", exit);
}-*/;
| protected native void addJavaScriptHandlers() /*-{
var that = this;
var ref = this.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::jsWindowRef;
var loadStart = function(event) {
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadStartEvent(Ljava/lang/String;)(event.url);
};
var loadStop = function(event) {
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadStopEvent(Ljava/lang/String;)(event.url);
};
var loadError = function(event){
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireLoadErrorEvent(Ljava/lang/String;)(event.url);
}
var exit = function(event) {
ref.removeEventListener("loadstart", loadStart);
ref.removeEventListener("loadstop", loadStop);
ref.removeEventListener("loaderror",loadError);
ref.removeEventListener("exit", exit);
that.@com.googlecode.gwtphonegap.client.inappbrowser.js.InAppBrowserReferenceJsImpl::fireExitEvent()();
};
ref.addEventListener("loadstart", loadStart);
ref.addEventListener("loadstop", loadStop);
ref.addEventListener("loaderror",loadError);
ref.addEventListener("exit", exit);
}-*/;
|
diff --git a/CSipSimple/src/com/csipsimple/wizards/impl/Expert.java b/CSipSimple/src/com/csipsimple/wizards/impl/Expert.java
index 584e059e..2e5385a8 100644
--- a/CSipSimple/src/com/csipsimple/wizards/impl/Expert.java
+++ b/CSipSimple/src/com/csipsimple/wizards/impl/Expert.java
@@ -1,251 +1,255 @@
/**
* Copyright (C) 2010 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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 3 of the License, or
* (at your option) any later version.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.wizards.impl;
import java.util.HashMap;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.text.TextUtils;
import com.csipsimple.R;
import com.csipsimple.api.SipProfile;
import com.csipsimple.utils.Log;
public class Expert extends BaseImplementation {
private static final String THIS_FILE = "Expert";
private EditTextPreference accountDisplayName;
private EditTextPreference accountAccId;
private EditTextPreference accountRegUri;
private EditTextPreference accountUserName;
private EditTextPreference accountData;
private ListPreference accountDataType;
private EditTextPreference accountRealm;
private ListPreference accountScheme;
private ListPreference accountTransport;
private CheckBoxPreference accountPublishEnabled;
private EditTextPreference accountRegTimeout;
private EditTextPreference accountKaInterval;
private EditTextPreference accountForceContact;
private CheckBoxPreference accountAllowContactRewrite;
private ListPreference accountContactRewriteMethod;
private EditTextPreference accountProxy;
private ListPreference accountUseSrtp;
private void bindFields() {
accountDisplayName = (EditTextPreference) parent.findPreference("display_name");
accountAccId = (EditTextPreference) parent.findPreference("acc_id");
accountRegUri = (EditTextPreference) parent.findPreference("reg_uri");
accountRealm = (EditTextPreference) parent.findPreference("realm");
accountUserName = (EditTextPreference) parent.findPreference("username");
accountData = (EditTextPreference) parent.findPreference("data");
accountDataType = (ListPreference) parent.findPreference("data_type");
accountScheme = (ListPreference) parent.findPreference("scheme");
accountTransport = (ListPreference) parent.findPreference("transport");
accountUseSrtp = (ListPreference) parent.findPreference("use_srtp");
accountPublishEnabled = (CheckBoxPreference) parent.findPreference("publish_enabled");
accountRegTimeout = (EditTextPreference) parent.findPreference("reg_timeout");
accountKaInterval = (EditTextPreference) parent.findPreference("ka_interval");
accountForceContact = (EditTextPreference) parent.findPreference("force_contact");
accountAllowContactRewrite = (CheckBoxPreference) parent.findPreference("allow_contact_rewrite");
accountContactRewriteMethod = (ListPreference) parent.findPreference("contact_rewrite_method");
accountProxy = (EditTextPreference) parent.findPreference("proxy");
}
public void fillLayout(final SipProfile account) {
bindFields();
accountDisplayName.setText(account.display_name);
accountAccId.setText(account.acc_id);
accountRegUri.setText(account.reg_uri);
accountRealm.setText(account.realm);
accountUserName.setText(account.username);
accountData.setText(account.data);
{
String scheme = account.scheme;
if (scheme != null && !scheme.equals("")) {
accountScheme.setValue(scheme);
} else {
accountScheme.setValue("Digest");
}
}
{
int ctype = account.datatype;
if (ctype == SipProfile.CRED_DATA_PLAIN_PASSWD) {
accountDataType.setValueIndex(0);
} else if (ctype == SipProfile.CRED_DATA_DIGEST) {
accountDataType.setValueIndex(1);
}
//DISABLED SINCE NOT SUPPORTED YET
/*
else if (ctype ==SipProfile.CRED_CRED_DATA_EXT_AKA) {
accountDataType.setValueIndex(2);
} */else {
accountDataType.setValueIndex(0);
}
}
accountTransport.setValue(account.transport.toString());
accountPublishEnabled.setChecked((account.publish_enabled == 1));
accountRegTimeout.setText(Long.toString(account.reg_timeout));
accountKaInterval.setText(Long.toString(account.ka_interval));
accountForceContact.setText(account.force_contact);
accountAllowContactRewrite.setChecked(account.allow_contact_rewrite);
accountContactRewriteMethod.setValue(Integer.toString(account.contact_rewrite_method));
- accountProxy.setText(TextUtils.join(SipProfile.PROXIES_SEPARATOR, account.proxies));
+ if(account.proxies != null) {
+ accountProxy.setText(TextUtils.join(SipProfile.PROXIES_SEPARATOR, account.proxies));
+ }else {
+ accountProxy.setText("");
+ }
Log.d(THIS_FILE, "use srtp : "+account.use_srtp);
accountUseSrtp.setValueIndex(account.use_srtp);
}
public void updateDescriptions() {
setStringFieldSummary("display_name");
setStringFieldSummary("acc_id");
setStringFieldSummary("reg_uri");
setStringFieldSummary("realm");
setStringFieldSummary("username");
setStringFieldSummary("proxy");
setPasswordFieldSummary("data");
}
private static HashMap<String, Integer>SUMMARIES = new HashMap<String, Integer>(){/**
*
*/
private static final long serialVersionUID = -5469900404720631144L;
{
put("display_name", R.string.w_common_display_name_desc);
put("acc_id", R.string.w_expert_acc_id_desc);
put("reg_uri", R.string.w_expert_reg_uri_desc);
put("realm", R.string.w_expert_realm_desc);
put("username", R.string.w_expert_username_desc);
put("proxy", R.string.w_expert_proxy_desc);
put("data", R.string.w_expert_data_desc);
}};
@Override
public String getDefaultFieldSummary(String fieldName) {
Integer res = SUMMARIES.get(fieldName);
if(res != null) {
return parent.getString( res );
}
return "";
}
public boolean canSave() {
boolean isValid = true;
isValid &= checkField(accountDisplayName, isEmpty(accountDisplayName));
isValid &= checkField(accountAccId, isEmpty(accountAccId) || !isMatching(accountAccId, "[^<]*<sip(s)?:[^@]*@[^@]*>"));
isValid &= checkField(accountRegUri, isEmpty(accountRegUri) || !isMatching(accountRegUri, "sip(s)?:.*"));
isValid &= checkField(accountProxy, !isEmpty(accountProxy) && !isMatching(accountProxy, "sip(s)?:.*"));
return isValid;
}
public SipProfile buildAccount(SipProfile account) {
account.display_name = accountDisplayName.getText();
try {
account.transport = Integer.parseInt(accountTransport.getValue());
}catch(NumberFormatException e) {
Log.e(THIS_FILE, "Transport is not a number");
}
account.acc_id = getText(accountAccId);
account.reg_uri = getText(accountRegUri);
try {
account.use_srtp = Integer.parseInt(accountUseSrtp.getValue());
}catch(NumberFormatException e) {
Log.e(THIS_FILE, "Use srtp is not a number");
}
if (!isEmpty(accountUserName)) {
account.realm = getText(accountRealm);
account.username = getText(accountUserName);
account.data = getText(accountData);
account.scheme = accountScheme.getValue();
String dataType = accountDataType.getValue();
if(dataType.equalsIgnoreCase("0")) {
account.datatype = SipProfile.CRED_DATA_PLAIN_PASSWD;
}else if(dataType.equalsIgnoreCase("1")){
account.datatype = SipProfile.CRED_DATA_DIGEST;
}
//DISABLED SINCE NOT SUPPORTED YET
/*else if(dataType.equalsIgnoreCase("16")){
ci.setData_type(SipProfile.CRED_DATA_EXT_AKA);
} */else {
account.datatype = SipProfile.CRED_DATA_PLAIN_PASSWD;
}
} else {
account.realm = "";
account.username = "";
account.data = "";
account.scheme = "Digest";
account.datatype = SipProfile.CRED_DATA_PLAIN_PASSWD;
}
account.publish_enabled = accountPublishEnabled.isChecked() ? 1 : 0;
try {
account.reg_timeout = Integer.parseInt(accountRegTimeout.getText());
} catch (NumberFormatException e) {
account.reg_timeout = 0;
}
try {
account.ka_interval = Integer.parseInt(accountKaInterval.getText());
} catch (NumberFormatException e) {
account.ka_interval = 0;
}
try {
account.contact_rewrite_method = Integer.parseInt(accountContactRewriteMethod.getValue());
} catch (NumberFormatException e) {
//DO nothing
}
account.allow_contact_rewrite = accountAllowContactRewrite.isChecked();
String forceContact = accountForceContact.getText();
if(!TextUtils.isEmpty(forceContact)) {
account.force_contact = getText(accountForceContact);
}
if (!isEmpty(accountProxy)) {
account.proxies = new String[] { accountProxy.getText() };
} else {
account.proxies = null;
}
return account;
}
@Override
public int getBasePreferenceResource() {
return R.xml.w_expert_preferences;
}
@Override
public boolean needRestart() {
return false;
}
}
| true | true | public void fillLayout(final SipProfile account) {
bindFields();
accountDisplayName.setText(account.display_name);
accountAccId.setText(account.acc_id);
accountRegUri.setText(account.reg_uri);
accountRealm.setText(account.realm);
accountUserName.setText(account.username);
accountData.setText(account.data);
{
String scheme = account.scheme;
if (scheme != null && !scheme.equals("")) {
accountScheme.setValue(scheme);
} else {
accountScheme.setValue("Digest");
}
}
{
int ctype = account.datatype;
if (ctype == SipProfile.CRED_DATA_PLAIN_PASSWD) {
accountDataType.setValueIndex(0);
} else if (ctype == SipProfile.CRED_DATA_DIGEST) {
accountDataType.setValueIndex(1);
}
//DISABLED SINCE NOT SUPPORTED YET
/*
else if (ctype ==SipProfile.CRED_CRED_DATA_EXT_AKA) {
accountDataType.setValueIndex(2);
} */else {
accountDataType.setValueIndex(0);
}
}
accountTransport.setValue(account.transport.toString());
accountPublishEnabled.setChecked((account.publish_enabled == 1));
accountRegTimeout.setText(Long.toString(account.reg_timeout));
accountKaInterval.setText(Long.toString(account.ka_interval));
accountForceContact.setText(account.force_contact);
accountAllowContactRewrite.setChecked(account.allow_contact_rewrite);
accountContactRewriteMethod.setValue(Integer.toString(account.contact_rewrite_method));
accountProxy.setText(TextUtils.join(SipProfile.PROXIES_SEPARATOR, account.proxies));
Log.d(THIS_FILE, "use srtp : "+account.use_srtp);
accountUseSrtp.setValueIndex(account.use_srtp);
}
| public void fillLayout(final SipProfile account) {
bindFields();
accountDisplayName.setText(account.display_name);
accountAccId.setText(account.acc_id);
accountRegUri.setText(account.reg_uri);
accountRealm.setText(account.realm);
accountUserName.setText(account.username);
accountData.setText(account.data);
{
String scheme = account.scheme;
if (scheme != null && !scheme.equals("")) {
accountScheme.setValue(scheme);
} else {
accountScheme.setValue("Digest");
}
}
{
int ctype = account.datatype;
if (ctype == SipProfile.CRED_DATA_PLAIN_PASSWD) {
accountDataType.setValueIndex(0);
} else if (ctype == SipProfile.CRED_DATA_DIGEST) {
accountDataType.setValueIndex(1);
}
//DISABLED SINCE NOT SUPPORTED YET
/*
else if (ctype ==SipProfile.CRED_CRED_DATA_EXT_AKA) {
accountDataType.setValueIndex(2);
} */else {
accountDataType.setValueIndex(0);
}
}
accountTransport.setValue(account.transport.toString());
accountPublishEnabled.setChecked((account.publish_enabled == 1));
accountRegTimeout.setText(Long.toString(account.reg_timeout));
accountKaInterval.setText(Long.toString(account.ka_interval));
accountForceContact.setText(account.force_contact);
accountAllowContactRewrite.setChecked(account.allow_contact_rewrite);
accountContactRewriteMethod.setValue(Integer.toString(account.contact_rewrite_method));
if(account.proxies != null) {
accountProxy.setText(TextUtils.join(SipProfile.PROXIES_SEPARATOR, account.proxies));
}else {
accountProxy.setText("");
}
Log.d(THIS_FILE, "use srtp : "+account.use_srtp);
accountUseSrtp.setValueIndex(account.use_srtp);
}
|
diff --git a/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-repositories/xwiki-commons-extension-repository-maven/src/main/java/org/xwiki/extension/repository/aether/internal/AetherExtensionRepository.java b/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-repositories/xwiki-commons-extension-repository-maven/src/main/java/org/xwiki/extension/repository/aether/internal/AetherExtensionRepository.java
index bfd911140..6071d4220 100644
--- a/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-repositories/xwiki-commons-extension-repository-maven/src/main/java/org/xwiki/extension/repository/aether/internal/AetherExtensionRepository.java
+++ b/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-repositories/xwiki-commons-extension-repository-maven/src/main/java/org/xwiki/extension/repository/aether/internal/AetherExtensionRepository.java
@@ -1,488 +1,490 @@
/*
* 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.extension.repository.aether.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Developer;
import org.apache.maven.model.License;
import org.apache.maven.model.Model;
import org.codehaus.plexus.PlexusContainer;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.ArtifactProperties;
import org.eclipse.aether.artifact.ArtifactType;
import org.eclipse.aether.artifact.ArtifactTypeRegistry;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.artifact.DefaultArtifactType;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.Exclusion;
import org.eclipse.aether.impl.ArtifactDescriptorReader;
import org.eclipse.aether.impl.VersionRangeResolver;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactDescriptorRequest;
import org.eclipse.aether.resolution.ArtifactDescriptorResult;
import org.eclipse.aether.resolution.VersionRangeRequest;
import org.eclipse.aether.resolution.VersionRangeResolutionException;
import org.eclipse.aether.resolution.VersionRangeResult;
import org.eclipse.aether.util.repository.AuthenticationBuilder;
import org.eclipse.aether.util.version.GenericVersionScheme;
import org.eclipse.aether.version.InvalidVersionSpecificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.extension.DefaultExtensionAuthor;
import org.xwiki.extension.Extension;
import org.xwiki.extension.ExtensionDependency;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.ExtensionLicense;
import org.xwiki.extension.ExtensionLicenseManager;
import org.xwiki.extension.ResolveException;
import org.xwiki.extension.repository.AbstractExtensionRepository;
import org.xwiki.extension.repository.ExtensionRepositoryDescriptor;
import org.xwiki.extension.repository.aether.internal.util.DefaultJavaNetProxySelector;
import org.xwiki.extension.repository.result.CollectionIterableResult;
import org.xwiki.extension.repository.result.IterableResult;
import org.xwiki.extension.version.Version;
import org.xwiki.extension.version.VersionConstraint;
import org.xwiki.extension.version.VersionRange;
import org.xwiki.extension.version.internal.DefaultVersion;
import org.xwiki.properties.ConverterManager;
/**
* @version $Id$
* @since 4.0M1
*/
public class AetherExtensionRepository extends AbstractExtensionRepository
{
public static final String MPKEYPREFIX = "xwiki.extension.";
public static final String MPNAME_NAME = "name";
public static final String MPNAME_SUMMARY = "summary";
public static final String MPNAME_WEBSITE = "website";
public static final String MPNAME_FEATURES = "features";
/**
* Used to parse the version.
*/
private static final GenericVersionScheme AETHERVERSIONSCHEME = new GenericVersionScheme();
private static final Logger LOGGER = LoggerFactory.getLogger(AetherExtensionRepository.class);
private transient PlexusContainer plexusContainer;
private transient RemoteRepository remoteRepository;
private transient ArtifactDescriptorReader mavenDescriptorReader;
private transient VersionRangeResolver versionRangeResolver;
private transient ConverterManager converter;
private transient ExtensionLicenseManager licenseManager;
private transient AetherExtensionRepositoryFactory repositoryFactory;
private transient Method loadPomMethod;
public AetherExtensionRepository(ExtensionRepositoryDescriptor repositoryDescriptor,
AetherExtensionRepositoryFactory repositoryFactory, PlexusContainer plexusContainer,
ComponentManager componentManager) throws Exception
{
super(repositoryDescriptor);
this.repositoryFactory = repositoryFactory;
this.plexusContainer = plexusContainer;
RemoteRepository.Builder repositoryBuilder =
new RemoteRepository.Builder(repositoryDescriptor.getId(), "default", repositoryDescriptor.getURI()
.toString());
// Authentication
String username = getDescriptor().getProperty("auth.user");
if (username != null) {
AuthenticationBuilder authenticationBuilder = new AuthenticationBuilder();
authenticationBuilder.addUsername(username);
authenticationBuilder.addPassword(getDescriptor().getProperty("auth.password"));
repositoryBuilder.setAuthentication(authenticationBuilder.build());
}
// Proxy
try {
repositoryBuilder.setProxy(DefaultJavaNetProxySelector.determineProxy(repositoryDescriptor.getURI()));
} catch (Exception e) {
LOGGER.warn("Unexpected exception when trying to find a proxy for [{}]", repositoryDescriptor.getURI());
}
this.remoteRepository = repositoryBuilder.build();
this.converter = componentManager.getInstance(ConverterManager.class);
this.licenseManager = componentManager.getInstance(ExtensionLicenseManager.class);
this.versionRangeResolver = this.plexusContainer.lookup(VersionRangeResolver.class);
this.mavenDescriptorReader = this.plexusContainer.lookup(ArtifactDescriptorReader.class);
// FIXME: not very nice
// * use a private method of a library we don't control is not the nicest thing. But it's a big and very
// usefull method. A shame its not a bit more public.
// * having to parse the pom.xml since we are supposed to support anything supported by AETHER is not
// very clean either. But AETHER almost resolve nothing, not even the type of the artifact, we pretty
// much get only dependencies and licenses.
this.loadPomMethod =
this.mavenDescriptorReader.getClass().getDeclaredMethod("loadPom", RepositorySystemSession.class,
ArtifactDescriptorRequest.class, ArtifactDescriptorResult.class);
this.loadPomMethod.setAccessible(true);
}
protected RepositorySystemSession createRepositorySystemSession()
{
return this.repositoryFactory.createRepositorySystemSession();
}
@Override
public Extension resolve(ExtensionId extensionId) throws ResolveException
{
if (getDescriptor().getType().equals("maven") && this.mavenDescriptorReader != null) {
return resolveMaven(extensionId);
} else {
// FIXME: impossible to resolve extension type as well as most of the information with pure Aether API
throw new ResolveException("Unsupported");
}
}
@Override
public Extension resolve(ExtensionDependency extensionDependency) throws ResolveException
{
if (getDescriptor().getType().equals("maven") && this.mavenDescriptorReader != null) {
return resolveMaven(extensionDependency);
} else {
// FIXME: impossible to resolve extension type as well as most of the information with pure Aether API
throw new ResolveException("Unsupported");
}
}
@Override
public IterableResult<Version> resolveVersions(String id, int offset, int nb) throws ResolveException
{
Artifact artifact = AetherUtils.createArtifact(id, "(,)");
List<org.eclipse.aether.version.Version> versions;
try {
versions = resolveVersions(artifact, createRepositorySystemSession());
if (versions.isEmpty()) {
throw new ResolveException("No versions available for id [" + id + "]");
}
} catch (VersionRangeResolutionException e) {
throw new ResolveException("Failed to resolve versions for id [" + id + "]", e);
}
if (nb == 0 || offset >= versions.size()) {
return new CollectionIterableResult<Version>(versions.size(), offset, Collections.<Version> emptyList());
}
int fromId = offset < 0 ? 0 : offset;
int toId = offset + nb > versions.size() || nb < 0 ? versions.size() : offset + nb;
List<Version> result = new ArrayList<Version>(toId - fromId);
for (int i = fromId; i < toId; ++i) {
result.add(new DefaultVersion(versions.get(i).toString()));
}
return new CollectionIterableResult<Version>(versions.size(), offset, result);
}
private org.eclipse.aether.version.Version resolveVersionConstraint(String id, VersionConstraint versionConstraint,
RepositorySystemSession session) throws ResolveException
{
if (versionConstraint.getVersion() != null) {
try {
return AETHERVERSIONSCHEME.parseVersion(versionConstraint.getVersion().getValue());
} catch (InvalidVersionSpecificationException e) {
throw new ResolveException("Invalid version [" + versionConstraint.getVersion() + "]", e);
}
}
List<org.eclipse.aether.version.Version> commonVersions = null;
for (VersionRange range : versionConstraint.getRanges()) {
List<org.eclipse.aether.version.Version> versions = resolveVersionRange(id, range, session);
if (commonVersions == null) {
commonVersions =
versionConstraint.getRanges().size() > 1 ? new ArrayList<org.eclipse.aether.version.Version>(
versions) : versions;
} else {
// Find commons versions between all the ranges of the constraint
for (Iterator<org.eclipse.aether.version.Version> it = commonVersions.iterator(); it.hasNext();) {
org.eclipse.aether.version.Version version = it.next();
if (!versions.contains(version)) {
it.remove();
}
}
}
}
if (commonVersions.isEmpty()) {
throw new ResolveException("No versions available for id [" + id + "] and version constraint ["
+ versionConstraint + "]");
}
return commonVersions.get(commonVersions.size() - 1);
}
private List<org.eclipse.aether.version.Version> resolveVersionRange(String id, VersionRange versionRange,
RepositorySystemSession session) throws ResolveException
{
Artifact artifact = AetherUtils.createArtifact(id, versionRange.getValue());
try {
List<org.eclipse.aether.version.Version> versions = resolveVersions(artifact, session);
if (versions.isEmpty()) {
throw new ResolveException("No versions available for id [" + id + "] and version range ["
+ versionRange + "]");
}
return versions;
} catch (VersionRangeResolutionException e) {
throw new ResolveException("Failed to resolve version range", e);
}
}
private List<org.eclipse.aether.version.Version> resolveVersions(Artifact artifact, RepositorySystemSession session)
throws VersionRangeResolutionException
{
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.addRepository(this.remoteRepository);
VersionRangeResult rangeResult = this.versionRangeResolver.resolveVersionRange(session, rangeRequest);
return rangeResult.getVersions();
}
private String getProperty(Model model, String propertyName)
{
return model.getProperties().getProperty(MPKEYPREFIX + propertyName);
}
private String getPropertyString(Model model, String propertyName, String def)
{
return StringUtils.defaultString(getProperty(model, propertyName), def);
}
private AetherExtension resolveMaven(ExtensionDependency extensionDependency) throws ResolveException
{
RepositorySystemSession session = createRepositorySystemSession();
Artifact artifact;
String artifactExtension;
if (extensionDependency instanceof AetherExtensionDependency) {
artifact = ((AetherExtensionDependency) extensionDependency).getAetherDependency().getArtifact();
artifactExtension =
((AetherExtensionDependency) extensionDependency).getAetherDependency().getArtifact().getExtension();
} else {
artifact =
AetherUtils.createArtifact(extensionDependency.getId(), extensionDependency.getVersionConstraint()
.getValue());
if (!extensionDependency.getVersionConstraint().getRanges().isEmpty()) {
artifact =
artifact.setVersion(resolveVersionConstraint(extensionDependency.getId(),
extensionDependency.getVersionConstraint(), session).toString());
}
artifactExtension = null;
}
return resolveMaven(artifact, artifactExtension);
}
private AetherExtension resolveMaven(ExtensionId extensionId) throws ResolveException
{
Artifact artifact = AetherUtils.createArtifact(extensionId.getId(), extensionId.getVersion().getValue());
return resolveMaven(artifact, null);
}
private AetherExtension resolveMaven(Artifact artifact, String artifactExtension) throws ResolveException
{
RepositorySystemSession session = createRepositorySystemSession();
// Get Maven descriptor
Model model;
try {
model = loadPom(artifact, session);
} catch (Exception e) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor", e);
}
if (model == null) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor");
}
// Set type
if (artifactExtension == null) {
// Resolve extension from the pom packaging
- ArtifactType artifactType = session.getArtifactTypeRegistry().get(model.getId());
+ ArtifactType artifactType = session.getArtifactTypeRegistry().get(model.getPackaging());
if (artifactType != null) {
artifactExtension = artifactType.getExtension();
+ } else {
+ artifactExtension = model.getPackaging();
}
}
artifact =
new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(),
artifactExtension, artifact.getVersion());
AetherExtension extension = new AetherExtension(artifact, model, this, this.plexusContainer);
extension.setName(getPropertyString(model, MPNAME_NAME, model.getName()));
extension.setSummary(getPropertyString(model, MPNAME_SUMMARY, model.getDescription()));
extension.setWebsite(getPropertyString(model, MPNAME_WEBSITE, model.getUrl()));
// authors
for (Developer developer : model.getDevelopers()) {
URL authorURL = null;
if (developer.getUrl() != null) {
try {
authorURL = new URL(developer.getUrl());
} catch (MalformedURLException e) {
// TODO: log ?
}
}
extension.addAuthor(new DefaultExtensionAuthor(StringUtils.defaultIfBlank(developer.getName(),
developer.getId()), authorURL));
}
// licenses
for (License license : model.getLicenses()) {
extension.addLicense(getExtensionLicense(license));
}
// features
String featuresString = getProperty(model, MPNAME_FEATURES);
if (StringUtils.isNotBlank(featuresString)) {
featuresString = featuresString.replaceAll("[\r\n]", "");
extension.setFeatures(this.converter.<Collection<String>> convert(List.class, featuresString));
}
// dependencies
try {
ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();
for (org.apache.maven.model.Dependency mavenDependency : model.getDependencies()) {
if (!mavenDependency.isOptional()
&& (mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) {
extension.addDependency(new AetherExtensionDependency(
convertToAether(mavenDependency, stereotypes), mavenDependency));
}
}
} catch (Exception e) {
throw new ResolveException("Failed to resolve dependencies", e);
}
return extension;
}
private Dependency convertToAether(org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry stereotypes)
{
ArtifactType stereotype = stereotypes.get(dependency.getType());
if (stereotype == null) {
stereotype = new DefaultArtifactType(dependency.getType());
}
boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0;
Map<String, String> props = null;
if (system) {
props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, dependency.getSystemPath());
}
Artifact artifact =
new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null,
dependency.getVersion(), props, stereotype);
List<Exclusion> exclusions = new ArrayList<Exclusion>(dependency.getExclusions().size());
for (org.apache.maven.model.Exclusion exclusion : dependency.getExclusions()) {
exclusions.add(convert(exclusion));
}
Dependency result = new Dependency(artifact, dependency.getScope(), dependency.isOptional(), exclusions);
return result;
}
private Exclusion convert(org.apache.maven.model.Exclusion exclusion)
{
return new Exclusion(exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*");
}
// TODO: download custom licenses content
private ExtensionLicense getExtensionLicense(License license)
{
if (license.getName() == null) {
return new ExtensionLicense("noname", null);
}
return createLicenseByName(license.getName());
}
private ExtensionLicense createLicenseByName(String name)
{
ExtensionLicense extensionLicense = this.licenseManager.getLicense(name);
return extensionLicense != null ? extensionLicense : new ExtensionLicense(name, null);
}
private Model loadPom(Artifact artifact, RepositorySystemSession session) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException
{
ArtifactDescriptorRequest artifactDescriptorRequest = new ArtifactDescriptorRequest();
artifactDescriptorRequest.setArtifact(artifact);
artifactDescriptorRequest.addRepository(this.remoteRepository);
ArtifactDescriptorResult artifactDescriptorResult = new ArtifactDescriptorResult(artifactDescriptorRequest);
return (Model) this.loadPomMethod.invoke(this.mavenDescriptorReader, session, artifactDescriptorRequest,
artifactDescriptorResult);
}
protected RemoteRepository getRemoteRepository()
{
return this.remoteRepository;
}
}
| false | true | private AetherExtension resolveMaven(Artifact artifact, String artifactExtension) throws ResolveException
{
RepositorySystemSession session = createRepositorySystemSession();
// Get Maven descriptor
Model model;
try {
model = loadPom(artifact, session);
} catch (Exception e) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor", e);
}
if (model == null) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor");
}
// Set type
if (artifactExtension == null) {
// Resolve extension from the pom packaging
ArtifactType artifactType = session.getArtifactTypeRegistry().get(model.getId());
if (artifactType != null) {
artifactExtension = artifactType.getExtension();
}
}
artifact =
new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(),
artifactExtension, artifact.getVersion());
AetherExtension extension = new AetherExtension(artifact, model, this, this.plexusContainer);
extension.setName(getPropertyString(model, MPNAME_NAME, model.getName()));
extension.setSummary(getPropertyString(model, MPNAME_SUMMARY, model.getDescription()));
extension.setWebsite(getPropertyString(model, MPNAME_WEBSITE, model.getUrl()));
// authors
for (Developer developer : model.getDevelopers()) {
URL authorURL = null;
if (developer.getUrl() != null) {
try {
authorURL = new URL(developer.getUrl());
} catch (MalformedURLException e) {
// TODO: log ?
}
}
extension.addAuthor(new DefaultExtensionAuthor(StringUtils.defaultIfBlank(developer.getName(),
developer.getId()), authorURL));
}
// licenses
for (License license : model.getLicenses()) {
extension.addLicense(getExtensionLicense(license));
}
// features
String featuresString = getProperty(model, MPNAME_FEATURES);
if (StringUtils.isNotBlank(featuresString)) {
featuresString = featuresString.replaceAll("[\r\n]", "");
extension.setFeatures(this.converter.<Collection<String>> convert(List.class, featuresString));
}
// dependencies
try {
ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();
for (org.apache.maven.model.Dependency mavenDependency : model.getDependencies()) {
if (!mavenDependency.isOptional()
&& (mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) {
extension.addDependency(new AetherExtensionDependency(
convertToAether(mavenDependency, stereotypes), mavenDependency));
}
}
} catch (Exception e) {
throw new ResolveException("Failed to resolve dependencies", e);
}
return extension;
}
| private AetherExtension resolveMaven(Artifact artifact, String artifactExtension) throws ResolveException
{
RepositorySystemSession session = createRepositorySystemSession();
// Get Maven descriptor
Model model;
try {
model = loadPom(artifact, session);
} catch (Exception e) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor", e);
}
if (model == null) {
throw new ResolveException("Failed to resolve artifact [" + artifact + "] descriptor");
}
// Set type
if (artifactExtension == null) {
// Resolve extension from the pom packaging
ArtifactType artifactType = session.getArtifactTypeRegistry().get(model.getPackaging());
if (artifactType != null) {
artifactExtension = artifactType.getExtension();
} else {
artifactExtension = model.getPackaging();
}
}
artifact =
new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(),
artifactExtension, artifact.getVersion());
AetherExtension extension = new AetherExtension(artifact, model, this, this.plexusContainer);
extension.setName(getPropertyString(model, MPNAME_NAME, model.getName()));
extension.setSummary(getPropertyString(model, MPNAME_SUMMARY, model.getDescription()));
extension.setWebsite(getPropertyString(model, MPNAME_WEBSITE, model.getUrl()));
// authors
for (Developer developer : model.getDevelopers()) {
URL authorURL = null;
if (developer.getUrl() != null) {
try {
authorURL = new URL(developer.getUrl());
} catch (MalformedURLException e) {
// TODO: log ?
}
}
extension.addAuthor(new DefaultExtensionAuthor(StringUtils.defaultIfBlank(developer.getName(),
developer.getId()), authorURL));
}
// licenses
for (License license : model.getLicenses()) {
extension.addLicense(getExtensionLicense(license));
}
// features
String featuresString = getProperty(model, MPNAME_FEATURES);
if (StringUtils.isNotBlank(featuresString)) {
featuresString = featuresString.replaceAll("[\r\n]", "");
extension.setFeatures(this.converter.<Collection<String>> convert(List.class, featuresString));
}
// dependencies
try {
ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();
for (org.apache.maven.model.Dependency mavenDependency : model.getDependencies()) {
if (!mavenDependency.isOptional()
&& (mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) {
extension.addDependency(new AetherExtensionDependency(
convertToAether(mavenDependency, stereotypes), mavenDependency));
}
}
} catch (Exception e) {
throw new ResolveException("Failed to resolve dependencies", e);
}
return extension;
}
|
diff --git a/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java b/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java
index 156dca6..b6bfc38 100644
--- a/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java
+++ b/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java
@@ -1,171 +1,172 @@
package edu.chl.codenameg.model.levels;
import java.util.ArrayList;
import java.util.List;
import org.newdawn.slick.tiled.TiledMap;
import edu.chl.codenameg.model.Entity;
import edu.chl.codenameg.model.Hitbox;
import edu.chl.codenameg.model.Position;
import edu.chl.codenameg.model.entity.Block;
import edu.chl.codenameg.model.entity.GoalBlock;
import edu.chl.codenameg.model.entity.LethalBlock;
import edu.chl.codenameg.model.entity.MovableBlock;
import edu.chl.codenameg.model.entity.MovingBlock;
public class LevelFactory {
private static LevelFactory instance;
TiledMap tiledmap;
private LevelFactory() {
}
public static LevelFactory getInstance(){
if(instance == null) {
instance = new LevelFactory();
}
return instance;
}
public Level getLevel(int i)throws IllegalArgumentException{
if(i == 1){
return loadLevelFromFile(getLevelFilePath(i));
}else if (i == 2){
return new LevelTwo();
}else if (i == 3){
return new LevelThree();
}else if (i == 4){
return loadLevelFromFile(getLevelFilePath(i));
}else{
throw new IllegalArgumentException();
}
}
public Level loadLevelFromFile(String path) {
// if(tiledmap != null) {
// for(Object o : tiledmap.getObjectGroups()) {
// System.out.println(o);
// if(o instanceof ObjectGroup) {
// GroupObject go = (GroupObject)o;
//
// System.out.println(go.index);
// }
// }
// }
List<Entity> entities = new ArrayList<Entity>();
Position spawnposition = new Position(0,0);
for(int groupID=0; groupID<tiledmap.getObjectGroupCount(); groupID++) {
// int groupID = 0;
// System.out.println(tiledmap.getLayerCount());
// String blocktype = tiledmap.getLayerProperty(groupID,"layertype","fff");
// System.out.println(blocktype);
for(int objectID=0; objectID<tiledmap.getObjectCount(groupID); objectID++) {
String name = tiledmap.getObjectName(groupID, objectID);
if(name.equals("Block")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity block = new Block(position,hitbox);
entities.add(block);
}
if(name.equals("LethalBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity lethalblock = new LethalBlock(position,hitbox);
entities.add(lethalblock);
}
if(name.equals("MovableBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity movableblock = new MovableBlock(position, hitbox);
entities.add(movableblock);
}
if(name.equals("MovingBlock")) {
String direction = tiledmap.getObjectProperty(groupID, objectID, "Direction", "down");
Position endPosition = new Position(0,0);
Position startPosition = new Position(0,0);
+ Entity movingblock = new MovingBlock();
if(direction.equals("up")) {
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
- startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID));
+ startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID)-movingblock.getHitbox().getHeight());
} else if(direction.equals("down")) {
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
- endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID));
+ endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID)-movingblock.getHitbox().getHeight());
} else if(direction.equals("right")) {
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
- endPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
+ endPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID)-movingblock.getHitbox().getWidth(), tiledmap.getObjectY(groupID, objectID));
} else if(direction.equals("left")) {
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
- startPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
+ startPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID)-movingblock.getHitbox().getWidth(), tiledmap.getObjectY(groupID, objectID));
}
- Entity movingblock = new MovingBlock(startPosition,endPosition,1000);
+ movingblock = new MovingBlock(startPosition,endPosition,1000);
entities.add(movingblock);
}
if(name.equals("GoalBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity lethalblock = new GoalBlock(position,hitbox);
entities.add(lethalblock);
}
if(name.equals("Spawn")) {
spawnposition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
}
}
}
Level level = new GeneratedLevel(entities,spawnposition,1);
return level;
}
public String getLevelFilePath(int i) {
return "levels/level1.tmx";
}
public void setTiledMap(TiledMap tm) {
this.tiledmap = tm;
}
private class GeneratedLevel implements Level {
List<Entity> entities;
Position spawnposition;
int numberPlayers = 1;
public GeneratedLevel(List<Entity> entities, Position spawnposition, int numberPlayers) {
this.entities = entities;
this.spawnposition = spawnposition;
this.numberPlayers = numberPlayers;
}
@Override
public List<Entity> getListOfEnteties() {
// TODO Auto-generated method stub
return entities;
}
@Override
public Position getStartPosition() {
return spawnposition;
}
@Override
public int getAmountOfPlayers() {
return numberPlayers;
}
}
}
| false | true | public Level loadLevelFromFile(String path) {
// if(tiledmap != null) {
// for(Object o : tiledmap.getObjectGroups()) {
// System.out.println(o);
// if(o instanceof ObjectGroup) {
// GroupObject go = (GroupObject)o;
//
// System.out.println(go.index);
// }
// }
// }
List<Entity> entities = new ArrayList<Entity>();
Position spawnposition = new Position(0,0);
for(int groupID=0; groupID<tiledmap.getObjectGroupCount(); groupID++) {
// int groupID = 0;
// System.out.println(tiledmap.getLayerCount());
// String blocktype = tiledmap.getLayerProperty(groupID,"layertype","fff");
// System.out.println(blocktype);
for(int objectID=0; objectID<tiledmap.getObjectCount(groupID); objectID++) {
String name = tiledmap.getObjectName(groupID, objectID);
if(name.equals("Block")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity block = new Block(position,hitbox);
entities.add(block);
}
if(name.equals("LethalBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity lethalblock = new LethalBlock(position,hitbox);
entities.add(lethalblock);
}
if(name.equals("MovableBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity movableblock = new MovableBlock(position, hitbox);
entities.add(movableblock);
}
if(name.equals("MovingBlock")) {
String direction = tiledmap.getObjectProperty(groupID, objectID, "Direction", "down");
Position endPosition = new Position(0,0);
Position startPosition = new Position(0,0);
if(direction.equals("up")) {
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID));
} else if(direction.equals("down")) {
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID));
} else if(direction.equals("right")) {
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
endPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
} else if(direction.equals("left")) {
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
startPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
}
Entity movingblock = new MovingBlock(startPosition,endPosition,1000);
entities.add(movingblock);
}
if(name.equals("GoalBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity lethalblock = new GoalBlock(position,hitbox);
entities.add(lethalblock);
}
if(name.equals("Spawn")) {
spawnposition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
}
}
}
Level level = new GeneratedLevel(entities,spawnposition,1);
return level;
}
| public Level loadLevelFromFile(String path) {
// if(tiledmap != null) {
// for(Object o : tiledmap.getObjectGroups()) {
// System.out.println(o);
// if(o instanceof ObjectGroup) {
// GroupObject go = (GroupObject)o;
//
// System.out.println(go.index);
// }
// }
// }
List<Entity> entities = new ArrayList<Entity>();
Position spawnposition = new Position(0,0);
for(int groupID=0; groupID<tiledmap.getObjectGroupCount(); groupID++) {
// int groupID = 0;
// System.out.println(tiledmap.getLayerCount());
// String blocktype = tiledmap.getLayerProperty(groupID,"layertype","fff");
// System.out.println(blocktype);
for(int objectID=0; objectID<tiledmap.getObjectCount(groupID); objectID++) {
String name = tiledmap.getObjectName(groupID, objectID);
if(name.equals("Block")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity block = new Block(position,hitbox);
entities.add(block);
}
if(name.equals("LethalBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity lethalblock = new LethalBlock(position,hitbox);
entities.add(lethalblock);
}
if(name.equals("MovableBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity movableblock = new MovableBlock(position, hitbox);
entities.add(movableblock);
}
if(name.equals("MovingBlock")) {
String direction = tiledmap.getObjectProperty(groupID, objectID, "Direction", "down");
Position endPosition = new Position(0,0);
Position startPosition = new Position(0,0);
Entity movingblock = new MovingBlock();
if(direction.equals("up")) {
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID)-movingblock.getHitbox().getHeight());
} else if(direction.equals("down")) {
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID)+tiledmap.getObjectHeight(groupID, objectID)-movingblock.getHitbox().getHeight());
} else if(direction.equals("right")) {
startPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
endPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID)-movingblock.getHitbox().getWidth(), tiledmap.getObjectY(groupID, objectID));
} else if(direction.equals("left")) {
endPosition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
startPosition = new Position(tiledmap.getObjectX(groupID, objectID)+tiledmap.getObjectWidth(groupID, objectID)-movingblock.getHitbox().getWidth(), tiledmap.getObjectY(groupID, objectID));
}
movingblock = new MovingBlock(startPosition,endPosition,1000);
entities.add(movingblock);
}
if(name.equals("GoalBlock")) {
Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth(groupID, objectID),tiledmap.getObjectHeight(groupID, objectID));
Position position = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
Entity lethalblock = new GoalBlock(position,hitbox);
entities.add(lethalblock);
}
if(name.equals("Spawn")) {
spawnposition = new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID));
}
}
}
Level level = new GeneratedLevel(entities,spawnposition,1);
return level;
}
|
diff --git a/org.envirocar.app/src/org/envirocar/app/activity/preference/CarSelectionPreference.java b/org.envirocar.app/src/org/envirocar/app/activity/preference/CarSelectionPreference.java
index fad09d84..f5ff53c4 100644
--- a/org.envirocar.app/src/org/envirocar/app/activity/preference/CarSelectionPreference.java
+++ b/org.envirocar.app/src/org/envirocar/app/activity/preference/CarSelectionPreference.java
@@ -1,651 +1,654 @@
/*
* enviroCar 2013
* Copyright (C) 2013
* Martin Dueren, Jakob Moellers, Gerald Pape, Christopher Stephan
*
* 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 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 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 org.envirocar.app.activity.preference;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.Header;
import org.envirocar.app.R;
import org.envirocar.app.application.User;
import org.envirocar.app.application.UserManager;
import org.envirocar.app.logging.Logger;
import org.envirocar.app.model.Car;
import org.envirocar.app.model.Car.FuelType;
import org.envirocar.app.network.RestClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Base64InputStream;
import android.util.Base64OutputStream;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CarSelectionPreference extends DialogPreference {
private static final String SENSOR_TYPE = "car";
private static final Logger logger = Logger.getLogger(CarSelectionPreference.class);
private static final String DEFAULT_VALUE = "null";
private Car car;
private LinearLayout garageProgress;
private EditText modelEditText;
private EditText manufacturerEditText;
private EditText constructionYearEditText;
protected String carModel;
protected String carManufacturer;
protected String carConstructionYear;
protected String carFuelType;
protected String carEngineDisplacement;
private Spinner sensorSpinner;
private ProgressBar sensorDlProgress;
private Button sensorRetryButton;
protected List<Car> sensors;
private ScrollView garageForm;
private RadioButton gasolineRadioButton;
private RadioButton dieselRadioButton;
private EditText engineDisplacementEditText;
public CarSelectionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.my_garage_layout);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
setDialogIcon(null);
}
@Override
protected void onBindDialogView(View view) {
setupUIItems(view);
}
private void setupUIItems(View view) {
//TODO !fancy! search for sensors
garageForm = (ScrollView) view.findViewById(R.id.garage_form);
garageProgress = (LinearLayout) view.findViewById(R.id.addCarToGarage_status);
setupCarCreationItems(view);
sensorSpinner = (Spinner) view.findViewById(R.id.dashboard_current_sensor_spinner);
sensorSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
private boolean firstSelect = true;
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
if(!firstSelect){
logger.info(parent.getItemAtPosition(pos)+"");
updateCurrentSensor((Car) parent.getItemAtPosition(pos));
}else{
firstSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
logger.info("no change detected");
}
});
sensorDlProgress = (ProgressBar) view.findViewById(R.id.sensor_dl_progress);
sensorRetryButton = (Button) view.findViewById(R.id.retrybutton);
sensorRetryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
downloadSensors();
}
});
if(!UserManager.instance().isLoggedIn()){
manufacturerEditText.setEnabled(false);
constructionYearEditText.setEnabled(false);
modelEditText.setEnabled(false);
gasolineRadioButton.setEnabled(false);
dieselRadioButton.setEnabled(false);
engineDisplacementEditText.setEnabled(false);
((Button) view.findViewById(R.id.register_car_button)).setText(R.string.action_sign_in_short);
((TextView) view.findViewById(R.id.title_create_new_sensor)).setText(R.string.garage_not_signed_in);
}
downloadSensors();
view.findViewById(R.id.mygaragelayout).requestFocus();
view.findViewById(R.id.mygaragelayout).requestFocusFromTouch();
}
private void setupCarCreationItems(View view) {
modelEditText = (EditText) view.findViewById(R.id.addCarToGarage_car_model);
manufacturerEditText = (EditText) view.findViewById(R.id.addCarToGarage_car_manufacturer);
constructionYearEditText = (EditText) view.findViewById(R.id.addCarToGarage_car_constructionYear);
engineDisplacementEditText = (EditText) view.findViewById(R.id.addCarToGarage_car_engineDisplacement);
TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
carModel = modelEditText.getText().toString();
carManufacturer = manufacturerEditText.getText().toString();
carConstructionYear = constructionYearEditText.getText()
.toString();
carEngineDisplacement = engineDisplacementEditText.getText().toString();
}
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
};
modelEditText.addTextChangedListener(textWatcher);
manufacturerEditText.addTextChangedListener(textWatcher);
constructionYearEditText.addTextChangedListener(textWatcher);
engineDisplacementEditText.addTextChangedListener(textWatcher);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
carFuelType = resolveFuelTypeFromCheckbox(v.getId());
logger.info(carFuelType);
}
};
RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radiogroup_fueltype);
carFuelType = resolveFuelTypeFromCheckbox( radioGroup.getCheckedRadioButtonId());
gasolineRadioButton = (RadioButton) view.findViewById(R.id.radio_gasoline);
gasolineRadioButton.setOnClickListener(listener);
dieselRadioButton = (RadioButton) view.findViewById(R.id.radio_diesel);
dieselRadioButton.setOnClickListener(listener);
view.findViewById(R.id.register_car_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
if(UserManager.instance().isLoggedIn()){
registerSensorAtServer(SENSOR_TYPE, carManufacturer,
carModel, carConstructionYear, carFuelType, carEngineDisplacement);
}
else {
Toast.makeText(getDialog().getContext(),
"Please log in", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Shows the progress UI and hides the register form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
garageProgress.setVisibility(View.VISIBLE);
garageProgress.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
garageProgress
.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
garageForm.setVisibility(View.VISIBLE);
garageForm.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
garageForm.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
garageProgress.setVisibility(show ? View.VISIBLE : View.GONE);
garageForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Register a new sensor (car) at the server
* @param sensorType
* @param carManufacturer Car manufacturer
* @param carModel Car model
* @param carConstructionYear Construction year of the car
* @param carFuelType Fuel type of the car
*/
private void registerSensorAtServer(final String sensorType,
final String carManufacturer, final String carModel,
final String carConstructionYear, final String carFuelType,
final String carEngineDisplacement) {
try {
checkEmpty(sensorType, carManufacturer, carModel, carConstructionYear,
carConstructionYear, carFuelType, carEngineDisplacement);
} catch (Exception e) {
Toast.makeText(getContext(), "Not all values were defined.", Toast.LENGTH_SHORT).show();
return;
}
String sensorString = String
.format(Locale.ENGLISH,
"{ \"type\": \"%s\", \"properties\": {\"manufacturer\": \"%s\", \"model\": \"%s\", \"fuelType\": \"%s\", \"constructionYear\": %s, \"engineDisplacement\": %s } }",
sensorType, carManufacturer, carModel, carFuelType,
carConstructionYear, carEngineDisplacement);
User user = UserManager.instance().getUser();
String username = user.getUsername();
String token = user.getToken();
RestClient.createSensor(sensorString, username, token, new AsyncHttpResponseHandler(){
@Override
public void onStart() {
super.onStart();
showProgress(true);
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
- if(content.equals("can't resolve host") ){
+ if (content != null && content.equals("can't resolve host") ){
Toast.makeText(getContext(),
getContext().getString(R.string.error_host_not_found), Toast.LENGTH_SHORT).show();
+ } else {
+ logger.warn("Received error response: "+ content +"; "+error.getMessage(), error);
+ Toast.makeText(getContext(), "Server Error: "+content, Toast.LENGTH_SHORT).show();
}
showProgress(false);
}
@Override
public void onSuccess(int httpStatusCode, Header[] h, String response) {
super.onSuccess(httpStatusCode, h, response);
String location = "";
for (int i = 0; i< h.length; i++){
if( h[i].getName().equals("Location")){
location += h[i].getValue();
break;
}
}
logger.info(httpStatusCode+" "+location);
String sensorId = location.substring(location.lastIndexOf("/")+1, location.length());
//put the sensor id into shared preferences
int engineDisplacement = Integer.parseInt(carEngineDisplacement);
int year = Integer.parseInt(carConstructionYear);
car = new Car(Car.resolveFuelType(carFuelType), carManufacturer, carModel, sensorId, year, engineDisplacement);
}
});
}
private void checkEmpty(String... values) throws Exception {
for (String string : values) {
if (string == null || string.isEmpty()) {
throw new Exception("Empty value!");
}
}
}
/**
* Get the fuel type form the checkbox
* @param resid
* @return
*/
private String resolveFuelTypeFromCheckbox(int resid){
switch(resid){
case R.id.radio_diesel:
return FuelType.DIESEL.toString();
case R.id.radio_gasoline:
return FuelType.GASOLINE.toString();
}
return "none";
}
protected void downloadSensors() {
sensorDlProgress.setVisibility(View.VISIBLE);
sensorSpinner.setVisibility(View.GONE);
sensorRetryButton.setVisibility(View.GONE);
RestClient.downloadSensors(new JsonHttpResponseHandler() {
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
sensorDlProgress.setVisibility(View.GONE);
sensorRetryButton.setVisibility(View.VISIBLE);
Toast.makeText(getContext(),
getContext().getString(R.string.error_host_not_found), Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(JSONObject response) {
super.onSuccess(response);
sensors = new ArrayList<Car>();
JSONArray res;
try {
res = response.getJSONArray("sensors");
} catch (JSONException e) {
logger.warn(e.getMessage(), e);
Toast.makeText(getContext(), "Could not retrieve cars from server", Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i<res.length(); i++){
String typeString;
JSONObject properties;
String carId;
try {
typeString = ((JSONObject) res.get(i)).optString("type", "none");
properties = ((JSONObject) res.get(i)).getJSONObject("properties");
carId = properties.getString("id");
} catch (JSONException e) {
logger.warn(e.getMessage(), e);
continue;
}
if (typeString.equals(SENSOR_TYPE)) {
try {
sensors.add(Car.fromJsonWithStrictEngineDisplacement(properties));
} catch (JSONException e) {
logger.warn(String.format("Car '%s' not supported: %s", carId != null ? carId : "null", e.getMessage()));
}
}
}
SensorAdapter adapter = new SensorAdapter();
sensorSpinner.setAdapter(adapter);
int index = adapter.getInitialSelectedItem();
sensorSpinner.setSelection(index);
sensorDlProgress.setVisibility(View.GONE);
sensorSpinner.setVisibility(View.VISIBLE);
}
});
}
/**
* This method updates the attributes of the current sensor (=car)
* @param sensorid the id that is stored on the server
* @param carManufacturer the car manufacturer
* @param carModel the car model
* @param fuelType the fuel type of the car
* @param year construction year of the car
*/
private void updateCurrentSensor(Car car) {
this.car = car;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
persistString(serializeCar(car));
setSummary(car.toString());
}
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
car = instantiateCar(this.getPersistedString(DEFAULT_VALUE));
}
if (car != null) {
setSummary(car.toString());
}
else {
setSummary(R.string.please_select);
}
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
// Check whether this Preference is persistent (continually saved)
if (isPersistent()) {
// No need to save instance state since it's persistent, use superclass state
return superState;
}
// Create instance of custom BaseSavedState
final SavedState myState = new SavedState(superState);
// Set the state's value with the class member that holds current setting value
myState.car = car;
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
// Check whether we saved the state in onSaveInstanceState
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save the state, so call superclass
super.onRestoreInstanceState(state);
return;
}
// Cast state to custom BaseSavedState and pass to superclass
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
}
public static String serializeCar(Car car) {
ObjectOutputStream oos = null;
Base64OutputStream b64 = null;
try {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
oos = new ObjectOutputStream(byteArrayOut);
oos.writeObject(car);
oos.flush();
ByteArrayOutputStream out = new ByteArrayOutputStream();
b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(byteArrayOut.toByteArray());
b64.flush();
b64.close();
out.flush();
out.close();
String result = new String(out.toByteArray());
return result;
} catch (IOException e) {
logger.warn(e.getMessage(), e);
} finally {
if (oos != null)
try {
b64.close();
oos.close();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
return null;
}
public static Car instantiateCar(String object) {
if (object == null) return null;
ObjectInputStream ois = null;
try {
Base64InputStream b64 = new Base64InputStream(new ByteArrayInputStream(object.getBytes()), Base64.DEFAULT);
ois = new ObjectInputStream(b64);
Car car = (Car) ois.readObject();
return car;
} catch (StreamCorruptedException e) {
logger.warn(e.getMessage(), e);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
} catch (ClassNotFoundException e) {
logger.warn(e.getMessage(), e);
} finally {
if (ois != null)
try {
ois.close();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
return null;
}
public static class SavedState extends BaseSavedState {
// Member that holds the setting's value
// Change this data type to match the type saved by your Preference
Car car;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
// Get the current preference's value
car = (Car) source.readSerializable(); // Change this to read the appropriate data type
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
// Write the preference's value
dest.writeSerializable(car); // Change this to write the appropriate data type
}
// Standard creator object using an instance of this class
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
private class SensorAdapter extends BaseAdapter implements SpinnerAdapter {
@Override
public int getCount() {
return sensors.size()+1;
}
public int getInitialSelectedItem() {
if (car != null) {
int index = 1;
for (Car c : sensors) {
if (c.equals(car)) {
return index;
}
index++;
}
}
return 0;
}
@Override
public Object getItem(int position) {
return sensors.get(position-1);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
TextView text;
if (position == 0) {
text = new TextView(parent.getContext());
text.setText(getContext().getString(R.string.please_select));
}
else {
text = new TextView(parent.getContext());
text.setText(((Car) getItem(position)).toString());
}
return text;
}
}
}
| false | true | private void registerSensorAtServer(final String sensorType,
final String carManufacturer, final String carModel,
final String carConstructionYear, final String carFuelType,
final String carEngineDisplacement) {
try {
checkEmpty(sensorType, carManufacturer, carModel, carConstructionYear,
carConstructionYear, carFuelType, carEngineDisplacement);
} catch (Exception e) {
Toast.makeText(getContext(), "Not all values were defined.", Toast.LENGTH_SHORT).show();
return;
}
String sensorString = String
.format(Locale.ENGLISH,
"{ \"type\": \"%s\", \"properties\": {\"manufacturer\": \"%s\", \"model\": \"%s\", \"fuelType\": \"%s\", \"constructionYear\": %s, \"engineDisplacement\": %s } }",
sensorType, carManufacturer, carModel, carFuelType,
carConstructionYear, carEngineDisplacement);
User user = UserManager.instance().getUser();
String username = user.getUsername();
String token = user.getToken();
RestClient.createSensor(sensorString, username, token, new AsyncHttpResponseHandler(){
@Override
public void onStart() {
super.onStart();
showProgress(true);
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
if(content.equals("can't resolve host") ){
Toast.makeText(getContext(),
getContext().getString(R.string.error_host_not_found), Toast.LENGTH_SHORT).show();
}
showProgress(false);
}
@Override
public void onSuccess(int httpStatusCode, Header[] h, String response) {
super.onSuccess(httpStatusCode, h, response);
String location = "";
for (int i = 0; i< h.length; i++){
if( h[i].getName().equals("Location")){
location += h[i].getValue();
break;
}
}
logger.info(httpStatusCode+" "+location);
String sensorId = location.substring(location.lastIndexOf("/")+1, location.length());
//put the sensor id into shared preferences
int engineDisplacement = Integer.parseInt(carEngineDisplacement);
int year = Integer.parseInt(carConstructionYear);
car = new Car(Car.resolveFuelType(carFuelType), carManufacturer, carModel, sensorId, year, engineDisplacement);
}
});
}
| private void registerSensorAtServer(final String sensorType,
final String carManufacturer, final String carModel,
final String carConstructionYear, final String carFuelType,
final String carEngineDisplacement) {
try {
checkEmpty(sensorType, carManufacturer, carModel, carConstructionYear,
carConstructionYear, carFuelType, carEngineDisplacement);
} catch (Exception e) {
Toast.makeText(getContext(), "Not all values were defined.", Toast.LENGTH_SHORT).show();
return;
}
String sensorString = String
.format(Locale.ENGLISH,
"{ \"type\": \"%s\", \"properties\": {\"manufacturer\": \"%s\", \"model\": \"%s\", \"fuelType\": \"%s\", \"constructionYear\": %s, \"engineDisplacement\": %s } }",
sensorType, carManufacturer, carModel, carFuelType,
carConstructionYear, carEngineDisplacement);
User user = UserManager.instance().getUser();
String username = user.getUsername();
String token = user.getToken();
RestClient.createSensor(sensorString, username, token, new AsyncHttpResponseHandler(){
@Override
public void onStart() {
super.onStart();
showProgress(true);
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
if (content != null && content.equals("can't resolve host") ){
Toast.makeText(getContext(),
getContext().getString(R.string.error_host_not_found), Toast.LENGTH_SHORT).show();
} else {
logger.warn("Received error response: "+ content +"; "+error.getMessage(), error);
Toast.makeText(getContext(), "Server Error: "+content, Toast.LENGTH_SHORT).show();
}
showProgress(false);
}
@Override
public void onSuccess(int httpStatusCode, Header[] h, String response) {
super.onSuccess(httpStatusCode, h, response);
String location = "";
for (int i = 0; i< h.length; i++){
if( h[i].getName().equals("Location")){
location += h[i].getValue();
break;
}
}
logger.info(httpStatusCode+" "+location);
String sensorId = location.substring(location.lastIndexOf("/")+1, location.length());
//put the sensor id into shared preferences
int engineDisplacement = Integer.parseInt(carEngineDisplacement);
int year = Integer.parseInt(carConstructionYear);
car = new Car(Car.resolveFuelType(carFuelType), carManufacturer, carModel, sensorId, year, engineDisplacement);
}
});
}
|
diff --git a/kie-spring/src/main/java/org/kie/spring/factorybeans/KContainerFactoryBean.java b/kie-spring/src/main/java/org/kie/spring/factorybeans/KContainerFactoryBean.java
index f1c559409..b5d7c5bde 100644
--- a/kie-spring/src/main/java/org/kie/spring/factorybeans/KContainerFactoryBean.java
+++ b/kie-spring/src/main/java/org/kie/spring/factorybeans/KContainerFactoryBean.java
@@ -1,59 +1,62 @@
/*
* Copyright 2013 JBoss 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.kie.spring.factorybeans;
import org.kie.api.KieServices;
import org.kie.api.builder.ReleaseId;
import org.kie.api.runtime.KieContainer;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
public class KContainerFactoryBean
implements
FactoryBean,
InitializingBean {
private ReleaseId releaseId;
private KieContainer kContainer;
public ReleaseId getReleaseId() {
return releaseId;
}
public void setReleaseId(ReleaseId releaseId) {
this.releaseId = releaseId;
}
public Object getObject() throws Exception {
return kContainer;
}
public Class<? extends KieContainer> getObjectType() {
return KieContainer.class;
}
public boolean isSingleton() {
return true;
}
public void afterPropertiesSet() throws Exception {
KieServices ks = KieServices.Factory.get();
- kContainer = ks.getKieClasspathContainer();
+ if ( releaseId == null) {
+ kContainer = ks.getKieClasspathContainer();
+ }
+ kContainer = ks.newKieContainer(releaseId);
}
}
| true | true | public void afterPropertiesSet() throws Exception {
KieServices ks = KieServices.Factory.get();
kContainer = ks.getKieClasspathContainer();
}
| public void afterPropertiesSet() throws Exception {
KieServices ks = KieServices.Factory.get();
if ( releaseId == null) {
kContainer = ks.getKieClasspathContainer();
}
kContainer = ks.newKieContainer(releaseId);
}
|
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/operations/ModelSynchronizeParticipant.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/operations/ModelSynchronizeParticipant.java
index 73a381b2a..6c67bddf0 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/operations/ModelSynchronizeParticipant.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/operations/ModelSynchronizeParticipant.java
@@ -1,188 +1,188 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.ui.operations;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.team.core.mapping.IMergeContext;
import org.eclipse.team.core.mapping.ISynchronizationContext;
import org.eclipse.team.internal.ui.TeamUIPlugin;
import org.eclipse.team.internal.ui.mapping.*;
import org.eclipse.team.ui.TeamUI;
import org.eclipse.team.ui.synchronize.*;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.IPageBookViewPage;
/**
* Synchronize participant that obtains it's synchronization state from
* a {@link ISynchronizationContext}.
* <p>
* <strong>EXPERIMENTAL</strong>. This class or interface has been added as
* part of a work in progress. There is a guarantee neither that this API will
* work nor that it will remain the same. Please do not use this API without
* consulting with the Platform/Team team.
* </p>
*
* @since 3.2
**/
public class ModelSynchronizeParticipant extends
AbstractSynchronizeParticipant {
public static final String TOOLBAR_CONTRIBUTION_GROUP = "toolbar_group_1"; //$NON-NLS-1$
public static final String CONTEXT_MENU_CONTRIBUTION_GROUP_1 = "context_menu_group_1"; //$NON-NLS-1$
public static final String CONTEXT_MENU_CONTRIBUTION_GROUP_2 = "context_menu_group_2"; //$NON-NLS-1$
private ISynchronizationContext context;
/**
* Actions for a model participant
*/
private class ModelActionContribution extends SynchronizePageActionGroup {
private MergeIncomingChangesAction updateToolbarAction;
public void initialize(ISynchronizePageConfiguration configuration) {
super.initialize(configuration);
ISynchronizationContext context = ((ModelSynchronizeParticipant)configuration.getParticipant()).getContext();
if (context instanceof IMergeContext) {
updateToolbarAction = new MergeIncomingChangesAction(configuration);
appendToGroup(
ISynchronizePageConfiguration.P_TOOLBAR_MENU,
TOOLBAR_CONTRIBUTION_GROUP,
updateToolbarAction);
+ appendToGroup(
+ ISynchronizePageConfiguration.P_CONTEXT_MENU,
+ CONTEXT_MENU_CONTRIBUTION_GROUP_1,
+ new MergeAction(configuration, false));
+ appendToGroup(
+ ISynchronizePageConfiguration.P_CONTEXT_MENU,
+ CONTEXT_MENU_CONTRIBUTION_GROUP_1,
+ new MergeAction(configuration, true));
+ appendToGroup(
+ ISynchronizePageConfiguration.P_CONTEXT_MENU,
+ CONTEXT_MENU_CONTRIBUTION_GROUP_2,
+ new MarkAsMergedAction(configuration));
}
- appendToGroup(
- ISynchronizePageConfiguration.P_CONTEXT_MENU,
- CONTEXT_MENU_CONTRIBUTION_GROUP_1,
- new MergeAction(configuration, false));
- appendToGroup(
- ISynchronizePageConfiguration.P_CONTEXT_MENU,
- CONTEXT_MENU_CONTRIBUTION_GROUP_1,
- new MergeAction(configuration, true));
- appendToGroup(
- ISynchronizePageConfiguration.P_CONTEXT_MENU,
- CONTEXT_MENU_CONTRIBUTION_GROUP_2,
- new MarkAsMergedAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_1,
// new WorkspaceCommitAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new OverrideAndUpdateAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new OverrideAndCommitAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new ConfirmMergedAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new IgnoreAction(), configuration));
// if (!configuration.getSite().isModal()) {
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CreatePatchAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new BranchAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new ShowAnnotationAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new ShowResourceInHistoryAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new SetKeywordSubstitutionAction(), configuration));
// }
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_4,
// new RefreshDirtyStateAction(configuration));
}
}
/**
* Create a participant for the given context
* @param context the synchronization context
*/
public ModelSynchronizeParticipant(ISynchronizationContext context, String name) {
initializeContext(context);
try {
setInitializationData(TeamUI.getSynchronizeManager().getParticipantDescriptor("org.eclipse.team.ui.synchronization_context_synchronize_participant")); //$NON-NLS-1$
} catch (CoreException e) {
TeamUIPlugin.log(e);
}
setSecondaryId(Long.toString(System.currentTimeMillis()));
setName(name);
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.AbstractSynchronizeParticipant#initializeConfiguration(org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration)
*/
protected void initializeConfiguration(
ISynchronizePageConfiguration configuration) {
configuration.setProperty(ISynchronizePageConfiguration.P_TOOLBAR_MENU, new String[] {ISynchronizePageConfiguration.NAVIGATE_GROUP, ISynchronizePageConfiguration.MODE_GROUP, TOOLBAR_CONTRIBUTION_GROUP});
configuration.addActionContribution(new ModelActionContribution());
configuration.setProperty(ISynchronizePageConfiguration.P_CONTEXT_MENU, new String[] { ISynchronizePageConfiguration.NAVIGATE_GROUP, CONTEXT_MENU_CONTRIBUTION_GROUP_1, CONTEXT_MENU_CONTRIBUTION_GROUP_2});
configuration.setSupportedModes(ISynchronizePageConfiguration.INCOMING_MODE | ISynchronizePageConfiguration.CONFLICTING_MODE);
configuration.setMode(ISynchronizePageConfiguration.INCOMING_MODE);
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.ISynchronizeParticipant#createPage(org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration)
*/
public IPageBookViewPage createPage(
ISynchronizePageConfiguration configuration) {
return new ModelSynchronizePage(configuration);
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.ISynchronizeParticipant#run(org.eclipse.ui.IWorkbenchPart)
*/
public void run(IWorkbenchPart part) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.ISynchronizeParticipant#dispose()
*/
public void dispose() {
context.dispose();
}
/**
* Set the context of this participant. This method must be invoked
* before a page is obtained from the participant.
* @param context the context for this participant
*/
protected void initializeContext(ISynchronizationContext context) {
this.context = context;
}
/**
* Return the synchronization context for this participant.
* @return the synchronization context for this participant
*/
public ISynchronizationContext getContext() {
return context;
}
}
| false | true | public void initialize(ISynchronizePageConfiguration configuration) {
super.initialize(configuration);
ISynchronizationContext context = ((ModelSynchronizeParticipant)configuration.getParticipant()).getContext();
if (context instanceof IMergeContext) {
updateToolbarAction = new MergeIncomingChangesAction(configuration);
appendToGroup(
ISynchronizePageConfiguration.P_TOOLBAR_MENU,
TOOLBAR_CONTRIBUTION_GROUP,
updateToolbarAction);
}
appendToGroup(
ISynchronizePageConfiguration.P_CONTEXT_MENU,
CONTEXT_MENU_CONTRIBUTION_GROUP_1,
new MergeAction(configuration, false));
appendToGroup(
ISynchronizePageConfiguration.P_CONTEXT_MENU,
CONTEXT_MENU_CONTRIBUTION_GROUP_1,
new MergeAction(configuration, true));
appendToGroup(
ISynchronizePageConfiguration.P_CONTEXT_MENU,
CONTEXT_MENU_CONTRIBUTION_GROUP_2,
new MarkAsMergedAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_1,
// new WorkspaceCommitAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new OverrideAndUpdateAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new OverrideAndCommitAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new ConfirmMergedAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new IgnoreAction(), configuration));
// if (!configuration.getSite().isModal()) {
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CreatePatchAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new BranchAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new ShowAnnotationAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new ShowResourceInHistoryAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new SetKeywordSubstitutionAction(), configuration));
// }
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_4,
// new RefreshDirtyStateAction(configuration));
}
| public void initialize(ISynchronizePageConfiguration configuration) {
super.initialize(configuration);
ISynchronizationContext context = ((ModelSynchronizeParticipant)configuration.getParticipant()).getContext();
if (context instanceof IMergeContext) {
updateToolbarAction = new MergeIncomingChangesAction(configuration);
appendToGroup(
ISynchronizePageConfiguration.P_TOOLBAR_MENU,
TOOLBAR_CONTRIBUTION_GROUP,
updateToolbarAction);
appendToGroup(
ISynchronizePageConfiguration.P_CONTEXT_MENU,
CONTEXT_MENU_CONTRIBUTION_GROUP_1,
new MergeAction(configuration, false));
appendToGroup(
ISynchronizePageConfiguration.P_CONTEXT_MENU,
CONTEXT_MENU_CONTRIBUTION_GROUP_1,
new MergeAction(configuration, true));
appendToGroup(
ISynchronizePageConfiguration.P_CONTEXT_MENU,
CONTEXT_MENU_CONTRIBUTION_GROUP_2,
new MarkAsMergedAction(configuration));
}
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_1,
// new WorkspaceCommitAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new OverrideAndUpdateAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new OverrideAndCommitAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_2,
// new ConfirmMergedAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new IgnoreAction(), configuration));
// if (!configuration.getSite().isModal()) {
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CreatePatchAction(configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new BranchAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new ShowAnnotationAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new ShowResourceInHistoryAction(), configuration));
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_3,
// new CVSActionDelegateWrapper(new SetKeywordSubstitutionAction(), configuration));
// }
// appendToGroup(
// ISynchronizePageConfiguration.P_CONTEXT_MENU,
// CONTEXT_MENU_CONTRIBUTION_GROUP_4,
// new RefreshDirtyStateAction(configuration));
}
|
diff --git a/src/org/rascalmpl/interpreter/matching/MatchResult.java b/src/org/rascalmpl/interpreter/matching/MatchResult.java
index dadd6b4e31..607b15b4d2 100644
--- a/src/org/rascalmpl/interpreter/matching/MatchResult.java
+++ b/src/org/rascalmpl/interpreter/matching/MatchResult.java
@@ -1,85 +1,85 @@
/*******************************************************************************
* Copyright (c) 2009-2011 CWI
* 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
*
* Contributors:
* * Jurgen J. Vinju - [email protected] - CWI
* * Tijs van der Storm - [email protected]
* * Emilie Balland - (CWI)
* * Paul Klint - [email protected] - CWI
* * Mark Hills - [email protected] (CWI)
* * Arnold Lankamp - [email protected]
*******************************************************************************/
package org.rascalmpl.interpreter.matching;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.rascalmpl.ast.Expression;
import org.rascalmpl.interpreter.IEvaluatorContext;
import org.rascalmpl.interpreter.result.Result;
import org.rascalmpl.interpreter.staticErrors.UnexpectedTypeError;
public class MatchResult extends AbstractBooleanResult {
private boolean positive;
private IMatchingResult mp;
private Expression expression;
private boolean firstTime;
private Expression pattern;
public MatchResult(IEvaluatorContext ctx, Expression pattern, boolean positive, Expression expression) {
super(ctx);
this.positive = positive;
this.pattern = pattern;
this.mp = null;
this.expression = expression;
}
@Override
public void init() {
super.init();
// because the right hand side may introduce types that are needed
// in the left-hand side, we first need to evaluate the expression
// before we construct a pattern.
Result<IValue> result = expression.interpret(ctx.getEvaluator());
Type subjectType = result.getType();
mp = pattern.getMatcher(ctx);
- mp.initMatch(expression.interpret(ctx.getEvaluator()));
+ mp.initMatch(result);
if(!mp.mayMatch(subjectType, ctx.getCurrentEnvt())) {
throw new UnexpectedTypeError(mp.getType(ctx.getCurrentEnvt()), subjectType, ctx.getCurrentAST());
}
firstTime = true;
}
@Override
public boolean hasNext() {
if (positive) {
return mp.hasNext();
}
if (firstTime) {
return true;
}
return mp.hasNext();
}
@Override
public boolean next() {
firstTime = false;
// TODO: should manage escape variable from negative matches!!!
if(hasNext()){
return positive ? mp.next() : !mp.next();
}
return !positive;
}
}
| true | true | public void init() {
super.init();
// because the right hand side may introduce types that are needed
// in the left-hand side, we first need to evaluate the expression
// before we construct a pattern.
Result<IValue> result = expression.interpret(ctx.getEvaluator());
Type subjectType = result.getType();
mp = pattern.getMatcher(ctx);
mp.initMatch(expression.interpret(ctx.getEvaluator()));
if(!mp.mayMatch(subjectType, ctx.getCurrentEnvt())) {
throw new UnexpectedTypeError(mp.getType(ctx.getCurrentEnvt()), subjectType, ctx.getCurrentAST());
}
firstTime = true;
}
| public void init() {
super.init();
// because the right hand side may introduce types that are needed
// in the left-hand side, we first need to evaluate the expression
// before we construct a pattern.
Result<IValue> result = expression.interpret(ctx.getEvaluator());
Type subjectType = result.getType();
mp = pattern.getMatcher(ctx);
mp.initMatch(result);
if(!mp.mayMatch(subjectType, ctx.getCurrentEnvt())) {
throw new UnexpectedTypeError(mp.getType(ctx.getCurrentEnvt()), subjectType, ctx.getCurrentAST());
}
firstTime = true;
}
|
diff --git a/src/test/cli/cloudify/github/GitCloudifyBuildTest.java b/src/test/cli/cloudify/github/GitCloudifyBuildTest.java
index 046cb0f3..2ac19db5 100644
--- a/src/test/cli/cloudify/github/GitCloudifyBuildTest.java
+++ b/src/test/cli/cloudify/github/GitCloudifyBuildTest.java
@@ -1,85 +1,85 @@
package test.cli.cloudify.github;
import framework.tools.SGTestHelper;
import framework.utils.GitUtils;
import framework.utils.LogUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import test.cli.cloudify.AbstractLocalCloudTest;
import test.cli.cloudify.CommandTestUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GitCloudifyBuildTest extends AbstractLocalCloudTest{
private File gitDir = null;
@Test(timeOut = 100000000, groups = "1", enabled = true)
public void test() throws IOException, InterruptedException {
String commandOutput = null;
String url = "https://github.com/CloudifySource/cloudify.git";
gitDir = new File(SGTestHelper.getBuildDir() + "/git/");
GitUtils.pull(url, gitDir);
String cloudifyFolder = SGTestHelper.getBuildDir() + "/git/cloudify/";
LogUtils.log("building Cloudify...");
- commandOutput = CommandTestUtils.runLocalCommand("ant -buildfile=" + cloudifyFolder + "build.xml cloudify.zip", true, false);
+ commandOutput = CommandTestUtils.runLocalCommand("ant -f " + cloudifyFolder + "build.xml cloudify.zip", true, false);
Assert.assertFalse(commandOutput.contains("BUILD FAILED"));
Collection<File> files = FileUtils.listFiles(
new File(cloudifyFolder + "/releases/"),
new RegexFileFilter("gigaspaces-cloudify.*.zip"),
DirectoryFileFilter.DIRECTORY
);
Assert.assertEquals(1, files.size());
Map<String, String> insideZipFiles = new HashMap<String, String>();
FileInputStream fis = new FileInputStream(files.iterator().next());
// this is where you start, with an InputStream containing the bytes from the zip file
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry entry;
// while there are entries I process them
while ((entry = zis.getNextEntry()) != null) {
insideZipFiles.put(entry.getName(), entry.getName());
System.out.println("entry: " + entry.getName() + ", " + entry.getSize());
// consume all the data from this entry
while (zis.available() > 0)
zis.read();
}
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/bin/cloudify.bat"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/bin/cloudify.sh"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/docs/cloudify-javadoc.zip"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/lib/platform/usm/usm.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/lib/required/dsl.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/recipes/apps/"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/recipes/services/"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/tools/cli/cli.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/tools/rest/rest.war"));
}
@AfterMethod
public void afterTest() {
try {
FileUtils.forceDelete(gitDir);
} catch (IOException e) {
LogUtils.log("Failed to delete git Cloudify folder", e);
}
super.afterTest();
}
}
| true | true | public void test() throws IOException, InterruptedException {
String commandOutput = null;
String url = "https://github.com/CloudifySource/cloudify.git";
gitDir = new File(SGTestHelper.getBuildDir() + "/git/");
GitUtils.pull(url, gitDir);
String cloudifyFolder = SGTestHelper.getBuildDir() + "/git/cloudify/";
LogUtils.log("building Cloudify...");
commandOutput = CommandTestUtils.runLocalCommand("ant -buildfile=" + cloudifyFolder + "build.xml cloudify.zip", true, false);
Assert.assertFalse(commandOutput.contains("BUILD FAILED"));
Collection<File> files = FileUtils.listFiles(
new File(cloudifyFolder + "/releases/"),
new RegexFileFilter("gigaspaces-cloudify.*.zip"),
DirectoryFileFilter.DIRECTORY
);
Assert.assertEquals(1, files.size());
Map<String, String> insideZipFiles = new HashMap<String, String>();
FileInputStream fis = new FileInputStream(files.iterator().next());
// this is where you start, with an InputStream containing the bytes from the zip file
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry entry;
// while there are entries I process them
while ((entry = zis.getNextEntry()) != null) {
insideZipFiles.put(entry.getName(), entry.getName());
System.out.println("entry: " + entry.getName() + ", " + entry.getSize());
// consume all the data from this entry
while (zis.available() > 0)
zis.read();
}
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/bin/cloudify.bat"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/bin/cloudify.sh"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/docs/cloudify-javadoc.zip"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/lib/platform/usm/usm.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/lib/required/dsl.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/recipes/apps/"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/recipes/services/"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/tools/cli/cli.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/tools/rest/rest.war"));
}
| public void test() throws IOException, InterruptedException {
String commandOutput = null;
String url = "https://github.com/CloudifySource/cloudify.git";
gitDir = new File(SGTestHelper.getBuildDir() + "/git/");
GitUtils.pull(url, gitDir);
String cloudifyFolder = SGTestHelper.getBuildDir() + "/git/cloudify/";
LogUtils.log("building Cloudify...");
commandOutput = CommandTestUtils.runLocalCommand("ant -f " + cloudifyFolder + "build.xml cloudify.zip", true, false);
Assert.assertFalse(commandOutput.contains("BUILD FAILED"));
Collection<File> files = FileUtils.listFiles(
new File(cloudifyFolder + "/releases/"),
new RegexFileFilter("gigaspaces-cloudify.*.zip"),
DirectoryFileFilter.DIRECTORY
);
Assert.assertEquals(1, files.size());
Map<String, String> insideZipFiles = new HashMap<String, String>();
FileInputStream fis = new FileInputStream(files.iterator().next());
// this is where you start, with an InputStream containing the bytes from the zip file
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry entry;
// while there are entries I process them
while ((entry = zis.getNextEntry()) != null) {
insideZipFiles.put(entry.getName(), entry.getName());
System.out.println("entry: " + entry.getName() + ", " + entry.getSize());
// consume all the data from this entry
while (zis.available() > 0)
zis.read();
}
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/bin/cloudify.bat"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/bin/cloudify.sh"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/docs/cloudify-javadoc.zip"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/lib/platform/usm/usm.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/lib/required/dsl.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/recipes/apps/"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/recipes/services/"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/tools/cli/cli.jar"));
Assert.assertNotNull(insideZipFiles.get("gigaspaces-cloudify-2.1.1-m1/tools/rest/rest.war"));
}
|
diff --git a/test/mnj/lua/METestMIDlet.java b/test/mnj/lua/METestMIDlet.java
index e14a6d7..31d20c3 100644
--- a/test/mnj/lua/METestMIDlet.java
+++ b/test/mnj/lua/METestMIDlet.java
@@ -1,18 +1,18 @@
// $Header$
package mnj.lua;
import j2meunit.midletui.TestRunner;
/**
* J2MEUnit TestRunner MIDlet.
*/
public class METestMIDlet extends TestRunner
{
public METestMIDlet() { }
public void startApp()
{
- start(new String[] { "METest" });
+ start(new String[] { "mnj.lua.METest" });
}
}
| true | true | public void startApp()
{
start(new String[] { "METest" });
}
| public void startApp()
{
start(new String[] { "mnj.lua.METest" });
}
|
diff --git a/org.eclipse.stem.ui/src/org/eclipse/stem/ui/editors/GenericPropertyEditor.java b/org.eclipse.stem.ui/src/org/eclipse/stem/ui/editors/GenericPropertyEditor.java
index 716dd98c..e37da156 100644
--- a/org.eclipse.stem.ui/src/org/eclipse/stem/ui/editors/GenericPropertyEditor.java
+++ b/org.eclipse.stem.ui/src/org/eclipse/stem/ui/editors/GenericPropertyEditor.java
@@ -1,622 +1,627 @@
package org.eclipse.stem.ui.editors;
/*******************************************************************************
* Copyright (c) 2010 IBM Corporation and others.
* 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import org.eclipse.core.resources.IProject;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.stem.core.STEMURI;
import org.eclipse.stem.core.common.CommonPackage;
import org.eclipse.stem.core.common.Identifiable;
import org.eclipse.stem.core.graph.Graph;
import org.eclipse.stem.definitions.nodes.impl.RegionImpl;
import org.eclipse.stem.ui.adapters.propertystrings.PropertyStringProvider;
import org.eclipse.stem.ui.adapters.propertystrings.PropertyStringProviderAdapter;
import org.eclipse.stem.ui.adapters.propertystrings.PropertyStringProviderAdapterFactory;
import org.eclipse.stem.ui.widgets.LocationPickerDialog;
import org.eclipse.stem.ui.widgets.MatrixEditorDialog;
import org.eclipse.stem.ui.widgets.MatrixEditorWidget.MatrixEditorValidator;
import org.eclipse.stem.ui.wizards.Messages;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* Producing a form given an identifiable object is common in STEM. This class consolidates
* what used to be a handful of places we do this into a single place.
*
*/
public abstract class GenericPropertyEditor extends Composite {
protected final Map<EStructuralFeature, Text> map = new HashMap<EStructuralFeature, Text>();
protected final Map<EStructuralFeature, String[]> matrixMap = new HashMap<EStructuralFeature, String[]>();
protected final Map<EStructuralFeature, Boolean> booleanMap = new HashMap<EStructuralFeature, Boolean>();
protected String errorMessage;
protected IProject project;
public GenericPropertyEditor(Composite parent, int style, IProject project) {
super(parent,style);
this.project = project;
}
/**
* Create the composite
*
* @param parent
* @param style
* @param projectValidator
*/
public GenericPropertyEditor(final Composite parent, final int style,
final Identifiable identifiable,
final ModifyListener projectValidator, IProject project) {
super(parent, style);
this.project = project;
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
setLayout(gridLayout);
// Get the adapter that will provide NLS'd names for the
// properties of the disease model
final PropertyStringProviderAdapter pspa = (PropertyStringProviderAdapter) PropertyStringProviderAdapterFactory.INSTANCE
.adapt(identifiable, PropertyStringProvider.class);
final ComposedAdapterFactory itemProviderFactory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
final IItemPropertySource propertySource = (IItemPropertySource) itemProviderFactory
.adapt(identifiable, IItemPropertySource.class);
final List<IItemPropertyDescriptor> properties = propertySource
.getPropertyDescriptors(identifiable);
for (final IItemPropertyDescriptor descriptor : properties) {
final EStructuralFeature feature = (EStructuralFeature) descriptor
.getFeature(null);
// Is this a disease model property that the user should specify?
boolean isDataPath = false;
boolean isURI = false;
if (isUserSpecifiedProperty(feature)) {
// Yes
final Label label = new Label(this, SWT.NONE);
label.setText(pspa.getPropertyName(descriptor));
final GridData labelGD = new GridData(GridData.BEGINNING);
labelGD.grabExcessHorizontalSpace = true;
labelGD.horizontalAlignment = SWT.FILL;
labelGD.horizontalIndent = 0;
label.setLayoutData(labelGD);
// Get a string value for the default value of the feature
final String defaultValueString = getPropertyDefaultValueString(descriptor);
EClassifier classifier = feature.getEType();
if(classifier.getName().equals("EBoolean")) {
Composite radioComposite = new Composite(this, SWT.BORDER);
FillLayout fillLayout = new FillLayout();
fillLayout.type = SWT.HORIZONTAL;
radioComposite.setLayout(fillLayout);
final Button falseButton = new Button(radioComposite, SWT.RADIO);
falseButton.setText(Messages.getString("NO"));//$NON-NLS-1$
Button trueButton = new Button(radioComposite, SWT.RADIO);
trueButton.setText(Messages.getString("YES"));//$NON-NLS-1$
if(defaultValueString != null) {
trueButton.setSelection(defaultValueString.equals("true"));
falseButton.setSelection(!defaultValueString.equals("true"));
}
else {falseButton.setSelection(true);trueButton.setSelection(false);}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == falseButton) {
booleanMap.put(feature, !falseButton.getSelection());
}
}
};
// these are radio buttons so we only need to add the listener to one of them.
falseButton.addListener(SWT.Selection, listener);
final GridData cGD = new GridData(GridData.END);
cGD.grabExcessHorizontalSpace = true;
cGD.horizontalAlignment = SWT.FILL;
radioComposite.setLayoutData(cGD);
} else if(classifier.getName().equals("URI")) {
// Bring up location picker for URI's
isURI = true;
final Text isokeyValueText = new Text(this, SWT.NONE);
isokeyValueText.setText("");
map.put(feature, isokeyValueText);
final GridData gd_isoKeyLabelValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
isokeyValueText.setLayoutData(gd_isoKeyLabelValue);
final Button locationButton = new Button(this, SWT.NONE);
locationButton.setText(Messages.getString("NPickLoc"));
final GridData lb_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
locationButton.setLayoutData(lb_isoKeyLabel);
locationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
LocationPickerDialog lpDialog = new LocationPickerDialog(GenericPropertyEditor.this.getShell(), SWT.NONE, Messages.getString("NPickLocTitle"), isokeyValueText.getText(), GenericPropertyEditor.this.project);
Object [] ret = lpDialog.open();
if(ret != null) {
if(ret[1] != null)
isokeyValueText.setText(((URI)ret[1]).toString());
else
isokeyValueText.setText(STEMURI.createURI("node/geo/region/"+((String)ret[0])).toString());
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
} else {
// Not a boolean
Text text = null;
if(isListOrMap(feature))
handleListOrMap(feature);
else {
text = new Text(this, SWT.BORDER | SWT.TRAIL);
if(defaultValueString != null)
text.setText(defaultValueString);
text.setToolTipText(pspa.getPropertyToolTip(descriptor));
map.put(feature, text);
final GridData textGD = new GridData(GridData.END);
textGD.grabExcessHorizontalSpace = true;
textGD.horizontalAlignment = SWT.FILL;
text.setLayoutData(textGD);
text.addModifyListener(projectValidator);
}
if (feature.getName().equals("dataPath")) { //$NON-NLS-1$
isDataPath = true;
final Composite buttons = new Composite(this, SWT.NONE);
final RowLayout buttonsLayout = new RowLayout();
buttonsLayout.marginTop = 0;
buttonsLayout.marginBottom = 0;
buttons.setLayout(buttonsLayout);
final Shell shell = this.getShell();
final Button fileChooserButton = new Button(buttons,
SWT.NONE);
fileChooserButton.setText(Messages
.getString("fileChooserButtonText")); //$NON-NLS-1$
fileChooserButton.setToolTipText(Messages
.getString("fileChooserButtonTooltipText")); //$NON-NLS-1$
final Text _text=text;
fileChooserButton
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(
final SelectionEvent e) {
final FileDialog fd = new FileDialog(shell,
SWT.OPEN | SWT.MULTI);
fd
.setText(Messages
.getString("fileChooserDialogTitle")); //$NON-NLS-1$
final String[] extensionsFilter = {
"*.txt", "*.csv" };
fd.setFilterExtensions(extensionsFilter);
// String format for single selected file
// will be:
// "path/file_name"
// For multi-files the format will be:
// "path/file_name1" "file_name2"
// "file_name3"...
String selected = "\"" + fd.open() + "\"";
final String[] selectedFiles = fd
.getFileNames();
if (selectedFiles.length > 1) { // if
// multi-files
// selected
+ StringBuilder str = new StringBuilder(selected);
for (int i = 1; i < selectedFiles.length; i++) {
- selected += " \""
- + selectedFiles[i] + "\"";
+ str.append(" \"");
+ str.append(selectedFiles[i]);
+ str.append("\"");
+// selected += " \""
+// + selectedFiles[i] + "\"";
}
+ selected = str.toString();
}
_text.setText(selected);
} // widgetSelected
} // SelectionAdapter
);
final Button dirChooserButton = new Button(buttons,
SWT.NONE);
dirChooserButton.setText(Messages
.getString("dirChooserButtonText")); //$NON-NLS-1$
dirChooserButton.setToolTipText(Messages
.getString("dirChooserButtonTooltipText")); //$NON-NLS-1$
dirChooserButton
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(
final SelectionEvent e) {
final DirectoryDialog dd = new DirectoryDialog(
shell, SWT.OPEN);
dd
.setText(Messages
.getString("dirChooserDialogTitle")); //$NON-NLS-1$
final String selected = dd.open();
_text.setText(selected);
} // widgetSelected
} // SelectionAdapter
);
final GridData fileBtnGD = new GridData(GridData.END);
// fileChooserButton.setLayoutData(fileBtnGD);
buttons.setLayoutData(fileBtnGD);
}
else if (feature.getName().startsWith("dataFile")) { //$NON-NLS-1$
isDataPath = true;
final Composite buttons = new Composite(this, SWT.NONE);
final RowLayout buttonsLayout = new RowLayout();
buttonsLayout.marginTop = 0;
buttonsLayout.marginBottom = 0;
buttons.setLayout(buttonsLayout);
final Shell shell = this.getShell();
final Button fileChooserButton = new Button(buttons, SWT.NONE);
fileChooserButton.setText(Messages.getString("fileChooserButtonText")); //$NON-NLS-1$
fileChooserButton.setToolTipText(Messages.getString("fileChooserButtonTooltipText")); //$NON-NLS-1$
final Text _text=text;
fileChooserButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final FileDialog fd = new FileDialog(shell, SWT.OPEN | SWT.SINGLE);
fd.setText(Messages.getString("fileChooserDialogTitle")); //$NON-NLS-1$
StringTokenizer tok = new StringTokenizer(feature.getName(), "_");
Vector<String> v = new Vector<String>();
tok.nextToken();
while (tok.hasMoreTokens()) {
v.add("*." + tok.nextToken());
}
v.add("*");
final String[] extensionsFilter = new String[v.size()];
fd.setFilterExtensions(v.toArray(extensionsFilter));
_text.setText(fd.open());
} // widgetSelected
} // SelectionAdapter
);
final GridData fileBtnGD = new GridData(GridData.END);
// fileChooserButton.setLayoutData(fileBtnGD);
buttons.setLayoutData(fileBtnGD);
}
} // is not boolean
if (!isDataPath && !isURI) {
final Label unitLabel = new Label(this, SWT.NONE);
unitLabel.setText(pspa.getPropertyUnits(descriptor));
final GridData unitLabelGD = new GridData(GridData.END);
unitLabelGD.verticalAlignment = GridData.CENTER;
unitLabel.setLayoutData(unitLabelGD);
}
} // if user specified
} // for each disease model property
} // GraphGeneratorPropertyEditor
private void handleListOrMap(final EStructuralFeature feature) {
Button button = new Button(this, SWT.NONE);
Image image = null;
final EClassifier type = feature.getEType();
if (type.getClassifierID() == CommonPackage.DOUBLE_VALUE_LIST ||
type.getClassifierID() == CommonPackage.STRING_VALUE_LIST)
image = AbstractUIPlugin.imageDescriptorFromPlugin(
"org.eclipse.stem.ui", "/icons/full/customobj16/List.gif").createImage();
else
image = AbstractUIPlugin.imageDescriptorFromPlugin(
"org.eclipse.stem.ui", "/icons/full/customobj16/Matrix.gif").createImage();
button.setImage(image);
final GridData buttonGD = new GridData(GridData.END);
//buttonGD.grabExcessHorizontalSpace = true;
//buttonGD.horizontalAlignment = SWT.FILL;
button.setLayoutData(buttonGD);
button.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
String title=null;
short cols=0;
short rows=0;
String [] rownames=null;
String [] colnames=null;
boolean fixedSize=false;
MatrixEditorValidator validator = null;
String [] existingVals=null;
// Retrieve any already entered values
if(matrixMap.get(feature)!=null) {
existingVals = matrixMap.get(feature);
}
if(type.getClassifierID() == CommonPackage.DOUBLE_VALUE_LIST ||
type.getClassifierID() == CommonPackage.STRING_VALUE_LIST) {
fixedSize = getFixedSize(feature);
title = feature.getName();
cols = 1;
rows = getRowCount(feature);
if(!fixedSize && rows == 0)
rows = (existingVals != null)? (short)existingVals.length:(short)1;
rownames = getRowNames(feature);
colnames = new String[1];colnames[0]=feature.getName();
} else if(type.getClassifierID() == CommonPackage.DOUBLE_VALUE_MATRIX) {
title = feature.getName();
cols = getColCount(feature);
rows = getRowCount(feature);
rownames = getRowNames(feature);
colnames = rownames;
fixedSize = getFixedSize(feature);
}
validator = getValidator(feature);
// Pre-populate with 0 (default from EMF not possible since it's a reference)
if(existingVals == null && (type.getClassifierID() == CommonPackage.DOUBLE_VALUE_LIST || type.getClassifierID() == CommonPackage.DOUBLE_VALUE_MATRIX)) {
existingVals = new String[cols*rows];
for(int i=0;i<cols*rows;++i) existingVals[i]="0.0";
}
Shell shell = GenericPropertyEditor.this.getShell();
MatrixEditorDialog dialog = new MatrixEditorDialog(shell, SWT.NONE, title, rows, cols, rownames, colnames, existingVals,fixedSize,validator);
String []res = dialog.open();
if(res!=null) {
matrixMap.put(feature, res);
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* getValidator. These are generic validators for strings and doubles. Override in
* subclass for more advanced validation (>0 etc.)
* @param feature
* @return
*/
public MatrixEditorValidator getValidator(EStructuralFeature feature) {
EClassifier type = feature.getEType();
MatrixEditorValidator validator=null;
if(type.getClassifierID() == CommonPackage.DOUBLE_VALUE_LIST ||
type.getClassifierID() == CommonPackage.DOUBLE_VALUE_MATRIX)
validator = new MatrixEditorValidator() {
public boolean validateValue(String val) {
if(val == null || val.trim().equals("")) return false;
try {
Double.parseDouble(val.trim());
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
};
else if(type.getClassifierID() == CommonPackage.STRING_VALUE_LIST)
validator = new MatrixEditorValidator() {
public boolean validateValue(String val) {
if(val == null || val.trim().equals("")) return false;
return true;
}
};
return validator;
}
/**
* These are overriden by subclass
*/
public short getColCount(EStructuralFeature feature) {
return 1;
}
public boolean getFixedSize(EStructuralFeature feature) {
return false;
}
public String[] getRowNames(EStructuralFeature feature) {
return null;
}
public String[] getColNames(EStructuralFeature feature) {
return null;
}
public short getRowCount(EStructuralFeature feature) {
return 1;
}
private boolean isListOrMap(EStructuralFeature feature) {
EClassifier type = feature.getEType();
if(type.getClassifierID() == CommonPackage.DOUBLE_VALUE_LIST ||
type.getClassifierID() == CommonPackage.STRING_VALUE_LIST ||
type.getClassifierID() == CommonPackage.DOUBLE_VALUE_MATRIX)
return true;
else return false;
}
/**
* @return <code>true</code> if the contents are valid, <code>false</code>
* otherwise.
*/
protected abstract boolean validate();
/**
* @param feature
* @return <code>true</code> if the feature is a dublin core feature that
* is specified by a user.
*/
protected abstract boolean isUserSpecifiedProperty(final EStructuralFeature feature);
/**
* @param text
* @param minValue
* @return
*/
protected boolean isValidLongValue(final String text, final long minValue) {
boolean retValue = true;
try {
final double value = Long.parseLong(text);
retValue = value >= minValue;
} catch (final NumberFormatException nfe) {
retValue = false;
} // catch ParseException
return retValue;
}
/**
* @param text
* @return
*/
protected boolean isValidPercentage(final String text) {
boolean retValue = true;
try {
final double value = Double.parseDouble(text);
retValue = value >= 0.0 && value <= 100.;
} catch (final NumberFormatException nfe) {
retValue = false;
} // catch ParseException
return retValue;
}
/**
* @param text
* @param minValue
* @return
*/
protected boolean isValidValue(final String text, final double minValue) {
boolean retValue = true;
try {
final double value = Double.parseDouble(text);
retValue = value >= minValue;
} catch (final NumberFormatException nfe) {
retValue = false;
} // catch ParseException
return retValue;
} // isValidRate
/**
* @param text
* @param minValue
* @return
*/
protected boolean isValidIntValue(final String text, final int minValue) {
boolean retValue = true;
try {
final double value = Integer.parseInt(text);
retValue = value >= minValue;
} catch (final NumberFormatException nfe) {
retValue = false;
} // catch ParseException
return retValue;
} // isValidIntRate
/**
* @param text
* @param minValue
* @return
*/
protected boolean isValidDoubleValue(final String text, final int minValue) {
boolean retValue = true;
try {
final double value = Double.parseDouble(text);
retValue = value >= minValue;
} catch (final NumberFormatException nfe) {
retValue = false;
} // catch ParseException
return retValue;
} // isValidIntRate
@Override
public void dispose() {
super.dispose();
}
@Override
protected void checkSubclass() {
// Disable the check that prevents sub-classing of SWT components
}
/**
* @param descriptor
* @return the string that represents the default value of the property
*/
protected String getPropertyDefaultValueString(final IItemPropertyDescriptor descriptor) {
final EStructuralFeature feature = (EStructuralFeature) descriptor
.getFeature(null);
return feature.getDefaultValueLiteral();
}
/**
* @return the error message that describes the problem with the contents
*/
public String getErrorMessage() {
return errorMessage;
}
} // GenericPropertyEditor
| false | true | public GenericPropertyEditor(final Composite parent, final int style,
final Identifiable identifiable,
final ModifyListener projectValidator, IProject project) {
super(parent, style);
this.project = project;
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
setLayout(gridLayout);
// Get the adapter that will provide NLS'd names for the
// properties of the disease model
final PropertyStringProviderAdapter pspa = (PropertyStringProviderAdapter) PropertyStringProviderAdapterFactory.INSTANCE
.adapt(identifiable, PropertyStringProvider.class);
final ComposedAdapterFactory itemProviderFactory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
final IItemPropertySource propertySource = (IItemPropertySource) itemProviderFactory
.adapt(identifiable, IItemPropertySource.class);
final List<IItemPropertyDescriptor> properties = propertySource
.getPropertyDescriptors(identifiable);
for (final IItemPropertyDescriptor descriptor : properties) {
final EStructuralFeature feature = (EStructuralFeature) descriptor
.getFeature(null);
// Is this a disease model property that the user should specify?
boolean isDataPath = false;
boolean isURI = false;
if (isUserSpecifiedProperty(feature)) {
// Yes
final Label label = new Label(this, SWT.NONE);
label.setText(pspa.getPropertyName(descriptor));
final GridData labelGD = new GridData(GridData.BEGINNING);
labelGD.grabExcessHorizontalSpace = true;
labelGD.horizontalAlignment = SWT.FILL;
labelGD.horizontalIndent = 0;
label.setLayoutData(labelGD);
// Get a string value for the default value of the feature
final String defaultValueString = getPropertyDefaultValueString(descriptor);
EClassifier classifier = feature.getEType();
if(classifier.getName().equals("EBoolean")) {
Composite radioComposite = new Composite(this, SWT.BORDER);
FillLayout fillLayout = new FillLayout();
fillLayout.type = SWT.HORIZONTAL;
radioComposite.setLayout(fillLayout);
final Button falseButton = new Button(radioComposite, SWT.RADIO);
falseButton.setText(Messages.getString("NO"));//$NON-NLS-1$
Button trueButton = new Button(radioComposite, SWT.RADIO);
trueButton.setText(Messages.getString("YES"));//$NON-NLS-1$
if(defaultValueString != null) {
trueButton.setSelection(defaultValueString.equals("true"));
falseButton.setSelection(!defaultValueString.equals("true"));
}
else {falseButton.setSelection(true);trueButton.setSelection(false);}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == falseButton) {
booleanMap.put(feature, !falseButton.getSelection());
}
}
};
// these are radio buttons so we only need to add the listener to one of them.
falseButton.addListener(SWT.Selection, listener);
final GridData cGD = new GridData(GridData.END);
cGD.grabExcessHorizontalSpace = true;
cGD.horizontalAlignment = SWT.FILL;
radioComposite.setLayoutData(cGD);
} else if(classifier.getName().equals("URI")) {
// Bring up location picker for URI's
isURI = true;
final Text isokeyValueText = new Text(this, SWT.NONE);
isokeyValueText.setText("");
map.put(feature, isokeyValueText);
final GridData gd_isoKeyLabelValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
isokeyValueText.setLayoutData(gd_isoKeyLabelValue);
final Button locationButton = new Button(this, SWT.NONE);
locationButton.setText(Messages.getString("NPickLoc"));
final GridData lb_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
locationButton.setLayoutData(lb_isoKeyLabel);
locationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
LocationPickerDialog lpDialog = new LocationPickerDialog(GenericPropertyEditor.this.getShell(), SWT.NONE, Messages.getString("NPickLocTitle"), isokeyValueText.getText(), GenericPropertyEditor.this.project);
Object [] ret = lpDialog.open();
if(ret != null) {
if(ret[1] != null)
isokeyValueText.setText(((URI)ret[1]).toString());
else
isokeyValueText.setText(STEMURI.createURI("node/geo/region/"+((String)ret[0])).toString());
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
} else {
// Not a boolean
Text text = null;
if(isListOrMap(feature))
handleListOrMap(feature);
else {
text = new Text(this, SWT.BORDER | SWT.TRAIL);
if(defaultValueString != null)
text.setText(defaultValueString);
text.setToolTipText(pspa.getPropertyToolTip(descriptor));
map.put(feature, text);
final GridData textGD = new GridData(GridData.END);
textGD.grabExcessHorizontalSpace = true;
textGD.horizontalAlignment = SWT.FILL;
text.setLayoutData(textGD);
text.addModifyListener(projectValidator);
}
if (feature.getName().equals("dataPath")) { //$NON-NLS-1$
isDataPath = true;
final Composite buttons = new Composite(this, SWT.NONE);
final RowLayout buttonsLayout = new RowLayout();
buttonsLayout.marginTop = 0;
buttonsLayout.marginBottom = 0;
buttons.setLayout(buttonsLayout);
final Shell shell = this.getShell();
final Button fileChooserButton = new Button(buttons,
SWT.NONE);
fileChooserButton.setText(Messages
.getString("fileChooserButtonText")); //$NON-NLS-1$
fileChooserButton.setToolTipText(Messages
.getString("fileChooserButtonTooltipText")); //$NON-NLS-1$
final Text _text=text;
fileChooserButton
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(
final SelectionEvent e) {
final FileDialog fd = new FileDialog(shell,
SWT.OPEN | SWT.MULTI);
fd
.setText(Messages
.getString("fileChooserDialogTitle")); //$NON-NLS-1$
final String[] extensionsFilter = {
"*.txt", "*.csv" };
fd.setFilterExtensions(extensionsFilter);
// String format for single selected file
// will be:
// "path/file_name"
// For multi-files the format will be:
// "path/file_name1" "file_name2"
// "file_name3"...
String selected = "\"" + fd.open() + "\"";
final String[] selectedFiles = fd
.getFileNames();
if (selectedFiles.length > 1) { // if
// multi-files
// selected
for (int i = 1; i < selectedFiles.length; i++) {
selected += " \""
+ selectedFiles[i] + "\"";
}
}
_text.setText(selected);
} // widgetSelected
} // SelectionAdapter
);
final Button dirChooserButton = new Button(buttons,
SWT.NONE);
dirChooserButton.setText(Messages
.getString("dirChooserButtonText")); //$NON-NLS-1$
dirChooserButton.setToolTipText(Messages
.getString("dirChooserButtonTooltipText")); //$NON-NLS-1$
dirChooserButton
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(
final SelectionEvent e) {
final DirectoryDialog dd = new DirectoryDialog(
shell, SWT.OPEN);
dd
.setText(Messages
.getString("dirChooserDialogTitle")); //$NON-NLS-1$
final String selected = dd.open();
_text.setText(selected);
} // widgetSelected
} // SelectionAdapter
);
final GridData fileBtnGD = new GridData(GridData.END);
// fileChooserButton.setLayoutData(fileBtnGD);
buttons.setLayoutData(fileBtnGD);
}
else if (feature.getName().startsWith("dataFile")) { //$NON-NLS-1$
isDataPath = true;
final Composite buttons = new Composite(this, SWT.NONE);
final RowLayout buttonsLayout = new RowLayout();
buttonsLayout.marginTop = 0;
buttonsLayout.marginBottom = 0;
buttons.setLayout(buttonsLayout);
final Shell shell = this.getShell();
final Button fileChooserButton = new Button(buttons, SWT.NONE);
fileChooserButton.setText(Messages.getString("fileChooserButtonText")); //$NON-NLS-1$
fileChooserButton.setToolTipText(Messages.getString("fileChooserButtonTooltipText")); //$NON-NLS-1$
final Text _text=text;
fileChooserButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final FileDialog fd = new FileDialog(shell, SWT.OPEN | SWT.SINGLE);
fd.setText(Messages.getString("fileChooserDialogTitle")); //$NON-NLS-1$
StringTokenizer tok = new StringTokenizer(feature.getName(), "_");
Vector<String> v = new Vector<String>();
tok.nextToken();
while (tok.hasMoreTokens()) {
v.add("*." + tok.nextToken());
}
v.add("*");
final String[] extensionsFilter = new String[v.size()];
fd.setFilterExtensions(v.toArray(extensionsFilter));
_text.setText(fd.open());
} // widgetSelected
} // SelectionAdapter
);
final GridData fileBtnGD = new GridData(GridData.END);
// fileChooserButton.setLayoutData(fileBtnGD);
buttons.setLayoutData(fileBtnGD);
}
} // is not boolean
if (!isDataPath && !isURI) {
final Label unitLabel = new Label(this, SWT.NONE);
unitLabel.setText(pspa.getPropertyUnits(descriptor));
final GridData unitLabelGD = new GridData(GridData.END);
unitLabelGD.verticalAlignment = GridData.CENTER;
unitLabel.setLayoutData(unitLabelGD);
}
} // if user specified
} // for each disease model property
} // GraphGeneratorPropertyEditor
| public GenericPropertyEditor(final Composite parent, final int style,
final Identifiable identifiable,
final ModifyListener projectValidator, IProject project) {
super(parent, style);
this.project = project;
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
setLayout(gridLayout);
// Get the adapter that will provide NLS'd names for the
// properties of the disease model
final PropertyStringProviderAdapter pspa = (PropertyStringProviderAdapter) PropertyStringProviderAdapterFactory.INSTANCE
.adapt(identifiable, PropertyStringProvider.class);
final ComposedAdapterFactory itemProviderFactory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
final IItemPropertySource propertySource = (IItemPropertySource) itemProviderFactory
.adapt(identifiable, IItemPropertySource.class);
final List<IItemPropertyDescriptor> properties = propertySource
.getPropertyDescriptors(identifiable);
for (final IItemPropertyDescriptor descriptor : properties) {
final EStructuralFeature feature = (EStructuralFeature) descriptor
.getFeature(null);
// Is this a disease model property that the user should specify?
boolean isDataPath = false;
boolean isURI = false;
if (isUserSpecifiedProperty(feature)) {
// Yes
final Label label = new Label(this, SWT.NONE);
label.setText(pspa.getPropertyName(descriptor));
final GridData labelGD = new GridData(GridData.BEGINNING);
labelGD.grabExcessHorizontalSpace = true;
labelGD.horizontalAlignment = SWT.FILL;
labelGD.horizontalIndent = 0;
label.setLayoutData(labelGD);
// Get a string value for the default value of the feature
final String defaultValueString = getPropertyDefaultValueString(descriptor);
EClassifier classifier = feature.getEType();
if(classifier.getName().equals("EBoolean")) {
Composite radioComposite = new Composite(this, SWT.BORDER);
FillLayout fillLayout = new FillLayout();
fillLayout.type = SWT.HORIZONTAL;
radioComposite.setLayout(fillLayout);
final Button falseButton = new Button(radioComposite, SWT.RADIO);
falseButton.setText(Messages.getString("NO"));//$NON-NLS-1$
Button trueButton = new Button(radioComposite, SWT.RADIO);
trueButton.setText(Messages.getString("YES"));//$NON-NLS-1$
if(defaultValueString != null) {
trueButton.setSelection(defaultValueString.equals("true"));
falseButton.setSelection(!defaultValueString.equals("true"));
}
else {falseButton.setSelection(true);trueButton.setSelection(false);}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == falseButton) {
booleanMap.put(feature, !falseButton.getSelection());
}
}
};
// these are radio buttons so we only need to add the listener to one of them.
falseButton.addListener(SWT.Selection, listener);
final GridData cGD = new GridData(GridData.END);
cGD.grabExcessHorizontalSpace = true;
cGD.horizontalAlignment = SWT.FILL;
radioComposite.setLayoutData(cGD);
} else if(classifier.getName().equals("URI")) {
// Bring up location picker for URI's
isURI = true;
final Text isokeyValueText = new Text(this, SWT.NONE);
isokeyValueText.setText("");
map.put(feature, isokeyValueText);
final GridData gd_isoKeyLabelValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
isokeyValueText.setLayoutData(gd_isoKeyLabelValue);
final Button locationButton = new Button(this, SWT.NONE);
locationButton.setText(Messages.getString("NPickLoc"));
final GridData lb_isoKeyLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
locationButton.setLayoutData(lb_isoKeyLabel);
locationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
LocationPickerDialog lpDialog = new LocationPickerDialog(GenericPropertyEditor.this.getShell(), SWT.NONE, Messages.getString("NPickLocTitle"), isokeyValueText.getText(), GenericPropertyEditor.this.project);
Object [] ret = lpDialog.open();
if(ret != null) {
if(ret[1] != null)
isokeyValueText.setText(((URI)ret[1]).toString());
else
isokeyValueText.setText(STEMURI.createURI("node/geo/region/"+((String)ret[0])).toString());
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
} else {
// Not a boolean
Text text = null;
if(isListOrMap(feature))
handleListOrMap(feature);
else {
text = new Text(this, SWT.BORDER | SWT.TRAIL);
if(defaultValueString != null)
text.setText(defaultValueString);
text.setToolTipText(pspa.getPropertyToolTip(descriptor));
map.put(feature, text);
final GridData textGD = new GridData(GridData.END);
textGD.grabExcessHorizontalSpace = true;
textGD.horizontalAlignment = SWT.FILL;
text.setLayoutData(textGD);
text.addModifyListener(projectValidator);
}
if (feature.getName().equals("dataPath")) { //$NON-NLS-1$
isDataPath = true;
final Composite buttons = new Composite(this, SWT.NONE);
final RowLayout buttonsLayout = new RowLayout();
buttonsLayout.marginTop = 0;
buttonsLayout.marginBottom = 0;
buttons.setLayout(buttonsLayout);
final Shell shell = this.getShell();
final Button fileChooserButton = new Button(buttons,
SWT.NONE);
fileChooserButton.setText(Messages
.getString("fileChooserButtonText")); //$NON-NLS-1$
fileChooserButton.setToolTipText(Messages
.getString("fileChooserButtonTooltipText")); //$NON-NLS-1$
final Text _text=text;
fileChooserButton
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(
final SelectionEvent e) {
final FileDialog fd = new FileDialog(shell,
SWT.OPEN | SWT.MULTI);
fd
.setText(Messages
.getString("fileChooserDialogTitle")); //$NON-NLS-1$
final String[] extensionsFilter = {
"*.txt", "*.csv" };
fd.setFilterExtensions(extensionsFilter);
// String format for single selected file
// will be:
// "path/file_name"
// For multi-files the format will be:
// "path/file_name1" "file_name2"
// "file_name3"...
String selected = "\"" + fd.open() + "\"";
final String[] selectedFiles = fd
.getFileNames();
if (selectedFiles.length > 1) { // if
// multi-files
// selected
StringBuilder str = new StringBuilder(selected);
for (int i = 1; i < selectedFiles.length; i++) {
str.append(" \"");
str.append(selectedFiles[i]);
str.append("\"");
// selected += " \""
// + selectedFiles[i] + "\"";
}
selected = str.toString();
}
_text.setText(selected);
} // widgetSelected
} // SelectionAdapter
);
final Button dirChooserButton = new Button(buttons,
SWT.NONE);
dirChooserButton.setText(Messages
.getString("dirChooserButtonText")); //$NON-NLS-1$
dirChooserButton.setToolTipText(Messages
.getString("dirChooserButtonTooltipText")); //$NON-NLS-1$
dirChooserButton
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(
final SelectionEvent e) {
final DirectoryDialog dd = new DirectoryDialog(
shell, SWT.OPEN);
dd
.setText(Messages
.getString("dirChooserDialogTitle")); //$NON-NLS-1$
final String selected = dd.open();
_text.setText(selected);
} // widgetSelected
} // SelectionAdapter
);
final GridData fileBtnGD = new GridData(GridData.END);
// fileChooserButton.setLayoutData(fileBtnGD);
buttons.setLayoutData(fileBtnGD);
}
else if (feature.getName().startsWith("dataFile")) { //$NON-NLS-1$
isDataPath = true;
final Composite buttons = new Composite(this, SWT.NONE);
final RowLayout buttonsLayout = new RowLayout();
buttonsLayout.marginTop = 0;
buttonsLayout.marginBottom = 0;
buttons.setLayout(buttonsLayout);
final Shell shell = this.getShell();
final Button fileChooserButton = new Button(buttons, SWT.NONE);
fileChooserButton.setText(Messages.getString("fileChooserButtonText")); //$NON-NLS-1$
fileChooserButton.setToolTipText(Messages.getString("fileChooserButtonTooltipText")); //$NON-NLS-1$
final Text _text=text;
fileChooserButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final FileDialog fd = new FileDialog(shell, SWT.OPEN | SWT.SINGLE);
fd.setText(Messages.getString("fileChooserDialogTitle")); //$NON-NLS-1$
StringTokenizer tok = new StringTokenizer(feature.getName(), "_");
Vector<String> v = new Vector<String>();
tok.nextToken();
while (tok.hasMoreTokens()) {
v.add("*." + tok.nextToken());
}
v.add("*");
final String[] extensionsFilter = new String[v.size()];
fd.setFilterExtensions(v.toArray(extensionsFilter));
_text.setText(fd.open());
} // widgetSelected
} // SelectionAdapter
);
final GridData fileBtnGD = new GridData(GridData.END);
// fileChooserButton.setLayoutData(fileBtnGD);
buttons.setLayoutData(fileBtnGD);
}
} // is not boolean
if (!isDataPath && !isURI) {
final Label unitLabel = new Label(this, SWT.NONE);
unitLabel.setText(pspa.getPropertyUnits(descriptor));
final GridData unitLabelGD = new GridData(GridData.END);
unitLabelGD.verticalAlignment = GridData.CENTER;
unitLabel.setLayoutData(unitLabelGD);
}
} // if user specified
} // for each disease model property
} // GraphGeneratorPropertyEditor
|
diff --git a/src/biz/bokhorst/xprivacy/PrivacyService.java b/src/biz/bokhorst/xprivacy/PrivacyService.java
index c8dbdb3f..6d87b014 100644
--- a/src/biz/bokhorst/xprivacy/PrivacyService.java
+++ b/src/biz/bokhorst/xprivacy/PrivacyService.java
@@ -1,2170 +1,2170 @@
package biz.bokhorst.xprivacy;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Process;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class PrivacyService {
private static int mXUid = -1;
private static boolean mRegistered = false;
private static boolean mUseCache = false;
private static String mSecret = null;
private static Thread mWorker = null;
private static Handler mHandler = null;
private static Semaphore mOndemandSemaphore = new Semaphore(1, true);
private static List<String> mListError = new ArrayList<String>();
private static IPrivacyService mClient = null;
private static final String cTableRestriction = "restriction";
private static final String cTableUsage = "usage";
private static final String cTableSetting = "setting";
private static final int cCurrentVersion = 311;
private static final String cServiceName = "xprivacy305";
// TODO: define column names
// sqlite3 /data/system/xprivacy/xprivacy.db
public static void register(List<String> listError, String secret) {
// Store secret and errors
mSecret = secret;
mListError.addAll(listError);
try {
// Register privacy service
// @formatter:off
// public static void addService(String name, IBinder service)
// public static void addService(String name, IBinder service, boolean allowIsolated)
// @formatter:on
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class,
boolean.class);
mAddService.invoke(null, cServiceName, mPrivacyService, true);
} else {
Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class);
mAddService.invoke(null, cServiceName, mPrivacyService);
}
// This will and should open the database
mRegistered = true;
Util.log(null, Log.WARN, "Service registered name=" + cServiceName);
// Publish semaphore to activity manager service
XActivityManagerService.setSemaphore(mOndemandSemaphore);
// Get memory class to enable/disable caching
// http://stackoverflow.com/questions/2630158/detect-application-heap-size-in-android
int memoryClass = (int) (Runtime.getRuntime().maxMemory() / 1024L / 1024L);
mUseCache = (memoryClass >= 32);
Util.log(null, Log.WARN, "Memory class=" + memoryClass + " cache=" + mUseCache);
// Start a worker thread
mWorker = new Thread(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
mHandler = new Handler();
Looper.loop();
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
});
mWorker.start();
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
public static boolean isRegistered() {
return mRegistered;
}
public static boolean checkClient() {
// Runs client side
try {
IPrivacyService client = getClient();
if (client != null)
return (client.getVersion() == cCurrentVersion);
} catch (RemoteException ex) {
Util.bug(null, ex);
}
return false;
}
public static IPrivacyService getClient() {
// Runs client side
if (mClient == null)
try {
// public static IBinder getService(String name)
Class<?> cServiceManager = Class.forName("android.os.ServiceManager");
Method mGetService = cServiceManager.getDeclaredMethod("getService", String.class);
mClient = IPrivacyService.Stub.asInterface((IBinder) mGetService.invoke(null, cServiceName));
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Disable disk/network strict mode
// TODO: hook setThreadPolicy
try {
ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
ThreadPolicy newpolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites()
.permitNetwork().build();
StrictMode.setThreadPolicy(newpolicy);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return mClient;
}
public static void reportErrorInternal(String message) {
synchronized (mListError) {
mListError.add(message);
}
}
public static PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret)
throws RemoteException {
if (isRegistered())
return mPrivacyService.getRestriction(restriction, usage, secret);
else {
IPrivacyService client = getClient();
if (client == null) {
Log.w("XPrivacy", "No client for " + restriction);
Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace")));
PRestriction result = new PRestriction(restriction);
result.restricted = false;
return result;
} else
return client.getRestriction(restriction, usage, secret);
}
}
public static PSetting getSetting(PSetting setting) throws RemoteException {
if (isRegistered())
return mPrivacyService.getSetting(setting);
else {
IPrivacyService client = getClient();
if (client == null) {
Log.w("XPrivacy", "No client for " + setting + " uid=" + Process.myUid() + " pid=" + Process.myPid());
Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace")));
return setting;
} else
return client.getSetting(setting);
}
}
private static final IPrivacyService.Stub mPrivacyService = new IPrivacyService.Stub() {
private SQLiteDatabase mDb = null;
private SQLiteDatabase mDbUsage = null;
private SQLiteStatement stmtGetRestriction = null;
private SQLiteStatement stmtGetSetting = null;
private SQLiteStatement stmtGetUsageRestriction = null;
private SQLiteStatement stmtGetUsageMethod = null;
private ReentrantReadWriteLock mLock = new ReentrantReadWriteLock(true);
private ReentrantReadWriteLock mLockUsage = new ReentrantReadWriteLock(true);
private boolean mSelectCategory = true;
private boolean mSelectOnce = false;
private Map<CSetting, CSetting> mSettingCache = new HashMap<CSetting, CSetting>();
private Map<CRestriction, CRestriction> mAskedOnceCache = new HashMap<CRestriction, CRestriction>();
private Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>();
private final int cMaxUsageData = 500; // entries
private final int cMaxOnDemandDialog = 20; // seconds
private ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
new PriorityThreadFactory());
final class PriorityThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
}
// Management
@Override
public int getVersion() throws RemoteException {
return cCurrentVersion;
}
@Override
public List<String> check() throws RemoteException {
enforcePermission();
List<String> listError = new ArrayList<String>();
synchronized (mListError) {
int c = 0;
int i = 0;
while (i < mListError.size()) {
String msg = mListError.get(i);
c += msg.length();
if (c < 5000)
listError.add(msg);
else
break;
i++;
}
}
File dbFile = getDbFile();
if (!dbFile.exists())
listError.add("Database does not exists");
if (!dbFile.canRead())
listError.add("Database not readable");
if (!dbFile.canWrite())
listError.add("Database not writable");
SQLiteDatabase db = getDb();
if (db == null)
listError.add("Database not available");
else if (!db.isOpen())
listError.add("Database not open");
return listError;
}
@Override
public void reportError(String message) throws RemoteException {
reportErrorInternal(message);
}
// Restrictions
@Override
public void setRestriction(PRestriction restriction) throws RemoteException {
try {
enforcePermission();
setRestrictionInternal(restriction);
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
private void setRestrictionInternal(PRestriction restriction) throws RemoteException {
// Validate
if (restriction.restrictionName == null) {
Util.log(null, Log.ERROR, "Set invalid restriction " + restriction);
Util.logStack(null, Log.ERROR);
throw new RemoteException("Invalid restriction");
}
try {
SQLiteDatabase db = getDb();
if (db == null)
return;
// 0 not restricted, ask
// 1 restricted, ask
// 2 not restricted, asked
// 3 restricted, asked
mLock.writeLock().lock();
db.beginTransaction();
try {
// Create category record
if (restriction.methodName == null) {
ContentValues cvalues = new ContentValues();
cvalues.put("uid", restriction.uid);
cvalues.put("restriction", restriction.restrictionName);
cvalues.put("method", "");
cvalues.put("restricted", (restriction.restricted ? 1 : 0) + (restriction.asked ? 2 : 0));
db.insertWithOnConflict(cTableRestriction, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE);
}
// Create method exception record
if (restriction.methodName != null) {
ContentValues mvalues = new ContentValues();
mvalues.put("uid", restriction.uid);
mvalues.put("restriction", restriction.restrictionName);
mvalues.put("method", restriction.methodName);
mvalues.put("restricted", (restriction.restricted ? 0 : 1) + (restriction.asked ? 2 : 0));
db.insertWithOnConflict(cTableRestriction, null, mvalues, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Update cache
if (mUseCache)
synchronized (mRestrictionCache) {
for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet()))
if (key.isSameMethod(restriction))
mRestrictionCache.remove(key);
CRestriction key = new CRestriction(restriction, restriction.extra);
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
mRestrictionCache.put(key, key);
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void setRestrictionList(List<PRestriction> listRestriction) throws RemoteException {
enforcePermission();
for (PRestriction restriction : listRestriction)
setRestrictionInternal(restriction);
}
@Override
public PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret)
throws RemoteException {
long start = System.currentTimeMillis();
boolean cached = false;
final PRestriction mresult = new PRestriction(restriction);
try {
// No permissions enforced, but usage data requires a secret
// Sanity checks
if (restriction.restrictionName == null) {
Util.log(null, Log.ERROR, "Get invalid restriction " + restriction);
return mresult;
}
if (usage && restriction.methodName == null) {
Util.log(null, Log.ERROR, "Get invalid restriction " + restriction);
return mresult;
}
// Check for self
if (Util.getAppId(restriction.uid) == getXUid()) {
if (PrivacyManager.cIdentification.equals(restriction.restrictionName)
&& "getString".equals(restriction.methodName)) {
mresult.asked = true;
return mresult;
}
if (PrivacyManager.cIPC.equals(restriction.restrictionName)) {
mresult.asked = true;
return mresult;
} else if (PrivacyManager.cStorage.equals(restriction.restrictionName)) {
mresult.asked = true;
return mresult;
} else if (PrivacyManager.cSystem.equals(restriction.restrictionName)) {
mresult.asked = true;
return mresult;
} else if (PrivacyManager.cView.equals(restriction.restrictionName)) {
mresult.asked = true;
return mresult;
}
}
// Get meta data
Hook hook = null;
if (restriction.methodName != null) {
hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName);
if (hook == null)
// Can happen after replacing apk
Util.log(null, Log.WARN, "Hook not found in service: " + restriction);
}
// Check for system component
if (usage && !PrivacyManager.isApplication(restriction.uid))
if (!getSettingBool(0, PrivacyManager.cSettingSystem, false))
return mresult;
// Check if restrictions enabled
if (usage && !getSettingBool(restriction.uid, PrivacyManager.cSettingRestricted, true))
return mresult;
// Check cache
if (mUseCache) {
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key)) {
cached = true;
CRestriction cache = mRestrictionCache.get(key);
mresult.restricted = cache.restricted;
mresult.asked = cache.asked;
}
}
}
if (!cached) {
PRestriction cresult = new PRestriction(restriction.uid, restriction.restrictionName, null);
boolean methodFound = false;
// No permissions required
SQLiteDatabase db = getDb();
if (db == null)
return mresult;
// Precompile statement when needed
if (stmtGetRestriction == null) {
String sql = "SELECT restricted FROM " + cTableRestriction
+ " WHERE uid=? AND restriction=? AND method=?";
stmtGetRestriction = db.compileStatement(sql);
}
// Execute statement
mLock.readLock().lock();
db.beginTransaction();
try {
try {
synchronized (stmtGetRestriction) {
stmtGetRestriction.clearBindings();
stmtGetRestriction.bindLong(1, restriction.uid);
stmtGetRestriction.bindString(2, restriction.restrictionName);
stmtGetRestriction.bindString(3, "");
long state = stmtGetRestriction.simpleQueryForLong();
cresult.restricted = ((state & 1) != 0);
cresult.asked = ((state & 2) != 0);
mresult.restricted = cresult.restricted;
mresult.asked = cresult.asked;
}
} catch (SQLiteDoneException ignored) {
}
if (restriction.methodName != null)
try {
synchronized (stmtGetRestriction) {
stmtGetRestriction.clearBindings();
stmtGetRestriction.bindLong(1, restriction.uid);
stmtGetRestriction.bindString(2, restriction.restrictionName);
stmtGetRestriction.bindString(3, restriction.methodName);
long state = stmtGetRestriction.simpleQueryForLong();
// Method can be excepted
if (mresult.restricted)
mresult.restricted = ((state & 1) == 0);
// Category asked=true takes precedence
if (!mresult.asked)
mresult.asked = ((state & 2) != 0);
methodFound = true;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
// Default dangerous
if (!methodFound && hook != null && hook.isDangerous())
if (!getSettingBool(0, PrivacyManager.cSettingDangerous, false)) {
mresult.restricted = false;
mresult.asked = true;
}
// Check whitelist
if (usage && hook != null && hook.whitelist() != null && restriction.extra != null) {
String value = getSetting(new PSetting(restriction.uid, hook.whitelist(), restriction.extra,
null)).value;
if (value == null) {
String xextra = getXExtra(restriction, hook);
if (xextra != null)
value = getSetting(new PSetting(restriction.uid, hook.whitelist(), xextra, null)).value;
}
if (value != null) {
// true means allow, false means block
mresult.restricted = !Boolean.parseBoolean(value);
mresult.asked = true;
}
}
// Fallback
if (!mresult.restricted && usage && PrivacyManager.isApplication(restriction.uid)
&& !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (hook != null && !hook.isDangerous()) {
mresult.restricted = PrivacyProvider.getRestrictedFallback(null, restriction.uid,
restriction.restrictionName, restriction.methodName);
Util.log(null, Log.WARN, "Fallback " + mresult);
}
}
// Update cache
if (mUseCache) {
CRestriction key = new CRestriction(mresult, restriction.extra);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
mRestrictionCache.put(key, key);
}
}
}
// Ask to restrict
boolean ondemand = false;
if (!mresult.asked && usage && PrivacyManager.isApplication(restriction.uid))
ondemand = onDemandDialog(hook, restriction, mresult);
// Notify user
if (!ondemand && mresult.restricted && usage && hook != null && hook.shouldNotify())
notifyRestricted(restriction);
// Store usage data
if (usage && hook != null && hook.hasUsageData())
storeUsageData(restriction, secret, mresult);
} catch (Throwable ex) {
Util.bug(null, ex);
}
long ms = System.currentTimeMillis() - start;
Util.log(null, Log.INFO,
String.format("get service %s%s %d ms", restriction, (cached ? " (cached)" : ""), ms));
return mresult;
}
private void storeUsageData(final PRestriction restriction, String secret, final PRestriction mresult)
throws RemoteException {
// Check if enabled
if (getSettingBool(0, PrivacyManager.cSettingUsage, true)) {
// Check secret
boolean allowed = true;
if (Util.getAppId(Binder.getCallingUid()) != getXUid()) {
if (mSecret == null || !mSecret.equals(secret)) {
allowed = false;
Util.log(null, Log.WARN, "Invalid secret");
}
}
if (allowed) {
mExecutor.execute(new Runnable() {
public void run() {
try {
if (XActivityManagerService.canWriteUsageData()) {
SQLiteDatabase dbUsage = getDbUsage();
if (dbUsage == null)
return;
String extra = "";
if (restriction.extra != null)
if (getSettingBool(0, PrivacyManager.cSettingParameters, false))
extra = restriction.extra;
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", restriction.uid);
values.put("restriction", restriction.restrictionName);
values.put("method", restriction.methodName);
values.put("restricted", mresult.restricted);
values.put("time", new Date().getTime());
values.put("extra", extra);
dbUsage.insertWithOnConflict(cTableUsage, null, values,
SQLiteDatabase.CONFLICT_REPLACE);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
}
} catch (SQLiteException ex) {
Util.log(null, Log.WARN, ex.toString());
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
});
}
}
}
@Override
public List<PRestriction> getRestrictionList(PRestriction selector) throws RemoteException {
List<PRestriction> result = new ArrayList<PRestriction>();
try {
enforcePermission();
PRestriction query;
if (selector.restrictionName == null)
for (String sRestrictionName : PrivacyManager.getRestrictions()) {
PRestriction restriction = new PRestriction(selector.uid, sRestrictionName, null, false);
query = getRestriction(restriction, false, null);
restriction.restricted = query.restricted;
restriction.asked = query.asked;
result.add(restriction);
}
else
for (Hook md : PrivacyManager.getHooks(selector.restrictionName)) {
PRestriction restriction = new PRestriction(selector.uid, selector.restrictionName,
md.getName(), false);
query = getRestriction(restriction, false, null);
restriction.restricted = query.restricted;
restriction.asked = query.asked;
result.add(restriction);
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteRestrictions(int uid, String restrictionName) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
if ("".equals(restrictionName))
db.delete(cTableRestriction, "uid=?", new String[] { Integer.toString(uid) });
else
db.delete(cTableRestriction, "uid=? AND restriction=?", new String[] { Integer.toString(uid),
restrictionName });
Util.log(null, Log.WARN, "Restrictions deleted uid=" + uid + " category=" + restrictionName);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear caches
if (mUseCache)
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mAskedOnceCache) {
mAskedOnceCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Usage
@Override
public long getUsage(List<PRestriction> listRestriction) throws RemoteException {
long lastUsage = 0;
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
// Precompile statement when needed
if (stmtGetUsageRestriction == null) {
String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=?";
stmtGetUsageRestriction = dbUsage.compileStatement(sql);
}
if (stmtGetUsageMethod == null) {
String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=? AND method=?";
stmtGetUsageMethod = dbUsage.compileStatement(sql);
}
mLockUsage.readLock().lock();
dbUsage.beginTransaction();
try {
for (PRestriction restriction : listRestriction) {
if (restriction.methodName == null)
try {
synchronized (stmtGetUsageRestriction) {
stmtGetUsageRestriction.clearBindings();
stmtGetUsageRestriction.bindLong(1, restriction.uid);
stmtGetUsageRestriction.bindString(2, restriction.restrictionName);
lastUsage = Math.max(lastUsage, stmtGetUsageRestriction.simpleQueryForLong());
}
} catch (SQLiteDoneException ignored) {
}
else
try {
synchronized (stmtGetUsageMethod) {
stmtGetUsageMethod.clearBindings();
stmtGetUsageMethod.bindLong(1, restriction.uid);
stmtGetUsageMethod.bindString(2, restriction.restrictionName);
stmtGetUsageMethod.bindString(3, restriction.methodName);
lastUsage = Math.max(lastUsage, stmtGetUsageMethod.simpleQueryForLong());
}
} catch (SQLiteDoneException ignored) {
}
}
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return lastUsage;
}
@Override
public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException {
List<PRestriction> result = new ArrayList<PRestriction>();
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
mLockUsage.readLock().lock();
dbUsage.beginTransaction();
try {
Cursor cursor;
if (uid == 0) {
if ("".equals(restrictionName))
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, null, new String[] {}, null, null,
"time DESC LIMIT " + cMaxUsageData);
else
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName },
null, null, "time DESC LIMIT " + cMaxUsageData);
} else {
if ("".equals(restrictionName))
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) },
null, null, "time DESC LIMIT " + cMaxUsageData);
else
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "uid=? AND restriction=?",
new String[] { Integer.toString(uid), restrictionName }, null, null,
"time DESC LIMIT " + cMaxUsageData);
}
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
PRestriction data = new PRestriction();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
data.extra = cursor.getString(5);
result.add(data);
}
} finally {
cursor.close();
}
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
if (uid == 0)
dbUsage.delete(cTableUsage, null, new String[] {});
else
dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(PSetting setting) throws RemoteException {
try {
enforcePermission();
setSettingInternal(setting);
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
private void setSettingInternal(PSetting setting) throws RemoteException {
try {
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND type=? AND name=?",
new String[] { Integer.toString(setting.uid), setting.type, setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("type", setting.type);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Update cache
if (mUseCache) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
key.setValue(setting.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
if (setting.value != null)
mSettingCache.put(key, key);
}
}
// Clear restrictions for white list
if (Meta.isWhitelist(setting.type))
for (String restrictionName : PrivacyManager.getRestrictions())
for (Hook hook : PrivacyManager.getHooks(restrictionName))
if (setting.type.equals(hook.whitelist())) {
PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(),
hook.getName());
Util.log(null, Log.WARN, "Clearing cache for " + restriction);
synchronized (mRestrictionCache) {
for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet()))
if (key.isSameMethod(restriction)) {
Util.log(null, Log.WARN, "Removing " + key);
mRestrictionCache.remove(key);
}
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void setSettingList(List<PSetting> listSetting) throws RemoteException {
enforcePermission();
for (PSetting setting : listSetting)
setSettingInternal(setting);
}
@Override
@SuppressLint("DefaultLocale")
public PSetting getSetting(PSetting setting) throws RemoteException {
PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value);
try {
// No permissions enforced
// Check cache
if (mUseCache && setting.value != null) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key)) {
result.value = mSettingCache.get(key).getValue();
return result;
}
}
}
// No persmissions required
SQLiteDatabase db = getDb();
if (db == null)
return result;
// Fallback
if (!PrivacyManager.cSettingMigrated.equals(setting.name)
&& !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (setting.uid == 0)
result.value = PrivacyProvider.getSettingFallback(setting.name, null, false);
if (result.value == null) {
result.value = PrivacyProvider.getSettingFallback(
String.format("%s.%d", setting.name, setting.uid), setting.value, false);
return result;
}
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
mLock.readLock().lock();
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, setting.uid);
stmtGetSetting.bindString(2, setting.type);
stmtGetSetting.bindString(3, setting.name);
String value = stmtGetSetting.simpleQueryForString();
if (value != null)
result.value = value;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
// Add to cache
if (mUseCache && result.value != null) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
key.setValue(result.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return result;
}
@Override
public List<PSetting> getSettingList(int uid) throws RemoteException {
List<PSetting> listSetting = new ArrayList<PSetting>();
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return listSetting;
mLock.readLock().lock();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor
.getString(2)));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return listSetting;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear cache
if (mUseCache)
synchronized (mSettingCache) {
mSettingCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void clear() throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
SQLiteDatabase dbUsage = getDbUsage();
if (db == null || dbUsage == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM " + cTableRestriction);
db.execSQL("DELETE FROM " + cTableSetting);
Util.log(null, Log.WARN, "Database cleared");
// Reset migrated
ContentValues values = new ContentValues();
values.put("uid", 0);
values.put("type", "");
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear caches
if (mUseCache) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingCache) {
mSettingCache.clear();
}
}
synchronized (mAskedOnceCache) {
mAskedOnceCache.clear();
}
Util.log(null, Log.WARN, "Caches cleared");
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
dbUsage.execSQL("DELETE FROM " + cTableUsage);
Util.log(null, Log.WARN, "Usage database cleared");
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void dump(int uid) throws RemoteException {
if (uid == 0) {
} else {
synchronized (mRestrictionCache) {
for (CRestriction crestriction : mRestrictionCache.keySet())
if (crestriction.getUid() == uid)
Util.log(null, Log.WARN, "Dump crestriction=" + crestriction);
}
synchronized (mAskedOnceCache) {
for (CRestriction crestriction : mAskedOnceCache.keySet())
if (crestriction.getUid() == uid && !crestriction.isExpired())
Util.log(null, Log.WARN, "Dump asked=" + crestriction);
}
synchronized (mSettingCache) {
for (CSetting csetting : mSettingCache.keySet())
if (csetting.getUid() == uid)
Util.log(null, Log.WARN, "Dump csetting=" + csetting);
}
}
}
// Helper methods
private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) {
try {
// Without handler nothing can be done
if (mHandler == null)
return false;
// Check for exceptions
if (hook != null && !hook.canOnDemand())
return false;
// Check if enabled
if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true))
return false;
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false))
return false;
// Skip dangerous methods
final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
if (!dangerous && hook != null && hook.isDangerous() && hook.whitelist() == null)
return false;
// Get am context
final Context context = getContext();
if (context == null)
return false;
long token = 0;
try {
token = Binder.clearCallingIdentity();
// Get application info
final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid);
// Check if system application
if (!dangerous && appInfo.isSystem())
return false;
// Check if activity manager agrees
if (!XActivityManagerService.canOnDemand())
return false;
// Go ask
Util.log(null, Log.WARN, "On demand " + restriction);
mOndemandSemaphore.acquireUninterruptibly();
try {
// Check if activity manager still agrees
if (!XActivityManagerService.canOnDemand())
return false;
Util.log(null, Log.WARN, "On demanding " + restriction);
// Check if not asked before
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
if (mRestrictionCache.get(key).asked) {
Util.log(null, Log.WARN, "Already asked " + restriction);
return false;
}
}
synchronized (mAskedOnceCache) {
if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) {
Util.log(null, Log.WARN, "Already asked once " + restriction);
return false;
}
}
if (restriction.extra != null && hook != null && hook.whitelist() != null) {
CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra);
CSetting xkey = null;
String xextra = getXExtra(restriction, hook);
if (xextra != null)
xkey = new CSetting(restriction.uid, hook.whitelist(), xextra);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(skey)
|| (xkey != null && mSettingCache.containsKey(xkey))) {
Util.log(null, Log.WARN, "Already asked " + skey);
return false;
}
}
}
final AlertDialogHolder holder = new AlertDialogHolder();
final CountDownLatch latch = new CountDownLatch(1);
// Run dialog in looper
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Dialog
AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo,
dangerous, result, context, latch);
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
alertDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
holder.dialog = alertDialog;
// Progress bar
final ProgressBar mProgress = (ProgressBar) alertDialog
.findViewById(R.id.pbProgress);
mProgress.setMax(cMaxOnDemandDialog * 20);
mProgress.setProgress(cMaxOnDemandDialog * 20);
Runnable rProgress = new Runnable() {
@Override
public void run() {
AlertDialog dialog = holder.dialog;
if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) {
mProgress.incrementProgressBy(-1);
mHandler.postDelayed(this, 50);
}
}
};
mHandler.postDelayed(rProgress, 50);
} catch (Throwable ex) {
Util.bug(null, ex);
latch.countDown();
}
}
});
// Wait for dialog to complete
if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) {
Util.log(null, Log.WARN, "On demand dialog timeout " + restriction);
mHandler.post(new Runnable() {
@Override
public void run() {
AlertDialog dialog = holder.dialog;
if (dialog != null)
dialog.cancel();
}
});
}
} finally {
mOndemandSemaphore.release();
}
} finally {
Binder.restoreCallingIdentity(token);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return true;
}
final class AlertDialogHolder {
public AlertDialog dialog = null;
}
private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook,
ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context,
final CountDownLatch latch) throws NameNotFoundException {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Reference views
View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null);
ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon);
TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName);
TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt);
TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory);
TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction);
TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters);
TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters);
final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory);
final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce);
final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist);
final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra);
// Set values
if ((hook != null && hook.isDangerous()) || appInfo.isSystem())
view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark));
ivAppIcon.setImageDrawable(appInfo.getIcon(context));
- tvUid.setText(Integer.toString(appInfo.getUid()));
+ tvUid.setText(Integer.toString(restriction.uid));
tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName()));
String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow);
tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")");
int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self);
tvCategory.setText(resources.getString(catId));
tvFunction.setText(restriction.methodName);
if (restriction.extra == null)
rowParameters.setVisibility(View.GONE);
else
tvParameters.setText(restriction.extra);
cbCategory.setChecked(mSelectCategory);
cbOnce.setChecked(mSelectOnce);
cbOnce.setText(String.format(resources.getString(R.string.title_once),
PrivacyManager.cRestrictionCacheTimeoutMs / 1000));
if (hook != null && hook.whitelist() != null && restriction.extra != null) {
cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra));
cbWhitelist.setVisibility(View.VISIBLE);
String xextra = getXExtra(restriction, hook);
if (xextra != null) {
cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra));
cbWhitelistExtra.setVisibility(View.VISIBLE);
}
}
// Category, once and whitelist exclude each other
cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbOnce.setChecked(false);
cbWhitelist.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbWhitelist.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbOnce.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbOnce.setChecked(false);
cbWhitelist.setChecked(false);
}
}
});
// Ask
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(resources.getString(R.string.app_name));
alertDialogBuilder.setView(view);
alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher));
alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
if (!cbWhitelist.isChecked() && !cbWhitelistExtra.isChecked()) {
mSelectCategory = cbCategory.isChecked();
mSelectOnce = cbOnce.isChecked();
}
if (cbWhitelist.isChecked())
onDemandWhitelist(restriction, null, result, hook);
else if (cbWhitelistExtra.isChecked())
onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook);
else if (cbOnce.isChecked())
onDemandOnce(restriction, result);
else
onDemandChoice(restriction, cbCategory.isChecked(), true);
latch.countDown();
}
});
alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Allow
result.restricted = false;
if (!cbWhitelist.isChecked() && !cbWhitelistExtra.isChecked()) {
mSelectCategory = cbCategory.isChecked();
mSelectOnce = cbOnce.isChecked();
}
if (cbWhitelist.isChecked())
onDemandWhitelist(restriction, null, result, hook);
else if (cbWhitelistExtra.isChecked())
onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook);
else if (cbOnce.isChecked())
onDemandOnce(restriction, result);
else
onDemandChoice(restriction, cbCategory.isChecked(), false);
latch.countDown();
}
});
return alertDialogBuilder;
}
private String getXExtra(PRestriction restriction, Hook hook) {
if (hook != null)
if (hook.whitelist().equals(Meta.cTypeFilename)) {
String folder = new File(restriction.extra).getParent();
if (!TextUtils.isEmpty(folder))
return folder + File.separatorChar + "*";
} else if (hook.whitelist().equals(Meta.cTypeIPAddress)) {
int semi = restriction.extra.lastIndexOf(':');
String address = (semi >= 0 ? restriction.extra.substring(0, semi) : restriction.extra);
if (Patterns.IP_ADDRESS.matcher(address).matches()) {
int dot = address.lastIndexOf('.');
return address.substring(0, dot + 1) + '*'
+ (semi >= 0 ? restriction.extra.substring(semi) : "");
} else {
int dot = restriction.extra.indexOf('.');
if (dot > 0)
return '*' + restriction.extra.substring(dot);
}
}
return null;
}
private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result,
Hook hook) {
try {
// Set the whitelist
Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction
+ " xextra=" + xextra);
setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra
: xextra), Boolean.toString(!result.restricted)));
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void onDemandOnce(final PRestriction restriction, final PRestriction result) {
Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction);
result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs;
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mAskedOnceCache) {
if (mAskedOnceCache.containsKey(key))
mAskedOnceCache.remove(key);
mAskedOnceCache.put(key, key);
}
}
private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) {
try {
PRestriction result = new PRestriction(restriction);
// Get current category restriction state
boolean prevRestricted = false;
CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
prevRestricted = mRestrictionCache.get(key).restricted;
}
Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/"
+ prevRestricted + " restrict=" + restrict);
if (category || (restrict && restrict != prevRestricted)) {
// Set category restriction
result.methodName = null;
result.restricted = restrict;
result.asked = category;
setRestrictionInternal(result);
// Clear category on change
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) {
result.methodName = md.getName();
result.restricted = (md.isDangerous() && !dangerous ? false : restrict);
result.asked = category;
setRestrictionInternal(result);
}
}
if (!category) {
// Set method restriction
result.methodName = restriction.methodName;
result.restricted = restrict;
result.asked = true;
result.extra = restriction.extra;
setRestrictionInternal(result);
}
// Mark state as changed
setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_CHANGED)));
// Update modification time
setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime,
Long.toString(System.currentTimeMillis())));
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void notifyRestricted(final PRestriction restriction) {
final Context context = getContext();
if (context != null && mHandler != null)
mHandler.post(new Runnable() {
@Override
public void run() {
long token = 0;
try {
token = Binder.clearCallingIdentity();
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Notify user
String text = resources.getString(R.string.msg_restrictedby);
text += " (" + restriction.uid + " " + restriction.restrictionName + "/"
+ restriction.methodName + ")";
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
} catch (NameNotFoundException ex) {
Util.bug(null, ex);
} finally {
Binder.restoreCallingIdentity(token);
}
}
});
}
private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException {
return getSettingBool(uid, "", name, defaultValue);
}
private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException {
String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value;
return Boolean.parseBoolean(value);
}
private void enforcePermission() {
int callingUid = Util.getAppId(Binder.getCallingUid());
if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID)
throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid());
}
private Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
if (am == null)
return null;
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private int getXUid() {
if (mXUid < 0)
try {
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
String self = PrivacyService.class.getPackage().getName();
ApplicationInfo xInfo = pm.getApplicationInfo(self, 0);
mXUid = xInfo.uid;
}
}
} catch (Throwable ignored) {
// The package manager may not be up-to-date yet
}
return mXUid;
}
private File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy"
+ File.separator + "xprivacy.db");
}
private File getDbUsageFile() {
return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy"
+ File.separator + "usage.db");
}
private void setupDatabase() {
try {
File dbFile = getDbFile();
// Create database folder
dbFile.getParentFile().mkdirs();
// Check database folder
if (dbFile.getParentFile().isDirectory())
Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile());
else
Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile());
// Move database from data/xprivacy folder
File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy");
if (folder.exists()) {
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = Util.move(file, target);
Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status);
}
folder.delete();
}
// Move database from data/application folder
folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName());
if (folder.exists()) {
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = Util.move(file, target);
Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status);
}
folder.delete();
}
// Set database file permissions
// Owner: rwx (system)
// Group: rwx (system)
// World: ---
Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID,
Process.SYSTEM_UID);
File[] files = dbFile.getParentFile().listFiles();
if (files != null)
for (File file : files)
if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db"))
Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private SQLiteDatabase getDb() {
synchronized (this) {
// Check current reference
if (mDb != null && !mDb.isOpen()) {
mDb = null;
Util.log(null, Log.ERROR, "Database not open");
}
if (mDb == null)
try {
setupDatabase();
// Create/upgrade database when needed
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
// Check database integrity
if (db.isDatabaseIntegrityOk())
Util.log(null, Log.WARN, "Database integrity ok");
else {
// http://www.sqlite.org/howtocorrupt.html
Util.log(null, Log.ERROR, "Database corrupt");
Cursor cursor = db.rawQuery("PRAGMA integrity_check", null);
try {
while (cursor.moveToNext()) {
String message = cursor.getString(0);
Util.log(null, Log.ERROR, message);
}
} finally {
cursor.close();
}
db.close();
// Backup database file
File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup");
dbBackup.delete();
dbFile.renameTo(dbBackup);
File dbJournal = new File(dbFile.getAbsolutePath() + "-journal");
File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal");
dbJournalBackup.delete();
dbJournal.renameTo(dbJournalBackup);
Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath());
// Create new database
db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
Util.log(null, Log.ERROR, "New, empty database created");
}
// Update migration status
if (db.getVersion() > 1) {
Util.log(null, Log.WARN, "Updating migration status");
mLock.writeLock().lock();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", 0);
if (db.getVersion() > 9)
values.put("type", "");
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
// Upgrade database if needed
if (db.needUpgrade(1)) {
Util.log(null, Log.WARN, "Creating database");
mLock.writeLock().lock();
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(2)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
// Old migrated indication
db.setVersion(2);
}
if (db.needUpgrade(3)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM usage WHERE method=''");
db.setVersion(3);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(4)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value IS NULL");
db.setVersion(4);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(5)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value = ''");
db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'");
db.setVersion(5);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(6)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'");
db.setVersion(6);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(7)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT");
db.setVersion(7);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(8)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DROP INDEX idx_usage");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)");
db.setVersion(8);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(9)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DROP TABLE usage");
db.setVersion(9);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(10)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT");
db.execSQL("DROP INDEX idx_setting");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)");
db.execSQL("UPDATE setting SET type=''");
db.setVersion(10);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(11)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
List<PSetting> listSetting = new ArrayList<PSetting>();
Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null,
null, null, null, null);
if (cursor != null)
try {
while (cursor.moveToNext()) {
int uid = cursor.getInt(0);
String name = cursor.getString(1);
String value = cursor.getString(2);
if (name.startsWith("Account.") || name.startsWith("Application.")
|| name.startsWith("Contact.") || name.startsWith("Template.")) {
int dot = name.indexOf('.');
String type = name.substring(0, dot);
listSetting
.add(new PSetting(uid, type, name.substring(dot + 1), value));
listSetting.add(new PSetting(uid, "", name, null));
} else if (name.startsWith("Whitelist.")) {
String[] component = name.split("\\.");
listSetting.add(new PSetting(uid, component[1], name.replace(
component[0] + "." + component[1] + ".", ""), value));
listSetting.add(new PSetting(uid, "", name, null));
}
}
} finally {
cursor.close();
}
for (PSetting setting : listSetting) {
Util.log(null, Log.WARN, "Converting " + setting);
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND type=? AND name=?",
new String[] { Integer.toString(setting.uid), setting.type,
setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("type", setting.type);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values,
SQLiteDatabase.CONFLICT_REPLACE);
}
}
db.setVersion(11);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
Util.log(null, Log.WARN, "Running VACUUM");
mLock.writeLock().lock();
try {
db.execSQL("VACUUM");
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
mLock.writeLock().unlock();
}
Util.log(null, Log.WARN, "Database version=" + db.getVersion());
mDb = db;
} catch (Throwable ex) {
mDb = null; // retry
Util.bug(null, ex);
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(
"/cache/xprivacy.log", true));
outputStreamWriter.write(ex.toString());
outputStreamWriter.write("\n");
outputStreamWriter.write(Log.getStackTraceString(ex));
outputStreamWriter.write("\n");
outputStreamWriter.close();
} catch (Throwable exex) {
Util.bug(null, exex);
}
}
return mDb;
}
}
private SQLiteDatabase getDbUsage() {
synchronized (this) {
// Check current reference
if (mDbUsage != null && !mDbUsage.isOpen()) {
mDbUsage = null;
Util.log(null, Log.ERROR, "Usage database not open");
}
if (mDbUsage == null)
try {
// Create/upgrade database when needed
File dbUsageFile = getDbUsageFile();
SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null);
// Check database integrity
if (dbUsage.isDatabaseIntegrityOk())
Util.log(null, Log.WARN, "Usage database integrity ok");
else {
dbUsage.close();
dbUsageFile.delete();
new File(dbUsageFile + "-journal").delete();
dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null);
Util.log(null, Log.ERROR, "Deleted corrupt usage data database");
}
// Upgrade database if needed
if (dbUsage.needUpgrade(1)) {
Util.log(null, Log.WARN, "Creating usage database");
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)");
dbUsage.setVersion(1);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
}
Util.log(null, Log.WARN, "Running VACUUM");
mLockUsage.writeLock().lock();
try {
dbUsage.execSQL("VACUUM");
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
mLockUsage.writeLock().unlock();
}
Util.log(null, Log.WARN, "Changing to asynchronous mode");
try {
dbUsage.rawQuery("PRAGMA synchronous=OFF", null);
} catch (Throwable ex) {
Util.bug(null, ex);
}
Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion());
mDbUsage = dbUsage;
} catch (Throwable ex) {
mDbUsage = null; // retry
Util.bug(null, ex);
}
return mDbUsage;
}
}
};
}
| true | true | public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException {
List<PRestriction> result = new ArrayList<PRestriction>();
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
mLockUsage.readLock().lock();
dbUsage.beginTransaction();
try {
Cursor cursor;
if (uid == 0) {
if ("".equals(restrictionName))
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, null, new String[] {}, null, null,
"time DESC LIMIT " + cMaxUsageData);
else
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName },
null, null, "time DESC LIMIT " + cMaxUsageData);
} else {
if ("".equals(restrictionName))
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) },
null, null, "time DESC LIMIT " + cMaxUsageData);
else
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "uid=? AND restriction=?",
new String[] { Integer.toString(uid), restrictionName }, null, null,
"time DESC LIMIT " + cMaxUsageData);
}
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
PRestriction data = new PRestriction();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
data.extra = cursor.getString(5);
result.add(data);
}
} finally {
cursor.close();
}
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
if (uid == 0)
dbUsage.delete(cTableUsage, null, new String[] {});
else
dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(PSetting setting) throws RemoteException {
try {
enforcePermission();
setSettingInternal(setting);
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
private void setSettingInternal(PSetting setting) throws RemoteException {
try {
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND type=? AND name=?",
new String[] { Integer.toString(setting.uid), setting.type, setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("type", setting.type);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Update cache
if (mUseCache) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
key.setValue(setting.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
if (setting.value != null)
mSettingCache.put(key, key);
}
}
// Clear restrictions for white list
if (Meta.isWhitelist(setting.type))
for (String restrictionName : PrivacyManager.getRestrictions())
for (Hook hook : PrivacyManager.getHooks(restrictionName))
if (setting.type.equals(hook.whitelist())) {
PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(),
hook.getName());
Util.log(null, Log.WARN, "Clearing cache for " + restriction);
synchronized (mRestrictionCache) {
for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet()))
if (key.isSameMethod(restriction)) {
Util.log(null, Log.WARN, "Removing " + key);
mRestrictionCache.remove(key);
}
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void setSettingList(List<PSetting> listSetting) throws RemoteException {
enforcePermission();
for (PSetting setting : listSetting)
setSettingInternal(setting);
}
@Override
@SuppressLint("DefaultLocale")
public PSetting getSetting(PSetting setting) throws RemoteException {
PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value);
try {
// No permissions enforced
// Check cache
if (mUseCache && setting.value != null) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key)) {
result.value = mSettingCache.get(key).getValue();
return result;
}
}
}
// No persmissions required
SQLiteDatabase db = getDb();
if (db == null)
return result;
// Fallback
if (!PrivacyManager.cSettingMigrated.equals(setting.name)
&& !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (setting.uid == 0)
result.value = PrivacyProvider.getSettingFallback(setting.name, null, false);
if (result.value == null) {
result.value = PrivacyProvider.getSettingFallback(
String.format("%s.%d", setting.name, setting.uid), setting.value, false);
return result;
}
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
mLock.readLock().lock();
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, setting.uid);
stmtGetSetting.bindString(2, setting.type);
stmtGetSetting.bindString(3, setting.name);
String value = stmtGetSetting.simpleQueryForString();
if (value != null)
result.value = value;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
// Add to cache
if (mUseCache && result.value != null) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
key.setValue(result.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return result;
}
@Override
public List<PSetting> getSettingList(int uid) throws RemoteException {
List<PSetting> listSetting = new ArrayList<PSetting>();
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return listSetting;
mLock.readLock().lock();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor
.getString(2)));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return listSetting;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear cache
if (mUseCache)
synchronized (mSettingCache) {
mSettingCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void clear() throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
SQLiteDatabase dbUsage = getDbUsage();
if (db == null || dbUsage == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM " + cTableRestriction);
db.execSQL("DELETE FROM " + cTableSetting);
Util.log(null, Log.WARN, "Database cleared");
// Reset migrated
ContentValues values = new ContentValues();
values.put("uid", 0);
values.put("type", "");
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear caches
if (mUseCache) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingCache) {
mSettingCache.clear();
}
}
synchronized (mAskedOnceCache) {
mAskedOnceCache.clear();
}
Util.log(null, Log.WARN, "Caches cleared");
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
dbUsage.execSQL("DELETE FROM " + cTableUsage);
Util.log(null, Log.WARN, "Usage database cleared");
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void dump(int uid) throws RemoteException {
if (uid == 0) {
} else {
synchronized (mRestrictionCache) {
for (CRestriction crestriction : mRestrictionCache.keySet())
if (crestriction.getUid() == uid)
Util.log(null, Log.WARN, "Dump crestriction=" + crestriction);
}
synchronized (mAskedOnceCache) {
for (CRestriction crestriction : mAskedOnceCache.keySet())
if (crestriction.getUid() == uid && !crestriction.isExpired())
Util.log(null, Log.WARN, "Dump asked=" + crestriction);
}
synchronized (mSettingCache) {
for (CSetting csetting : mSettingCache.keySet())
if (csetting.getUid() == uid)
Util.log(null, Log.WARN, "Dump csetting=" + csetting);
}
}
}
// Helper methods
private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) {
try {
// Without handler nothing can be done
if (mHandler == null)
return false;
// Check for exceptions
if (hook != null && !hook.canOnDemand())
return false;
// Check if enabled
if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true))
return false;
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false))
return false;
// Skip dangerous methods
final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
if (!dangerous && hook != null && hook.isDangerous() && hook.whitelist() == null)
return false;
// Get am context
final Context context = getContext();
if (context == null)
return false;
long token = 0;
try {
token = Binder.clearCallingIdentity();
// Get application info
final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid);
// Check if system application
if (!dangerous && appInfo.isSystem())
return false;
// Check if activity manager agrees
if (!XActivityManagerService.canOnDemand())
return false;
// Go ask
Util.log(null, Log.WARN, "On demand " + restriction);
mOndemandSemaphore.acquireUninterruptibly();
try {
// Check if activity manager still agrees
if (!XActivityManagerService.canOnDemand())
return false;
Util.log(null, Log.WARN, "On demanding " + restriction);
// Check if not asked before
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
if (mRestrictionCache.get(key).asked) {
Util.log(null, Log.WARN, "Already asked " + restriction);
return false;
}
}
synchronized (mAskedOnceCache) {
if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) {
Util.log(null, Log.WARN, "Already asked once " + restriction);
return false;
}
}
if (restriction.extra != null && hook != null && hook.whitelist() != null) {
CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra);
CSetting xkey = null;
String xextra = getXExtra(restriction, hook);
if (xextra != null)
xkey = new CSetting(restriction.uid, hook.whitelist(), xextra);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(skey)
|| (xkey != null && mSettingCache.containsKey(xkey))) {
Util.log(null, Log.WARN, "Already asked " + skey);
return false;
}
}
}
final AlertDialogHolder holder = new AlertDialogHolder();
final CountDownLatch latch = new CountDownLatch(1);
// Run dialog in looper
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Dialog
AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo,
dangerous, result, context, latch);
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
alertDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
holder.dialog = alertDialog;
// Progress bar
final ProgressBar mProgress = (ProgressBar) alertDialog
.findViewById(R.id.pbProgress);
mProgress.setMax(cMaxOnDemandDialog * 20);
mProgress.setProgress(cMaxOnDemandDialog * 20);
Runnable rProgress = new Runnable() {
@Override
public void run() {
AlertDialog dialog = holder.dialog;
if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) {
mProgress.incrementProgressBy(-1);
mHandler.postDelayed(this, 50);
}
}
};
mHandler.postDelayed(rProgress, 50);
} catch (Throwable ex) {
Util.bug(null, ex);
latch.countDown();
}
}
});
// Wait for dialog to complete
if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) {
Util.log(null, Log.WARN, "On demand dialog timeout " + restriction);
mHandler.post(new Runnable() {
@Override
public void run() {
AlertDialog dialog = holder.dialog;
if (dialog != null)
dialog.cancel();
}
});
}
} finally {
mOndemandSemaphore.release();
}
} finally {
Binder.restoreCallingIdentity(token);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return true;
}
final class AlertDialogHolder {
public AlertDialog dialog = null;
}
private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook,
ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context,
final CountDownLatch latch) throws NameNotFoundException {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Reference views
View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null);
ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon);
TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName);
TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt);
TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory);
TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction);
TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters);
TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters);
final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory);
final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce);
final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist);
final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra);
// Set values
if ((hook != null && hook.isDangerous()) || appInfo.isSystem())
view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark));
ivAppIcon.setImageDrawable(appInfo.getIcon(context));
tvUid.setText(Integer.toString(appInfo.getUid()));
tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName()));
String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow);
tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")");
int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self);
tvCategory.setText(resources.getString(catId));
tvFunction.setText(restriction.methodName);
if (restriction.extra == null)
rowParameters.setVisibility(View.GONE);
else
tvParameters.setText(restriction.extra);
cbCategory.setChecked(mSelectCategory);
cbOnce.setChecked(mSelectOnce);
cbOnce.setText(String.format(resources.getString(R.string.title_once),
PrivacyManager.cRestrictionCacheTimeoutMs / 1000));
if (hook != null && hook.whitelist() != null && restriction.extra != null) {
cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra));
cbWhitelist.setVisibility(View.VISIBLE);
String xextra = getXExtra(restriction, hook);
if (xextra != null) {
cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra));
cbWhitelistExtra.setVisibility(View.VISIBLE);
}
}
// Category, once and whitelist exclude each other
cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbOnce.setChecked(false);
cbWhitelist.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbWhitelist.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbOnce.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbOnce.setChecked(false);
cbWhitelist.setChecked(false);
}
}
});
// Ask
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(resources.getString(R.string.app_name));
alertDialogBuilder.setView(view);
alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher));
alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
if (!cbWhitelist.isChecked() && !cbWhitelistExtra.isChecked()) {
mSelectCategory = cbCategory.isChecked();
mSelectOnce = cbOnce.isChecked();
}
if (cbWhitelist.isChecked())
onDemandWhitelist(restriction, null, result, hook);
else if (cbWhitelistExtra.isChecked())
onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook);
else if (cbOnce.isChecked())
onDemandOnce(restriction, result);
else
onDemandChoice(restriction, cbCategory.isChecked(), true);
latch.countDown();
}
});
alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Allow
result.restricted = false;
if (!cbWhitelist.isChecked() && !cbWhitelistExtra.isChecked()) {
mSelectCategory = cbCategory.isChecked();
mSelectOnce = cbOnce.isChecked();
}
if (cbWhitelist.isChecked())
onDemandWhitelist(restriction, null, result, hook);
else if (cbWhitelistExtra.isChecked())
onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook);
else if (cbOnce.isChecked())
onDemandOnce(restriction, result);
else
onDemandChoice(restriction, cbCategory.isChecked(), false);
latch.countDown();
}
});
return alertDialogBuilder;
}
private String getXExtra(PRestriction restriction, Hook hook) {
if (hook != null)
if (hook.whitelist().equals(Meta.cTypeFilename)) {
String folder = new File(restriction.extra).getParent();
if (!TextUtils.isEmpty(folder))
return folder + File.separatorChar + "*";
} else if (hook.whitelist().equals(Meta.cTypeIPAddress)) {
int semi = restriction.extra.lastIndexOf(':');
String address = (semi >= 0 ? restriction.extra.substring(0, semi) : restriction.extra);
if (Patterns.IP_ADDRESS.matcher(address).matches()) {
int dot = address.lastIndexOf('.');
return address.substring(0, dot + 1) + '*'
+ (semi >= 0 ? restriction.extra.substring(semi) : "");
} else {
int dot = restriction.extra.indexOf('.');
if (dot > 0)
return '*' + restriction.extra.substring(dot);
}
}
return null;
}
private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result,
Hook hook) {
try {
// Set the whitelist
Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction
+ " xextra=" + xextra);
setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra
: xextra), Boolean.toString(!result.restricted)));
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void onDemandOnce(final PRestriction restriction, final PRestriction result) {
Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction);
result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs;
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mAskedOnceCache) {
if (mAskedOnceCache.containsKey(key))
mAskedOnceCache.remove(key);
mAskedOnceCache.put(key, key);
}
}
private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) {
try {
PRestriction result = new PRestriction(restriction);
// Get current category restriction state
boolean prevRestricted = false;
CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
prevRestricted = mRestrictionCache.get(key).restricted;
}
Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/"
+ prevRestricted + " restrict=" + restrict);
if (category || (restrict && restrict != prevRestricted)) {
// Set category restriction
result.methodName = null;
result.restricted = restrict;
result.asked = category;
setRestrictionInternal(result);
// Clear category on change
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) {
result.methodName = md.getName();
result.restricted = (md.isDangerous() && !dangerous ? false : restrict);
result.asked = category;
setRestrictionInternal(result);
}
}
if (!category) {
// Set method restriction
result.methodName = restriction.methodName;
result.restricted = restrict;
result.asked = true;
result.extra = restriction.extra;
setRestrictionInternal(result);
}
// Mark state as changed
setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_CHANGED)));
// Update modification time
setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime,
Long.toString(System.currentTimeMillis())));
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void notifyRestricted(final PRestriction restriction) {
final Context context = getContext();
if (context != null && mHandler != null)
mHandler.post(new Runnable() {
@Override
public void run() {
long token = 0;
try {
token = Binder.clearCallingIdentity();
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Notify user
String text = resources.getString(R.string.msg_restrictedby);
text += " (" + restriction.uid + " " + restriction.restrictionName + "/"
+ restriction.methodName + ")";
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
} catch (NameNotFoundException ex) {
Util.bug(null, ex);
} finally {
Binder.restoreCallingIdentity(token);
}
}
});
}
private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException {
return getSettingBool(uid, "", name, defaultValue);
}
private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException {
String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value;
return Boolean.parseBoolean(value);
}
private void enforcePermission() {
int callingUid = Util.getAppId(Binder.getCallingUid());
if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID)
throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid());
}
private Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
if (am == null)
return null;
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private int getXUid() {
if (mXUid < 0)
try {
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
String self = PrivacyService.class.getPackage().getName();
ApplicationInfo xInfo = pm.getApplicationInfo(self, 0);
mXUid = xInfo.uid;
}
}
} catch (Throwable ignored) {
// The package manager may not be up-to-date yet
}
return mXUid;
}
private File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy"
+ File.separator + "xprivacy.db");
}
private File getDbUsageFile() {
return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy"
+ File.separator + "usage.db");
}
private void setupDatabase() {
try {
File dbFile = getDbFile();
// Create database folder
dbFile.getParentFile().mkdirs();
// Check database folder
if (dbFile.getParentFile().isDirectory())
Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile());
else
Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile());
// Move database from data/xprivacy folder
File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy");
if (folder.exists()) {
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = Util.move(file, target);
Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status);
}
folder.delete();
}
// Move database from data/application folder
folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName());
if (folder.exists()) {
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = Util.move(file, target);
Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status);
}
folder.delete();
}
// Set database file permissions
// Owner: rwx (system)
// Group: rwx (system)
// World: ---
Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID,
Process.SYSTEM_UID);
File[] files = dbFile.getParentFile().listFiles();
if (files != null)
for (File file : files)
if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db"))
Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private SQLiteDatabase getDb() {
synchronized (this) {
// Check current reference
if (mDb != null && !mDb.isOpen()) {
mDb = null;
Util.log(null, Log.ERROR, "Database not open");
}
if (mDb == null)
try {
setupDatabase();
// Create/upgrade database when needed
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
// Check database integrity
if (db.isDatabaseIntegrityOk())
Util.log(null, Log.WARN, "Database integrity ok");
else {
// http://www.sqlite.org/howtocorrupt.html
Util.log(null, Log.ERROR, "Database corrupt");
Cursor cursor = db.rawQuery("PRAGMA integrity_check", null);
try {
while (cursor.moveToNext()) {
String message = cursor.getString(0);
Util.log(null, Log.ERROR, message);
}
} finally {
cursor.close();
}
db.close();
// Backup database file
File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup");
dbBackup.delete();
dbFile.renameTo(dbBackup);
File dbJournal = new File(dbFile.getAbsolutePath() + "-journal");
File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal");
dbJournalBackup.delete();
dbJournal.renameTo(dbJournalBackup);
Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath());
// Create new database
db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
Util.log(null, Log.ERROR, "New, empty database created");
}
// Update migration status
if (db.getVersion() > 1) {
Util.log(null, Log.WARN, "Updating migration status");
mLock.writeLock().lock();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", 0);
if (db.getVersion() > 9)
values.put("type", "");
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
// Upgrade database if needed
if (db.needUpgrade(1)) {
Util.log(null, Log.WARN, "Creating database");
mLock.writeLock().lock();
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(2)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
// Old migrated indication
db.setVersion(2);
}
if (db.needUpgrade(3)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM usage WHERE method=''");
db.setVersion(3);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(4)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value IS NULL");
db.setVersion(4);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(5)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value = ''");
db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'");
db.setVersion(5);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(6)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'");
db.setVersion(6);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(7)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT");
db.setVersion(7);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(8)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DROP INDEX idx_usage");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)");
db.setVersion(8);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(9)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DROP TABLE usage");
db.setVersion(9);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(10)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT");
db.execSQL("DROP INDEX idx_setting");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)");
db.execSQL("UPDATE setting SET type=''");
db.setVersion(10);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(11)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
List<PSetting> listSetting = new ArrayList<PSetting>();
Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null,
null, null, null, null);
if (cursor != null)
try {
while (cursor.moveToNext()) {
int uid = cursor.getInt(0);
String name = cursor.getString(1);
String value = cursor.getString(2);
if (name.startsWith("Account.") || name.startsWith("Application.")
|| name.startsWith("Contact.") || name.startsWith("Template.")) {
int dot = name.indexOf('.');
String type = name.substring(0, dot);
listSetting
.add(new PSetting(uid, type, name.substring(dot + 1), value));
listSetting.add(new PSetting(uid, "", name, null));
} else if (name.startsWith("Whitelist.")) {
String[] component = name.split("\\.");
listSetting.add(new PSetting(uid, component[1], name.replace(
component[0] + "." + component[1] + ".", ""), value));
listSetting.add(new PSetting(uid, "", name, null));
}
}
} finally {
cursor.close();
}
for (PSetting setting : listSetting) {
Util.log(null, Log.WARN, "Converting " + setting);
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND type=? AND name=?",
new String[] { Integer.toString(setting.uid), setting.type,
setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("type", setting.type);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values,
SQLiteDatabase.CONFLICT_REPLACE);
}
}
db.setVersion(11);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
Util.log(null, Log.WARN, "Running VACUUM");
mLock.writeLock().lock();
try {
db.execSQL("VACUUM");
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
mLock.writeLock().unlock();
}
Util.log(null, Log.WARN, "Database version=" + db.getVersion());
mDb = db;
} catch (Throwable ex) {
mDb = null; // retry
Util.bug(null, ex);
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(
"/cache/xprivacy.log", true));
outputStreamWriter.write(ex.toString());
outputStreamWriter.write("\n");
outputStreamWriter.write(Log.getStackTraceString(ex));
outputStreamWriter.write("\n");
outputStreamWriter.close();
} catch (Throwable exex) {
Util.bug(null, exex);
}
}
return mDb;
}
}
private SQLiteDatabase getDbUsage() {
synchronized (this) {
// Check current reference
if (mDbUsage != null && !mDbUsage.isOpen()) {
mDbUsage = null;
Util.log(null, Log.ERROR, "Usage database not open");
}
if (mDbUsage == null)
try {
// Create/upgrade database when needed
File dbUsageFile = getDbUsageFile();
SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null);
// Check database integrity
if (dbUsage.isDatabaseIntegrityOk())
Util.log(null, Log.WARN, "Usage database integrity ok");
else {
dbUsage.close();
dbUsageFile.delete();
new File(dbUsageFile + "-journal").delete();
dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null);
Util.log(null, Log.ERROR, "Deleted corrupt usage data database");
}
// Upgrade database if needed
if (dbUsage.needUpgrade(1)) {
Util.log(null, Log.WARN, "Creating usage database");
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)");
dbUsage.setVersion(1);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
}
Util.log(null, Log.WARN, "Running VACUUM");
mLockUsage.writeLock().lock();
try {
dbUsage.execSQL("VACUUM");
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
mLockUsage.writeLock().unlock();
}
Util.log(null, Log.WARN, "Changing to asynchronous mode");
try {
dbUsage.rawQuery("PRAGMA synchronous=OFF", null);
} catch (Throwable ex) {
Util.bug(null, ex);
}
Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion());
mDbUsage = dbUsage;
} catch (Throwable ex) {
mDbUsage = null; // retry
Util.bug(null, ex);
}
return mDbUsage;
}
}
};
}
| public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException {
List<PRestriction> result = new ArrayList<PRestriction>();
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
mLockUsage.readLock().lock();
dbUsage.beginTransaction();
try {
Cursor cursor;
if (uid == 0) {
if ("".equals(restrictionName))
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, null, new String[] {}, null, null,
"time DESC LIMIT " + cMaxUsageData);
else
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName },
null, null, "time DESC LIMIT " + cMaxUsageData);
} else {
if ("".equals(restrictionName))
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) },
null, null, "time DESC LIMIT " + cMaxUsageData);
else
cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method",
"restricted", "time", "extra" }, "uid=? AND restriction=?",
new String[] { Integer.toString(uid), restrictionName }, null, null,
"time DESC LIMIT " + cMaxUsageData);
}
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (usage data)");
else
try {
while (cursor.moveToNext()) {
PRestriction data = new PRestriction();
data.uid = cursor.getInt(0);
data.restrictionName = cursor.getString(1);
data.methodName = cursor.getString(2);
data.restricted = (cursor.getInt(3) > 0);
data.time = cursor.getLong(4);
data.extra = cursor.getString(5);
result.add(data);
}
} finally {
cursor.close();
}
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return result;
}
@Override
public void deleteUsage(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase dbUsage = getDbUsage();
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
if (uid == 0)
dbUsage.delete(cTableUsage, null, new String[] {});
else
dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Usage data deleted uid=" + uid);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
// Settings
@Override
public void setSetting(PSetting setting) throws RemoteException {
try {
enforcePermission();
setSettingInternal(setting);
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
private void setSettingInternal(PSetting setting) throws RemoteException {
try {
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND type=? AND name=?",
new String[] { Integer.toString(setting.uid), setting.type, setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("type", setting.type);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Update cache
if (mUseCache) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
key.setValue(setting.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
if (setting.value != null)
mSettingCache.put(key, key);
}
}
// Clear restrictions for white list
if (Meta.isWhitelist(setting.type))
for (String restrictionName : PrivacyManager.getRestrictions())
for (Hook hook : PrivacyManager.getHooks(restrictionName))
if (setting.type.equals(hook.whitelist())) {
PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(),
hook.getName());
Util.log(null, Log.WARN, "Clearing cache for " + restriction);
synchronized (mRestrictionCache) {
for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet()))
if (key.isSameMethod(restriction)) {
Util.log(null, Log.WARN, "Removing " + key);
mRestrictionCache.remove(key);
}
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void setSettingList(List<PSetting> listSetting) throws RemoteException {
enforcePermission();
for (PSetting setting : listSetting)
setSettingInternal(setting);
}
@Override
@SuppressLint("DefaultLocale")
public PSetting getSetting(PSetting setting) throws RemoteException {
PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value);
try {
// No permissions enforced
// Check cache
if (mUseCache && setting.value != null) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key)) {
result.value = mSettingCache.get(key).getValue();
return result;
}
}
}
// No persmissions required
SQLiteDatabase db = getDb();
if (db == null)
return result;
// Fallback
if (!PrivacyManager.cSettingMigrated.equals(setting.name)
&& !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) {
if (setting.uid == 0)
result.value = PrivacyProvider.getSettingFallback(setting.name, null, false);
if (result.value == null) {
result.value = PrivacyProvider.getSettingFallback(
String.format("%s.%d", setting.name, setting.uid), setting.value, false);
return result;
}
}
// Precompile statement when needed
if (stmtGetSetting == null) {
String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?";
stmtGetSetting = db.compileStatement(sql);
}
// Execute statement
mLock.readLock().lock();
db.beginTransaction();
try {
try {
synchronized (stmtGetSetting) {
stmtGetSetting.clearBindings();
stmtGetSetting.bindLong(1, setting.uid);
stmtGetSetting.bindString(2, setting.type);
stmtGetSetting.bindString(3, setting.name);
String value = stmtGetSetting.simpleQueryForString();
if (value != null)
result.value = value;
}
} catch (SQLiteDoneException ignored) {
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
// Add to cache
if (mUseCache && result.value != null) {
CSetting key = new CSetting(setting.uid, setting.type, setting.name);
key.setValue(result.value);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(key))
mSettingCache.remove(key);
mSettingCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return result;
}
@Override
public List<PSetting> getSettingList(int uid) throws RemoteException {
List<PSetting> listSetting = new ArrayList<PSetting>();
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return listSetting;
mLock.readLock().lock();
db.beginTransaction();
try {
Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?",
new String[] { Integer.toString(uid) }, null, null, null);
if (cursor == null)
Util.log(null, Log.WARN, "Database cursor null (settings)");
else
try {
while (cursor.moveToNext())
listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor
.getString(2)));
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.readLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
return listSetting;
}
@Override
public void deleteSettings(int uid) throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
if (db == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) });
Util.log(null, Log.WARN, "Settings deleted uid=" + uid);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear cache
if (mUseCache)
synchronized (mSettingCache) {
mSettingCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void clear() throws RemoteException {
try {
enforcePermission();
SQLiteDatabase db = getDb();
SQLiteDatabase dbUsage = getDbUsage();
if (db == null || dbUsage == null)
return;
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM " + cTableRestriction);
db.execSQL("DELETE FROM " + cTableSetting);
Util.log(null, Log.WARN, "Database cleared");
// Reset migrated
ContentValues values = new ContentValues();
values.put("uid", 0);
values.put("type", "");
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
// Clear caches
if (mUseCache) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingCache) {
mSettingCache.clear();
}
}
synchronized (mAskedOnceCache) {
mAskedOnceCache.clear();
}
Util.log(null, Log.WARN, "Caches cleared");
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
dbUsage.execSQL("DELETE FROM " + cTableUsage);
Util.log(null, Log.WARN, "Usage database cleared");
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (Throwable ex) {
Util.bug(null, ex);
throw new RemoteException(ex.toString());
}
}
@Override
public void dump(int uid) throws RemoteException {
if (uid == 0) {
} else {
synchronized (mRestrictionCache) {
for (CRestriction crestriction : mRestrictionCache.keySet())
if (crestriction.getUid() == uid)
Util.log(null, Log.WARN, "Dump crestriction=" + crestriction);
}
synchronized (mAskedOnceCache) {
for (CRestriction crestriction : mAskedOnceCache.keySet())
if (crestriction.getUid() == uid && !crestriction.isExpired())
Util.log(null, Log.WARN, "Dump asked=" + crestriction);
}
synchronized (mSettingCache) {
for (CSetting csetting : mSettingCache.keySet())
if (csetting.getUid() == uid)
Util.log(null, Log.WARN, "Dump csetting=" + csetting);
}
}
}
// Helper methods
private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) {
try {
// Without handler nothing can be done
if (mHandler == null)
return false;
// Check for exceptions
if (hook != null && !hook.canOnDemand())
return false;
// Check if enabled
if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true))
return false;
if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false))
return false;
// Skip dangerous methods
final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
if (!dangerous && hook != null && hook.isDangerous() && hook.whitelist() == null)
return false;
// Get am context
final Context context = getContext();
if (context == null)
return false;
long token = 0;
try {
token = Binder.clearCallingIdentity();
// Get application info
final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid);
// Check if system application
if (!dangerous && appInfo.isSystem())
return false;
// Check if activity manager agrees
if (!XActivityManagerService.canOnDemand())
return false;
// Go ask
Util.log(null, Log.WARN, "On demand " + restriction);
mOndemandSemaphore.acquireUninterruptibly();
try {
// Check if activity manager still agrees
if (!XActivityManagerService.canOnDemand())
return false;
Util.log(null, Log.WARN, "On demanding " + restriction);
// Check if not asked before
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
if (mRestrictionCache.get(key).asked) {
Util.log(null, Log.WARN, "Already asked " + restriction);
return false;
}
}
synchronized (mAskedOnceCache) {
if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) {
Util.log(null, Log.WARN, "Already asked once " + restriction);
return false;
}
}
if (restriction.extra != null && hook != null && hook.whitelist() != null) {
CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra);
CSetting xkey = null;
String xextra = getXExtra(restriction, hook);
if (xextra != null)
xkey = new CSetting(restriction.uid, hook.whitelist(), xextra);
synchronized (mSettingCache) {
if (mSettingCache.containsKey(skey)
|| (xkey != null && mSettingCache.containsKey(xkey))) {
Util.log(null, Log.WARN, "Already asked " + skey);
return false;
}
}
}
final AlertDialogHolder holder = new AlertDialogHolder();
final CountDownLatch latch = new CountDownLatch(1);
// Run dialog in looper
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Dialog
AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo,
dangerous, result, context, latch);
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
alertDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
holder.dialog = alertDialog;
// Progress bar
final ProgressBar mProgress = (ProgressBar) alertDialog
.findViewById(R.id.pbProgress);
mProgress.setMax(cMaxOnDemandDialog * 20);
mProgress.setProgress(cMaxOnDemandDialog * 20);
Runnable rProgress = new Runnable() {
@Override
public void run() {
AlertDialog dialog = holder.dialog;
if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) {
mProgress.incrementProgressBy(-1);
mHandler.postDelayed(this, 50);
}
}
};
mHandler.postDelayed(rProgress, 50);
} catch (Throwable ex) {
Util.bug(null, ex);
latch.countDown();
}
}
});
// Wait for dialog to complete
if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) {
Util.log(null, Log.WARN, "On demand dialog timeout " + restriction);
mHandler.post(new Runnable() {
@Override
public void run() {
AlertDialog dialog = holder.dialog;
if (dialog != null)
dialog.cancel();
}
});
}
} finally {
mOndemandSemaphore.release();
}
} finally {
Binder.restoreCallingIdentity(token);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return true;
}
final class AlertDialogHolder {
public AlertDialog dialog = null;
}
private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook,
ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context,
final CountDownLatch latch) throws NameNotFoundException {
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Reference views
View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null);
ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon);
TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName);
TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt);
TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory);
TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction);
TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters);
TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters);
final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory);
final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce);
final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist);
final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra);
// Set values
if ((hook != null && hook.isDangerous()) || appInfo.isSystem())
view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark));
ivAppIcon.setImageDrawable(appInfo.getIcon(context));
tvUid.setText(Integer.toString(restriction.uid));
tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName()));
String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow);
tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")");
int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self);
tvCategory.setText(resources.getString(catId));
tvFunction.setText(restriction.methodName);
if (restriction.extra == null)
rowParameters.setVisibility(View.GONE);
else
tvParameters.setText(restriction.extra);
cbCategory.setChecked(mSelectCategory);
cbOnce.setChecked(mSelectOnce);
cbOnce.setText(String.format(resources.getString(R.string.title_once),
PrivacyManager.cRestrictionCacheTimeoutMs / 1000));
if (hook != null && hook.whitelist() != null && restriction.extra != null) {
cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra));
cbWhitelist.setVisibility(View.VISIBLE);
String xextra = getXExtra(restriction, hook);
if (xextra != null) {
cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra));
cbWhitelistExtra.setVisibility(View.VISIBLE);
}
}
// Category, once and whitelist exclude each other
cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbOnce.setChecked(false);
cbWhitelist.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbWhitelist.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbOnce.setChecked(false);
cbWhitelistExtra.setChecked(false);
}
}
});
cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cbCategory.setChecked(false);
cbOnce.setChecked(false);
cbWhitelist.setChecked(false);
}
}
});
// Ask
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(resources.getString(R.string.app_name));
alertDialogBuilder.setView(view);
alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher));
alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Deny
result.restricted = true;
if (!cbWhitelist.isChecked() && !cbWhitelistExtra.isChecked()) {
mSelectCategory = cbCategory.isChecked();
mSelectOnce = cbOnce.isChecked();
}
if (cbWhitelist.isChecked())
onDemandWhitelist(restriction, null, result, hook);
else if (cbWhitelistExtra.isChecked())
onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook);
else if (cbOnce.isChecked())
onDemandOnce(restriction, result);
else
onDemandChoice(restriction, cbCategory.isChecked(), true);
latch.countDown();
}
});
alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Allow
result.restricted = false;
if (!cbWhitelist.isChecked() && !cbWhitelistExtra.isChecked()) {
mSelectCategory = cbCategory.isChecked();
mSelectOnce = cbOnce.isChecked();
}
if (cbWhitelist.isChecked())
onDemandWhitelist(restriction, null, result, hook);
else if (cbWhitelistExtra.isChecked())
onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook);
else if (cbOnce.isChecked())
onDemandOnce(restriction, result);
else
onDemandChoice(restriction, cbCategory.isChecked(), false);
latch.countDown();
}
});
return alertDialogBuilder;
}
private String getXExtra(PRestriction restriction, Hook hook) {
if (hook != null)
if (hook.whitelist().equals(Meta.cTypeFilename)) {
String folder = new File(restriction.extra).getParent();
if (!TextUtils.isEmpty(folder))
return folder + File.separatorChar + "*";
} else if (hook.whitelist().equals(Meta.cTypeIPAddress)) {
int semi = restriction.extra.lastIndexOf(':');
String address = (semi >= 0 ? restriction.extra.substring(0, semi) : restriction.extra);
if (Patterns.IP_ADDRESS.matcher(address).matches()) {
int dot = address.lastIndexOf('.');
return address.substring(0, dot + 1) + '*'
+ (semi >= 0 ? restriction.extra.substring(semi) : "");
} else {
int dot = restriction.extra.indexOf('.');
if (dot > 0)
return '*' + restriction.extra.substring(dot);
}
}
return null;
}
private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result,
Hook hook) {
try {
// Set the whitelist
Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction
+ " xextra=" + xextra);
setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra
: xextra), Boolean.toString(!result.restricted)));
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void onDemandOnce(final PRestriction restriction, final PRestriction result) {
Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction);
result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs;
CRestriction key = new CRestriction(restriction, restriction.extra);
synchronized (mAskedOnceCache) {
if (mAskedOnceCache.containsKey(key))
mAskedOnceCache.remove(key);
mAskedOnceCache.put(key, key);
}
}
private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) {
try {
PRestriction result = new PRestriction(restriction);
// Get current category restriction state
boolean prevRestricted = false;
CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
prevRestricted = mRestrictionCache.get(key).restricted;
}
Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/"
+ prevRestricted + " restrict=" + restrict);
if (category || (restrict && restrict != prevRestricted)) {
// Set category restriction
result.methodName = null;
result.restricted = restrict;
result.asked = category;
setRestrictionInternal(result);
// Clear category on change
boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false);
for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) {
result.methodName = md.getName();
result.restricted = (md.isDangerous() && !dangerous ? false : restrict);
result.asked = category;
setRestrictionInternal(result);
}
}
if (!category) {
// Set method restriction
result.methodName = restriction.methodName;
result.restricted = restrict;
result.asked = true;
result.extra = restriction.extra;
setRestrictionInternal(result);
}
// Mark state as changed
setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_CHANGED)));
// Update modification time
setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime,
Long.toString(System.currentTimeMillis())));
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void notifyRestricted(final PRestriction restriction) {
final Context context = getContext();
if (context != null && mHandler != null)
mHandler.post(new Runnable() {
@Override
public void run() {
long token = 0;
try {
token = Binder.clearCallingIdentity();
// Get resources
String self = PrivacyService.class.getPackage().getName();
Resources resources = context.getPackageManager().getResourcesForApplication(self);
// Notify user
String text = resources.getString(R.string.msg_restrictedby);
text += " (" + restriction.uid + " " + restriction.restrictionName + "/"
+ restriction.methodName + ")";
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
} catch (NameNotFoundException ex) {
Util.bug(null, ex);
} finally {
Binder.restoreCallingIdentity(token);
}
}
});
}
private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException {
return getSettingBool(uid, "", name, defaultValue);
}
private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException {
String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value;
return Boolean.parseBoolean(value);
}
private void enforcePermission() {
int callingUid = Util.getAppId(Binder.getCallingUid());
if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID)
throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid());
}
private Context getContext() {
// public static ActivityManagerService self()
// frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
try {
Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService");
Object am = cam.getMethod("self").invoke(null);
if (am == null)
return null;
return (Context) cam.getDeclaredField("mContext").get(am);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
private int getXUid() {
if (mXUid < 0)
try {
Context context = getContext();
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
String self = PrivacyService.class.getPackage().getName();
ApplicationInfo xInfo = pm.getApplicationInfo(self, 0);
mXUid = xInfo.uid;
}
}
} catch (Throwable ignored) {
// The package manager may not be up-to-date yet
}
return mXUid;
}
private File getDbFile() {
return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy"
+ File.separator + "xprivacy.db");
}
private File getDbUsageFile() {
return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy"
+ File.separator + "usage.db");
}
private void setupDatabase() {
try {
File dbFile = getDbFile();
// Create database folder
dbFile.getParentFile().mkdirs();
// Check database folder
if (dbFile.getParentFile().isDirectory())
Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile());
else
Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile());
// Move database from data/xprivacy folder
File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy");
if (folder.exists()) {
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = Util.move(file, target);
Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status);
}
folder.delete();
}
// Move database from data/application folder
folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator
+ PrivacyService.class.getPackage().getName());
if (folder.exists()) {
File[] oldFiles = folder.listFiles();
if (oldFiles != null)
for (File file : oldFiles)
if (file.getName().startsWith("xprivacy.db")) {
File target = new File(dbFile.getParentFile() + File.separator + file.getName());
boolean status = Util.move(file, target);
Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status);
}
folder.delete();
}
// Set database file permissions
// Owner: rwx (system)
// Group: rwx (system)
// World: ---
Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID,
Process.SYSTEM_UID);
File[] files = dbFile.getParentFile().listFiles();
if (files != null)
for (File file : files)
if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db"))
Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private SQLiteDatabase getDb() {
synchronized (this) {
// Check current reference
if (mDb != null && !mDb.isOpen()) {
mDb = null;
Util.log(null, Log.ERROR, "Database not open");
}
if (mDb == null)
try {
setupDatabase();
// Create/upgrade database when needed
File dbFile = getDbFile();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
// Check database integrity
if (db.isDatabaseIntegrityOk())
Util.log(null, Log.WARN, "Database integrity ok");
else {
// http://www.sqlite.org/howtocorrupt.html
Util.log(null, Log.ERROR, "Database corrupt");
Cursor cursor = db.rawQuery("PRAGMA integrity_check", null);
try {
while (cursor.moveToNext()) {
String message = cursor.getString(0);
Util.log(null, Log.ERROR, message);
}
} finally {
cursor.close();
}
db.close();
// Backup database file
File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup");
dbBackup.delete();
dbFile.renameTo(dbBackup);
File dbJournal = new File(dbFile.getAbsolutePath() + "-journal");
File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal");
dbJournalBackup.delete();
dbJournal.renameTo(dbJournalBackup);
Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath());
// Create new database
db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
Util.log(null, Log.ERROR, "New, empty database created");
}
// Update migration status
if (db.getVersion() > 1) {
Util.log(null, Log.WARN, "Updating migration status");
mLock.writeLock().lock();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", 0);
if (db.getVersion() > 9)
values.put("type", "");
values.put("name", PrivacyManager.cSettingMigrated);
values.put("value", Boolean.toString(true));
db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
// Upgrade database if needed
if (db.needUpgrade(1)) {
Util.log(null, Log.WARN, "Creating database");
mLock.writeLock().lock();
db.beginTransaction();
try {
// http://www.sqlite.org/lang_createtable.html
db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)");
db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)");
db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)");
db.setVersion(1);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(2)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
// Old migrated indication
db.setVersion(2);
}
if (db.needUpgrade(3)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM usage WHERE method=''");
db.setVersion(3);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(4)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value IS NULL");
db.setVersion(4);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(5)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE value = ''");
db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'");
db.setVersion(5);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(6)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'");
db.setVersion(6);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(7)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT");
db.setVersion(7);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(8)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DROP INDEX idx_usage");
db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)");
db.setVersion(8);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(9)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("DROP TABLE usage");
db.setVersion(9);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(10)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT");
db.execSQL("DROP INDEX idx_setting");
db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)");
db.execSQL("UPDATE setting SET type=''");
db.setVersion(10);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
if (db.needUpgrade(11)) {
Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion());
mLock.writeLock().lock();
db.beginTransaction();
try {
List<PSetting> listSetting = new ArrayList<PSetting>();
Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null,
null, null, null, null);
if (cursor != null)
try {
while (cursor.moveToNext()) {
int uid = cursor.getInt(0);
String name = cursor.getString(1);
String value = cursor.getString(2);
if (name.startsWith("Account.") || name.startsWith("Application.")
|| name.startsWith("Contact.") || name.startsWith("Template.")) {
int dot = name.indexOf('.');
String type = name.substring(0, dot);
listSetting
.add(new PSetting(uid, type, name.substring(dot + 1), value));
listSetting.add(new PSetting(uid, "", name, null));
} else if (name.startsWith("Whitelist.")) {
String[] component = name.split("\\.");
listSetting.add(new PSetting(uid, component[1], name.replace(
component[0] + "." + component[1] + ".", ""), value));
listSetting.add(new PSetting(uid, "", name, null));
}
}
} finally {
cursor.close();
}
for (PSetting setting : listSetting) {
Util.log(null, Log.WARN, "Converting " + setting);
if (setting.value == null)
db.delete(cTableSetting, "uid=? AND type=? AND name=?",
new String[] { Integer.toString(setting.uid), setting.type,
setting.name });
else {
// Create record
ContentValues values = new ContentValues();
values.put("uid", setting.uid);
values.put("type", setting.type);
values.put("name", setting.name);
values.put("value", setting.value);
// Insert/update record
db.insertWithOnConflict(cTableSetting, null, values,
SQLiteDatabase.CONFLICT_REPLACE);
}
}
db.setVersion(11);
db.setTransactionSuccessful();
} finally {
try {
db.endTransaction();
} finally {
mLock.writeLock().unlock();
}
}
}
Util.log(null, Log.WARN, "Running VACUUM");
mLock.writeLock().lock();
try {
db.execSQL("VACUUM");
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
mLock.writeLock().unlock();
}
Util.log(null, Log.WARN, "Database version=" + db.getVersion());
mDb = db;
} catch (Throwable ex) {
mDb = null; // retry
Util.bug(null, ex);
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(
"/cache/xprivacy.log", true));
outputStreamWriter.write(ex.toString());
outputStreamWriter.write("\n");
outputStreamWriter.write(Log.getStackTraceString(ex));
outputStreamWriter.write("\n");
outputStreamWriter.close();
} catch (Throwable exex) {
Util.bug(null, exex);
}
}
return mDb;
}
}
private SQLiteDatabase getDbUsage() {
synchronized (this) {
// Check current reference
if (mDbUsage != null && !mDbUsage.isOpen()) {
mDbUsage = null;
Util.log(null, Log.ERROR, "Usage database not open");
}
if (mDbUsage == null)
try {
// Create/upgrade database when needed
File dbUsageFile = getDbUsageFile();
SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null);
// Check database integrity
if (dbUsage.isDatabaseIntegrityOk())
Util.log(null, Log.WARN, "Usage database integrity ok");
else {
dbUsage.close();
dbUsageFile.delete();
new File(dbUsageFile + "-journal").delete();
dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null);
Util.log(null, Log.ERROR, "Deleted corrupt usage data database");
}
// Upgrade database if needed
if (dbUsage.needUpgrade(1)) {
Util.log(null, Log.WARN, "Creating usage database");
mLockUsage.writeLock().lock();
dbUsage.beginTransaction();
try {
dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)");
dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)");
dbUsage.setVersion(1);
dbUsage.setTransactionSuccessful();
} finally {
try {
dbUsage.endTransaction();
} finally {
mLockUsage.writeLock().unlock();
}
}
}
Util.log(null, Log.WARN, "Running VACUUM");
mLockUsage.writeLock().lock();
try {
dbUsage.execSQL("VACUUM");
} catch (Throwable ex) {
Util.bug(null, ex);
} finally {
mLockUsage.writeLock().unlock();
}
Util.log(null, Log.WARN, "Changing to asynchronous mode");
try {
dbUsage.rawQuery("PRAGMA synchronous=OFF", null);
} catch (Throwable ex) {
Util.bug(null, ex);
}
Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion());
mDbUsage = dbUsage;
} catch (Throwable ex) {
mDbUsage = null; // retry
Util.bug(null, ex);
}
return mDbUsage;
}
}
};
}
|
diff --git a/ssa-web/src/main/java/org/inftel/ssa/web/DashboardManager.java b/ssa-web/src/main/java/org/inftel/ssa/web/DashboardManager.java
index 752a446..2022455 100644
--- a/ssa-web/src/main/java/org/inftel/ssa/web/DashboardManager.java
+++ b/ssa-web/src/main/java/org/inftel/ssa/web/DashboardManager.java
@@ -1,170 +1,170 @@
package org.inftel.ssa.web;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGroup;
import javax.faces.context.FacesContext;
import org.inftel.ssa.domain.Task;
import org.inftel.ssa.domain.TaskStatus;
import org.inftel.ssa.domain.User;
import org.inftel.ssa.services.ResourceService;
import org.primefaces.component.dashboard.Dashboard;
import org.primefaces.component.panel.Panel;
import org.primefaces.event.DashboardReorderEvent;
import org.primefaces.model.DashboardColumn;
import org.primefaces.model.DashboardModel;
import org.primefaces.model.DefaultDashboardColumn;
import org.primefaces.model.DefaultDashboardModel;
@ManagedBean
@ViewScoped
public class DashboardManager implements Serializable {
public static final String TASK_PREFIX = "task_id_";
private final static Logger logger = Logger.getLogger(TaskManager.class.getName());
private static final long serialVersionUID = 1L;
@ManagedProperty(value = "#{sprintManager}")
private SprintManager sprintManager;
@ManagedProperty(value = "#{projectManager}")
private ProjectManager projectManager;
@ManagedProperty(value = "#{userManager}")
private UserManager userManager;
private int columnCount;
private Dashboard dashboard;
private DashboardModel dashboardModel;
@EJB
private ResourceService resourecService;
public DashboardManager() {
}
public void init() {
User currentUser = userManager.getCurrentUser();
columnCount = 3;
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
dashboard = (Dashboard) application.createComponent(fc, "org.primefaces.component.Dashboard", "org.primefaces.component.DashboardRenderer");
dashboard.setId("dashboard");
dashboardModel = new DefaultDashboardModel();
DashboardColumn toDo = new DefaultDashboardColumn();
DashboardColumn inProgress = new DefaultDashboardColumn();
DashboardColumn done = new DefaultDashboardColumn();
dashboardModel.addColumn(toDo);
dashboardModel.addColumn(inProgress);
dashboardModel.addColumn(done);
dashboard.setModel(dashboardModel);
- List<Task> tasks = projectManager.getCurrentProject().getTasks();
+ List<Task> tasks = projectManager.getCurrentProject(true).getTasks();
//Estas tareas tendrian que estar filtradas por el currenteSprint
for (Task task : tasks) {
Panel panel = (Panel) application.createComponent(fc, "org.primefaces.component.Panel", "org.primefaces.component.PanelRenderer");
//Al establecer el id me daba error sino ponia al menos una cadena de texto. Raro, la verdad
panel.setId(TASK_PREFIX + task.getId().toString());
panel.setHeader(task.getSummary());
dashboard.getChildren().add(panel);
// Style by task owner
String styles = "well";
if (task.getUser() == null) {
styles = styles + " none-user";
} else if (task.getUser().equals(currentUser)) {
styles = styles + " current-user";
} else {
styles = styles + " team-user";
}
panel.setStyleClass(styles);
DashboardColumn column = dashboardModel.getColumn(task.getStatus().ordinal());
column.addWidget(panel.getId());
HtmlOutputText priority = new HtmlOutputText();
priority.setStyleClass("priority");
priority.setValue("Priority: " + task.getPriority());
HtmlOutputText owner = new HtmlOutputText();
owner.setStyleClass("owner");
owner.setValue("Owner: " + (task.getUser() == null ? "nadie" : task.getUser().getEmail()));
HtmlOutputText description = new HtmlOutputText();
description.setStyleClass("description");
description.setValue(task.getDescription());
HtmlPanelGroup content = new HtmlPanelGroup();
content.setLayout("block");
content.setStyleClass("subtitle");
content.getChildren().add(priority);
content.getChildren().add(owner);
panel.getChildren().add(content);
panel.getChildren().add(description);
}
}
public Dashboard getDashboard() {
init();
return dashboard;
}
public void setDashboard(Dashboard dashboard) {
this.dashboard = dashboard;
}
public int getColumnCount() {
return columnCount;
}
public void setColumnCount(int columnCount) {
this.columnCount = columnCount;
}
public ProjectManager getProjectManager() {
return projectManager;
}
public void setProjectManager(ProjectManager projectManager) {
this.projectManager = projectManager;
}
public SprintManager getSprintManager() {
return sprintManager;
}
public void setSprintManager(SprintManager sprintManager) {
this.sprintManager = sprintManager;
}
public UserManager getUserManager() {
return userManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public void handleReorder(DashboardReorderEvent event) {
String widgetId = event.getWidgetId();
int columnIndex = event.getColumnIndex();
//TODO actualizar las tareas
logger.info("Widget movido: " + widgetId);
Task task = resourecService.findTask(Long.parseLong(widgetId.substring(TASK_PREFIX.length())));
task.setStatus(TaskStatus.values()[columnIndex]);
resourecService.saveTask(task);
logger.info("Columna destino: " + columnIndex);
}
}
| true | true | public void init() {
User currentUser = userManager.getCurrentUser();
columnCount = 3;
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
dashboard = (Dashboard) application.createComponent(fc, "org.primefaces.component.Dashboard", "org.primefaces.component.DashboardRenderer");
dashboard.setId("dashboard");
dashboardModel = new DefaultDashboardModel();
DashboardColumn toDo = new DefaultDashboardColumn();
DashboardColumn inProgress = new DefaultDashboardColumn();
DashboardColumn done = new DefaultDashboardColumn();
dashboardModel.addColumn(toDo);
dashboardModel.addColumn(inProgress);
dashboardModel.addColumn(done);
dashboard.setModel(dashboardModel);
List<Task> tasks = projectManager.getCurrentProject().getTasks();
//Estas tareas tendrian que estar filtradas por el currenteSprint
for (Task task : tasks) {
Panel panel = (Panel) application.createComponent(fc, "org.primefaces.component.Panel", "org.primefaces.component.PanelRenderer");
//Al establecer el id me daba error sino ponia al menos una cadena de texto. Raro, la verdad
panel.setId(TASK_PREFIX + task.getId().toString());
panel.setHeader(task.getSummary());
dashboard.getChildren().add(panel);
// Style by task owner
String styles = "well";
if (task.getUser() == null) {
styles = styles + " none-user";
} else if (task.getUser().equals(currentUser)) {
styles = styles + " current-user";
} else {
styles = styles + " team-user";
}
panel.setStyleClass(styles);
DashboardColumn column = dashboardModel.getColumn(task.getStatus().ordinal());
column.addWidget(panel.getId());
HtmlOutputText priority = new HtmlOutputText();
priority.setStyleClass("priority");
priority.setValue("Priority: " + task.getPriority());
HtmlOutputText owner = new HtmlOutputText();
owner.setStyleClass("owner");
owner.setValue("Owner: " + (task.getUser() == null ? "nadie" : task.getUser().getEmail()));
HtmlOutputText description = new HtmlOutputText();
description.setStyleClass("description");
description.setValue(task.getDescription());
HtmlPanelGroup content = new HtmlPanelGroup();
content.setLayout("block");
content.setStyleClass("subtitle");
content.getChildren().add(priority);
content.getChildren().add(owner);
panel.getChildren().add(content);
panel.getChildren().add(description);
}
}
| public void init() {
User currentUser = userManager.getCurrentUser();
columnCount = 3;
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
dashboard = (Dashboard) application.createComponent(fc, "org.primefaces.component.Dashboard", "org.primefaces.component.DashboardRenderer");
dashboard.setId("dashboard");
dashboardModel = new DefaultDashboardModel();
DashboardColumn toDo = new DefaultDashboardColumn();
DashboardColumn inProgress = new DefaultDashboardColumn();
DashboardColumn done = new DefaultDashboardColumn();
dashboardModel.addColumn(toDo);
dashboardModel.addColumn(inProgress);
dashboardModel.addColumn(done);
dashboard.setModel(dashboardModel);
List<Task> tasks = projectManager.getCurrentProject(true).getTasks();
//Estas tareas tendrian que estar filtradas por el currenteSprint
for (Task task : tasks) {
Panel panel = (Panel) application.createComponent(fc, "org.primefaces.component.Panel", "org.primefaces.component.PanelRenderer");
//Al establecer el id me daba error sino ponia al menos una cadena de texto. Raro, la verdad
panel.setId(TASK_PREFIX + task.getId().toString());
panel.setHeader(task.getSummary());
dashboard.getChildren().add(panel);
// Style by task owner
String styles = "well";
if (task.getUser() == null) {
styles = styles + " none-user";
} else if (task.getUser().equals(currentUser)) {
styles = styles + " current-user";
} else {
styles = styles + " team-user";
}
panel.setStyleClass(styles);
DashboardColumn column = dashboardModel.getColumn(task.getStatus().ordinal());
column.addWidget(panel.getId());
HtmlOutputText priority = new HtmlOutputText();
priority.setStyleClass("priority");
priority.setValue("Priority: " + task.getPriority());
HtmlOutputText owner = new HtmlOutputText();
owner.setStyleClass("owner");
owner.setValue("Owner: " + (task.getUser() == null ? "nadie" : task.getUser().getEmail()));
HtmlOutputText description = new HtmlOutputText();
description.setStyleClass("description");
description.setValue(task.getDescription());
HtmlPanelGroup content = new HtmlPanelGroup();
content.setLayout("block");
content.setStyleClass("subtitle");
content.getChildren().add(priority);
content.getChildren().add(owner);
panel.getChildren().add(content);
panel.getChildren().add(description);
}
}
|
diff --git a/src/main/java/com/github/tell/util/datastructure/ImmutableObject.java b/src/main/java/com/github/tell/util/datastructure/ImmutableObject.java
index d3950a0..b6b97de 100644
--- a/src/main/java/com/github/tell/util/datastructure/ImmutableObject.java
+++ b/src/main/java/com/github/tell/util/datastructure/ImmutableObject.java
@@ -1,97 +1,96 @@
/**
* @author Tadanori TERUYA <[email protected]> (2012)
*/
/*
* Copyright (c) 2012 Tadanori TERUYA (tell) <[email protected]>
*
* 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.
*
* @license: The MIT license <http://opensource.org/licenses/MIT>
*/
package com.github.tell.util.datastructure;
import java.io.Serializable;
public final class ImmutableObject<T extends Serializable> implements
Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = -8177196769410093651L;
private T o;
private CopyFunction<T> copyFunc;
public String toString() {
return o.toString();
}
public int hashCode() {
return o.hashCode();
}
public boolean equals(final Object o) {
if (o instanceof ImmutableObject<?>) {
@SuppressWarnings("unchecked")
final ImmutableObject<T> x = (ImmutableObject<T>) o;
return this.o.equals(x.o);
} else {
return false;
}
}
public ImmutableObject() {
this.o = null;
this.copyFunc = null;
}
public ImmutableObject(final T o) {
this.o = o;
this.copyFunc = new CopyFunction<T>(o);
}
@SuppressWarnings("unchecked")
public ImmutableObject<T> clone() {
try {
- final ImmutableObject<T> result = (ImmutableObject<T>) super
- .clone();
+ final ImmutableObject<T> result = new ImmutableObject<T>();
result.o = this.copyFunc.call();
result.copyFunc = this.copyFunc;
return result;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public T getObject() {
try {
return this.copyFunc.call();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| true | true | public ImmutableObject<T> clone() {
try {
final ImmutableObject<T> result = (ImmutableObject<T>) super
.clone();
result.o = this.copyFunc.call();
result.copyFunc = this.copyFunc;
return result;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
| public ImmutableObject<T> clone() {
try {
final ImmutableObject<T> result = new ImmutableObject<T>();
result.o = this.copyFunc.call();
result.copyFunc = this.copyFunc;
return result;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
|
diff --git a/Android/app/src/com/bigbluecup/android/AgsEngine.java b/Android/app/src/com/bigbluecup/android/AgsEngine.java
index fcb34d8b..355b4830 100644
--- a/Android/app/src/com/bigbluecup/android/AgsEngine.java
+++ b/Android/app/src/com/bigbluecup/android/AgsEngine.java
@@ -1,476 +1,476 @@
package com.bigbluecup.android;
import com.bigbluecup.android.EngineGlue;
import com.bigbluecup.android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
public class AgsEngine extends Activity
{
public boolean isInGame = false;
private Toast toast = null;
private EngineGlue glue;
private PowerManager.WakeLock wakeLock;
private AudioManager audio;
public CustomGlSurfaceView surfaceView;
public MessageHandler handler;
boolean ignoreNextPointerUp = false;
boolean ignoreMovement = false;
boolean initialized = false;
boolean stopLongclick = false;
boolean enableLongclick = false;
private float lastX = 0.0f;
private float lastY = 0.0f;
private float downX = 0.0f;
private float downY = 0.0f;
private boolean ignoreNextActionUp_Back = false;
private boolean ignoreNextActionUp_Menu = false;
private boolean draggingMouse = false;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the game filename from the launcher activity
String gameFilename = getIntent().getExtras().getString("filename");
String baseDirectory = getIntent().getExtras().getString("directory");
boolean loadLastSave = getIntent().getExtras().getBoolean("loadLastSave");
// Set windows options
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
// Stop the device from saving power
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "fullwakelock");
wakeLock.acquire();
// Set message handler for thread communication
handler = new MessageHandler();
audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Switch to the loading view and start the game
isInGame = true;
setContentView(R.layout.loading);
glue = new EngineGlue(this, gameFilename, baseDirectory, loadLastSave);
glue.start();
}
@Override
public void onDestroy()
{
glue.shutdownEngine();
super.onDestroy();
}
@Override
protected void onPause()
{
super.onPause();
wakeLock.release();
if (isInGame)
glue.pauseGame();
}
@Override
protected void onResume()
{
super.onResume();
wakeLock.acquire();
if (isInGame)
glue.resumeGame();
}
// Prevent the activity from being destroyed on a configuration change
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}
// Handle messages from the engine thread
class MessageHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case EngineGlue.MSG_SWITCH_TO_INGAME:
switchToIngame();
break;
case EngineGlue.MSG_SHOW_MESSAGE:
showMessage(msg.getData().getString("message"));
break;
case EngineGlue.MSG_SHOW_TOAST:
showToast(msg.getData().getString("message"));
break;
case EngineGlue.MSG_SET_ORIENTATION:
setRequestedOrientation(msg.getData().getInt("orientation"));
break;
case EngineGlue.MSG_ENABLE_LONGCLICK:
enableLongclick = true;
break;
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
switch (ev.getAction() & 0xFF)
{
case MotionEvent.ACTION_DOWN:
{
- downX = ev.getX();
- downY = ev.getY();
+ downX = lastX = ev.getX();
+ downY = lastY = ev.getY();
ignoreMovement = false;
initialized = false;
stopLongclick = false;
glue.moveMouse(0, 0, downX, downY);
break;
}
case MotionEvent.ACTION_MOVE:
{
if (!initialized)
{
lastX = ev.getX();
lastY = ev.getY();
initialized = true;
}
if (!ignoreMovement)
{
float x = ev.getX() - lastX;
float y = ev.getY() - lastY;
lastX = ev.getX();
lastY = ev.getY();
glue.moveMouse(x, y, lastX, lastY);
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
}
break;
}
case MotionEvent.ACTION_UP:
{
ignoreMovement = false;
long down_time = ev.getEventTime() - ev.getDownTime();
if (down_time < 200)
{
// Quick tap for clicking the left mouse button
glue.clickMouse(EngineGlue.MOUSE_CLICK_LEFT);
draggingMouse = false;
}
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
break;
}
// Second finger down
case 5: //MotionEvent.ACTION_POINTER_DOWN:
{
stopLongclick = true;
ignoreMovement = true;
ignoreNextPointerUp = true;
}
// Second finger lifted
case 6: //MotionEvent.ACTION_POINTER_UP:
{
if (!ignoreNextPointerUp)
{
glue.clickMouse(EngineGlue.MOUSE_CLICK_RIGHT);
ignoreMovement = false;
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
}
ignoreNextPointerUp = false;
break;
}
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.key_f1:
glue.keyboardEvent(0x1000 + 47, 0, false);
break;
case R.id.key_f2:
glue.keyboardEvent(0x1000 + 48, 0, false);
break;
case R.id.key_f3:
glue.keyboardEvent(0x1000 + 49, 0, false);
break;
case R.id.key_f4:
glue.keyboardEvent(0x1000 + 50, 0, false);
break;
case R.id.key_f5:
glue.keyboardEvent(0x1000 + 51, 0, false);
break;
case R.id.key_f6:
glue.keyboardEvent(0x1000 + 52, 0, false);
break;
case R.id.key_f7:
glue.keyboardEvent(0x1000 + 53, 0, false);
break;
case R.id.key_f8:
glue.keyboardEvent(0x1000 + 54, 0, false);
break;
case R.id.key_f9:
glue.keyboardEvent(0x1000 + 55, 0, false);
break;
case R.id.key_f10:
glue.keyboardEvent(0x1000 + 56, 0, false);
break;
case R.id.key_f11:
glue.keyboardEvent(0x1000 + 57, 0, false);
break;
case R.id.key_f12:
glue.keyboardEvent(0x1000 + 58, 0, false);
break;
case R.id.exitgame:
showExitConfirmation();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ingame, menu);
return true;
}
@Override
public boolean dispatchKeyEvent(KeyEvent ev)
{
// Very simple key processing for now, just one key event per poll
switch (ev.getAction())
{
case KeyEvent.ACTION_DOWN:
{
int key = ev.getKeyCode();
if ((key == KeyEvent.KEYCODE_BACK) && ((ev.getFlags() & 0x80) > 0)) // FLAG_LONG_PRESS
{
ignoreNextActionUp_Back = true;
showExitConfirmation();
}
if ((key == KeyEvent.KEYCODE_MENU) && ((ev.getFlags() & 0x80) > 0)) // FLAG_LONG_PRESS
{
ignoreNextActionUp_Menu = true;
InputMethodManager manager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
if (key == KeyEvent.KEYCODE_VOLUME_UP)
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
if (key == KeyEvent.KEYCODE_VOLUME_DOWN)
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
break;
}
case KeyEvent.ACTION_UP:
{
int key = ev.getKeyCode();
if (key == KeyEvent.KEYCODE_MENU)
{
if (!ignoreNextActionUp_Menu)
openOptionsMenu();
ignoreNextActionUp_Menu = false;
}
else if (key == KeyEvent.KEYCODE_BACK)
{
if (!ignoreNextActionUp_Back)
glue.keyboardEvent(key, 0, ev.isShiftPressed());
ignoreNextActionUp_Back = false;
}
else if (
(key == KeyEvent.KEYCODE_MENU)
|| (key == KeyEvent.KEYCODE_VOLUME_UP)
|| (key == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (key == 164) // KEYCODE_VOLUME_MUTE
|| (key == KeyEvent.KEYCODE_ALT_LEFT)
|| (key == KeyEvent.KEYCODE_ALT_RIGHT)
|| (key == KeyEvent.KEYCODE_SHIFT_LEFT)
|| (key == KeyEvent.KEYCODE_SHIFT_RIGHT))
return isInGame;
glue.keyboardEvent(key, ev.getUnicodeChar(), ev.isShiftPressed());
break;
}
}
return isInGame;
}
// Exit confirmation dialog displayed when hitting the "back" button
private void showExitConfirmation()
{
onPause();
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("Are you sure you want to quit?");
ad.setOnCancelListener(new OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
onResume();
}
});
ad.setPositiveButton("Yes", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
onResume();
onDestroy();
}
});
ad.setNegativeButton("No", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
onResume();
}
});
ad.show();
}
// Display a game message
public void showMessage(String message)
{
onPause();
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Error");
dialog.setMessage(message);
dialog.setPositiveButton("OK", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
onResume();
}
});
dialog.show();
}
public void showToast(String message)
{
if (toast == null)
toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
else
toast.setText(message);
toast.show();
}
// Switch to the game view after loading is done
public void switchToIngame()
{
surfaceView = new CustomGlSurfaceView(this);
setContentView(surfaceView);
surfaceView.setOnLongClickListener(new OnLongClickListener()
{
public boolean onLongClick(View v)
{
if (!draggingMouse && !stopLongclick && (Math.abs(downX - lastX) < 4.0f) && (Math.abs(downY - lastY) < 4.0f))
{
draggingMouse = true;
glue.clickMouse(EngineGlue.MOUSE_HOLD_LEFT);
return true; // Produces haptic feedback (vibration)
}
return false;
}
});
surfaceView.setLongClickable(enableLongclick);
isInGame = true;
}
}
| true | true | public boolean dispatchTouchEvent(MotionEvent ev)
{
switch (ev.getAction() & 0xFF)
{
case MotionEvent.ACTION_DOWN:
{
downX = ev.getX();
downY = ev.getY();
ignoreMovement = false;
initialized = false;
stopLongclick = false;
glue.moveMouse(0, 0, downX, downY);
break;
}
case MotionEvent.ACTION_MOVE:
{
if (!initialized)
{
lastX = ev.getX();
lastY = ev.getY();
initialized = true;
}
if (!ignoreMovement)
{
float x = ev.getX() - lastX;
float y = ev.getY() - lastY;
lastX = ev.getX();
lastY = ev.getY();
glue.moveMouse(x, y, lastX, lastY);
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
}
break;
}
case MotionEvent.ACTION_UP:
{
ignoreMovement = false;
long down_time = ev.getEventTime() - ev.getDownTime();
if (down_time < 200)
{
// Quick tap for clicking the left mouse button
glue.clickMouse(EngineGlue.MOUSE_CLICK_LEFT);
draggingMouse = false;
}
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
break;
}
// Second finger down
case 5: //MotionEvent.ACTION_POINTER_DOWN:
{
stopLongclick = true;
ignoreMovement = true;
ignoreNextPointerUp = true;
}
// Second finger lifted
case 6: //MotionEvent.ACTION_POINTER_UP:
{
if (!ignoreNextPointerUp)
{
glue.clickMouse(EngineGlue.MOUSE_CLICK_RIGHT);
ignoreMovement = false;
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
}
ignoreNextPointerUp = false;
break;
}
}
return super.dispatchTouchEvent(ev);
}
| public boolean dispatchTouchEvent(MotionEvent ev)
{
switch (ev.getAction() & 0xFF)
{
case MotionEvent.ACTION_DOWN:
{
downX = lastX = ev.getX();
downY = lastY = ev.getY();
ignoreMovement = false;
initialized = false;
stopLongclick = false;
glue.moveMouse(0, 0, downX, downY);
break;
}
case MotionEvent.ACTION_MOVE:
{
if (!initialized)
{
lastX = ev.getX();
lastY = ev.getY();
initialized = true;
}
if (!ignoreMovement)
{
float x = ev.getX() - lastX;
float y = ev.getY() - lastY;
lastX = ev.getX();
lastY = ev.getY();
glue.moveMouse(x, y, lastX, lastY);
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
}
break;
}
case MotionEvent.ACTION_UP:
{
ignoreMovement = false;
long down_time = ev.getEventTime() - ev.getDownTime();
if (down_time < 200)
{
// Quick tap for clicking the left mouse button
glue.clickMouse(EngineGlue.MOUSE_CLICK_LEFT);
draggingMouse = false;
}
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
break;
}
// Second finger down
case 5: //MotionEvent.ACTION_POINTER_DOWN:
{
stopLongclick = true;
ignoreMovement = true;
ignoreNextPointerUp = true;
}
// Second finger lifted
case 6: //MotionEvent.ACTION_POINTER_UP:
{
if (!ignoreNextPointerUp)
{
glue.clickMouse(EngineGlue.MOUSE_CLICK_RIGHT);
ignoreMovement = false;
try
{
// Delay a bit to not get flooded with events
Thread.sleep(50, 0);
}
catch (InterruptedException e) {}
}
ignoreNextPointerUp = false;
break;
}
}
return super.dispatchTouchEvent(ev);
}
|
diff --git a/src/com/eteks/sweethome3d/swing/WallPanel.java b/src/com/eteks/sweethome3d/swing/WallPanel.java
index 9ba381cd..90d8c37b 100644
--- a/src/com/eteks/sweethome3d/swing/WallPanel.java
+++ b/src/com/eteks/sweethome3d/swing/WallPanel.java
@@ -1,1104 +1,1104 @@
/*
* WallPanel.java 29 mai 07
*
* Sweet Home 3D, Copyright (c) 2007 Emmanuel PUYBARET / eTeks <[email protected]>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.eteks.sweethome3d.swing;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.eteks.sweethome3d.model.TextureImage;
import com.eteks.sweethome3d.model.UserPreferences;
import com.eteks.sweethome3d.tools.OperatingSystem;
import com.eteks.sweethome3d.tools.ResourceURLContent;
import com.eteks.sweethome3d.viewcontroller.DialogView;
import com.eteks.sweethome3d.viewcontroller.View;
import com.eteks.sweethome3d.viewcontroller.WallController;
/**
* Wall editing panel.
* @author Emmanuel Puybaret
*/
public class WallPanel extends JPanel implements DialogView {
private final WallController controller;
private JLabel xStartLabel;
private JSpinner xStartSpinner;
private JLabel yStartLabel;
private JSpinner yStartSpinner;
private JLabel xEndLabel;
private JSpinner xEndSpinner;
private JLabel yEndLabel;
private JSpinner yEndSpinner;
private JLabel distanceToEndPointLabel;
private JSpinner distanceToEndPointSpinner;
private JRadioButton leftSideColorRadioButton;
private ColorButton leftSideColorButton;
private JRadioButton leftSideTextureRadioButton;
private JComponent leftSideTextureComponent;
private JRadioButton leftSideMattRadioButton;
private JRadioButton leftSideShinyRadioButton;
private JRadioButton rightSideColorRadioButton;
private ColorButton rightSideColorButton;
private JRadioButton rightSideTextureRadioButton;
private JComponent rightSideTextureComponent;
private JRadioButton rightSideMattRadioButton;
private JRadioButton rightSideShinyRadioButton;
private JLabel patternLabel;
private JComboBox patternComboBox;
private JLabel topColorLabel;
private JRadioButton topDefaultColorRadioButton;
private JRadioButton topColorRadioButton;
private ColorButton topColorButton;
private JRadioButton rectangularWallRadioButton;
private JLabel rectangularWallHeightLabel;
private JSpinner rectangularWallHeightSpinner;
private JRadioButton slopingWallRadioButton;
private JLabel slopingWallHeightAtStartLabel;
private JSpinner slopingWallHeightAtStartSpinner;
private JLabel slopingWallHeightAtEndLabel;
private JSpinner slopingWallHeightAtEndSpinner;
private JLabel thicknessLabel;
private JSpinner thicknessSpinner;
private JLabel arcExtentLabel;
private JSpinner arcExtentSpinner;
private JLabel wallOrientationLabel;
private String dialogTitle;
/**
* Creates a panel that displays wall data according to the units set in
* <code>preferences</code>.
* @param preferences user preferences
* @param controller the controller of this panel
*/
public WallPanel(UserPreferences preferences,
WallController controller) {
super(new GridBagLayout());
this.controller = controller;
createComponents(preferences, controller);
setMnemonics(preferences);
layoutComponents(preferences, controller);
}
/**
* Creates and initializes components and spinners model.
*/
private void createComponents(UserPreferences preferences,
final WallController controller) {
// Get unit name matching current unit
String unitName = preferences.getLengthUnit().getName();
// Create X start label and its spinner bound to X_START controller property
this.xStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "xLabel.text", unitName));
final float maximumLength = preferences.getLengthUnit().getMaximumLength();
final NullableSpinner.NullableSpinnerLengthModel xStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.xStartSpinner = new NullableSpinner(xStartSpinnerModel);
xStartSpinnerModel.setNullable(controller.getXStart() == null);
xStartSpinnerModel.setLength(controller.getXStart());
final PropertyChangeListener xStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xStartSpinnerModel.setNullable(ev.getNewValue() == null);
xStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
xStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
controller.setXStart(xStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
}
});
// Create Y start label and its spinner bound to Y_START controller property
this.yStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel yStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.yStartSpinner = new NullableSpinner(yStartSpinnerModel);
yStartSpinnerModel.setNullable(controller.getYStart() == null);
yStartSpinnerModel.setLength(controller.getYStart());
final PropertyChangeListener yStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
yStartSpinnerModel.setNullable(ev.getNewValue() == null);
yStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
yStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
controller.setYStart(yStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
}
});
// Create X end label and its spinner bound to X_END controller property
this.xEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "xLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel xEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.xEndSpinner = new NullableSpinner(xEndSpinnerModel);
xEndSpinnerModel.setNullable(controller.getXEnd() == null);
xEndSpinnerModel.setLength(controller.getXEnd());
final PropertyChangeListener xEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xEndSpinnerModel.setNullable(ev.getNewValue() == null);
xEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
xEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
controller.setXEnd(xEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
}
});
// Create Y end label and its spinner bound to Y_END controller property
this.yEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel yEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.yEndSpinner = new NullableSpinner(yEndSpinnerModel);
yEndSpinnerModel.setNullable(controller.getYEnd() == null);
yEndSpinnerModel.setLength(controller.getYEnd());
final PropertyChangeListener yEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
yEndSpinnerModel.setNullable(ev.getNewValue() == null);
yEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
yEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
controller.setYEnd(yEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
}
});
// Create distance to end point label and its spinner bound to DISTANCE_TO_END_POINT controller property
this.distanceToEndPointLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "distanceToEndPointLabel.text", unitName));
float minimumLength = preferences.getLengthUnit().getMinimumLength();
final NullableSpinner.NullableSpinnerLengthModel distanceToEndPointSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, 2 * maximumLength * (float)Math.sqrt(2));
this.distanceToEndPointSpinner = new NullableSpinner(distanceToEndPointSpinnerModel);
distanceToEndPointSpinnerModel.setNullable(controller.getLength() == null);
- distanceToEndPointSpinnerModel.setLength(controller.getLength());
+ distanceToEndPointSpinnerModel.setLength(controller.getDistanceToEndPoint());
final PropertyChangeListener distanceToEndPointChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
distanceToEndPointSpinnerModel.setNullable(ev.getNewValue() == null);
distanceToEndPointSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
distanceToEndPointSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
- controller.setLength(distanceToEndPointSpinnerModel.getLength());
+ controller.setDistanceToEndPoint(distanceToEndPointSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
}
});
// Left side color and texture buttons bound to left side controller properties
this.leftSideColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideColorRadioButton.text"));
this.leftSideColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideColorRadioButton.isSelected()) {
controller.setLeftSidePaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateLeftSideColorRadioButtons(controller);
}
});
this.leftSideColorButton = new ColorButton(preferences);
this.leftSideColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "leftSideColorDialog.title"));
this.leftSideColorButton.setColor(controller.getLeftSideColor());
this.leftSideColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setLeftSideColor(leftSideColorButton.getColor());
controller.setLeftSidePaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
leftSideColorButton.setColor(controller.getLeftSideColor());
}
});
this.leftSideTextureRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideTextureRadioButton.text"));
this.leftSideTextureRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideTextureRadioButton.isSelected()) {
controller.setLeftSidePaint(WallController.WallPaint.TEXTURED);
}
}
});
this.leftSideTextureComponent = (JComponent)controller.getLeftSideTextureController().getView();
ButtonGroup leftSideColorButtonGroup = new ButtonGroup();
leftSideColorButtonGroup.add(this.leftSideColorRadioButton);
leftSideColorButtonGroup.add(this.leftSideTextureRadioButton);
updateLeftSideColorRadioButtons(controller);
// Left side shininess radio buttons bound to LEFT_SIDE_SHININESS controller property
this.leftSideMattRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideMattRadioButton.text"));
this.leftSideMattRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideMattRadioButton.isSelected()) {
controller.setLeftSideShininess(0f);
}
}
});
PropertyChangeListener leftSideShininessListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateLeftSideShininessRadioButtons(controller);
}
};
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_SHININESS,
leftSideShininessListener);
this.leftSideShinyRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideShinyRadioButton.text"));
this.leftSideShinyRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideShinyRadioButton.isSelected()) {
controller.setLeftSideShininess(0.25f);
}
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_SHININESS,
leftSideShininessListener);
ButtonGroup leftSideShininessButtonGroup = new ButtonGroup();
leftSideShininessButtonGroup.add(this.leftSideMattRadioButton);
leftSideShininessButtonGroup.add(this.leftSideShinyRadioButton);
updateLeftSideShininessRadioButtons(controller);
// Right side color and texture buttons bound to right side controller properties
this.rightSideColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideColorRadioButton.text"));
this.rightSideColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (rightSideColorRadioButton.isSelected()) {
controller.setRightSidePaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateRightSideColorRadioButtons(controller);
}
});
this.rightSideColorButton = new ColorButton(preferences);
this.rightSideColorButton.setColor(controller.getRightSideColor());
this.rightSideColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "rightSideColorDialog.title"));
this.rightSideColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setRightSideColor(rightSideColorButton.getColor());
controller.setRightSidePaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
rightSideColorButton.setColor(controller.getRightSideColor());
}
});
this.rightSideTextureRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideTextureRadioButton.text"));
this.rightSideTextureRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (rightSideTextureRadioButton.isSelected()) {
controller.setRightSidePaint(WallController.WallPaint.TEXTURED);
}
}
});
this.rightSideTextureComponent = (JComponent)controller.getRightSideTextureController().getView();
ButtonGroup rightSideColorButtonGroup = new ButtonGroup();
rightSideColorButtonGroup.add(this.rightSideColorRadioButton);
rightSideColorButtonGroup.add(this.rightSideTextureRadioButton);
updateRightSideColorRadioButtons(controller);
// Right side shininess radio buttons bound to LEFT_SIDE_SHININESS controller property
this.rightSideMattRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideMattRadioButton.text"));
this.rightSideMattRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rightSideMattRadioButton.isSelected()) {
controller.setRightSideShininess(0f);
}
}
});
PropertyChangeListener rightSideShininessListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateRightSideShininessRadioButtons(controller);
}
};
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_SHININESS,
rightSideShininessListener);
this.rightSideShinyRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideShinyRadioButton.text"));
this.rightSideShinyRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rightSideShinyRadioButton.isSelected()) {
controller.setRightSideShininess(0.25f);
}
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_SHININESS,
rightSideShininessListener);
ButtonGroup rightSideShininessButtonGroup = new ButtonGroup();
rightSideShininessButtonGroup.add(this.rightSideMattRadioButton);
rightSideShininessButtonGroup.add(this.rightSideShinyRadioButton);
updateRightSideShininessRadioButtons(controller);
// Top pattern and 3D color
this.patternLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "patternLabel.text"));
List<TextureImage> patterns = preferences.getPatternsCatalog().getPatterns();
if (controller.getPattern() == null) {
patterns = new ArrayList<TextureImage>(patterns);
patterns.add(0, null);
}
this.patternComboBox = new JComboBox(new DefaultComboBoxModel(patterns.toArray()));
this.patternComboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(final JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TextureImage pattern = (TextureImage)value;
final Component component = super.getListCellRendererComponent(
list, pattern == null ? " " : "", index, isSelected, cellHasFocus);
if (pattern != null) {
final BufferedImage patternImage = SwingTools.getPatternImage(
pattern, list.getBackground(), list.getForeground());
setIcon(new Icon() {
public int getIconWidth() {
return patternImage.getWidth() * 4 + 1;
}
public int getIconHeight() {
return patternImage.getHeight() + 2;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2D = (Graphics2D)g;
for (int i = 0; i < 4; i++) {
g2D.drawImage(patternImage, x + i * patternImage.getWidth(), y + 1, list);
}
g2D.setColor(list.getForeground());
g2D.drawRect(x, y, getIconWidth() - 2, getIconHeight() - 1);
}
});
}
return component;
}
});
this.patternComboBox.setSelectedItem(controller.getPattern());
this.patternComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
controller.setPattern((TextureImage)patternComboBox.getSelectedItem());
}
});
controller.addPropertyChangeListener(WallController.Property.PATTERN,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
patternComboBox.setSelectedItem(controller.getPattern());
}
});
this.topColorLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topColorLabel.text"));
this.topDefaultColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topDefaultColorRadioButton.text"));
this.topDefaultColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (topDefaultColorRadioButton.isSelected()) {
controller.setTopPaint(WallController.WallPaint.DEFAULT);
}
}
});
this.topColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topColorRadioButton.text"));
this.topColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (topColorRadioButton.isSelected()) {
controller.setTopPaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.TOP_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateTopColorRadioButtons(controller);
}
});
this.topColorButton = new ColorButton(preferences);
this.topColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "topColorDialog.title"));
this.topColorButton.setColor(controller.getTopColor());
this.topColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setTopColor(topColorButton.getColor());
controller.setTopPaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.TOP_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
topColorButton.setColor(controller.getTopColor());
}
});
ButtonGroup topColorGroup = new ButtonGroup();
topColorGroup.add(this.topDefaultColorRadioButton);
topColorGroup.add(this.topColorRadioButton);
updateTopColorRadioButtons(controller);
// Create height label and its spinner bound to RECTANGULAR_WALL_HEIGHT controller property
this.rectangularWallRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rectangularWallRadioButton.text"));
this.rectangularWallRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rectangularWallRadioButton.isSelected()) {
controller.setShape(WallController.WallShape.RECTANGULAR_WALL);
}
}
});
controller.addPropertyChangeListener(WallController.Property.SHAPE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateWallShapeRadioButtons(controller);
}
});
this.rectangularWallHeightLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rectangularWallHeightLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel rectangularWallHeightSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.rectangularWallHeightSpinner = new NullableSpinner(rectangularWallHeightSpinnerModel);
rectangularWallHeightSpinnerModel.setNullable(controller.getRectangularWallHeight() == null);
rectangularWallHeightSpinnerModel.setLength(controller.getRectangularWallHeight());
final PropertyChangeListener rectangularWallHeightChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
rectangularWallHeightSpinnerModel.setNullable(ev.getNewValue() == null);
rectangularWallHeightSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
rectangularWallHeightSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
controller.setRectangularWallHeight(rectangularWallHeightSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
}
});
this.slopingWallRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallRadioButton.text"));
this.slopingWallRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (slopingWallRadioButton.isSelected()) {
controller.setShape(WallController.WallShape.SLOPING_WALL);
}
}
});
ButtonGroup wallHeightButtonGroup = new ButtonGroup();
wallHeightButtonGroup.add(this.rectangularWallRadioButton);
wallHeightButtonGroup.add(this.slopingWallRadioButton);
updateWallShapeRadioButtons(controller);
// Create height at start label and its spinner bound to SLOPING_WALL_HEIGHT_AT_START controller property
this.slopingWallHeightAtStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallHeightAtStartLabel.text"));
final NullableSpinner.NullableSpinnerLengthModel slopingWallHeightAtStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.slopingWallHeightAtStartSpinner = new NullableSpinner(slopingWallHeightAtStartSpinnerModel);
slopingWallHeightAtStartSpinnerModel.setNullable(controller.getSlopingWallHeightAtStart() == null);
slopingWallHeightAtStartSpinnerModel.setLength(controller.getSlopingWallHeightAtStart());
final PropertyChangeListener slopingWallHeightAtStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
slopingWallHeightAtStartSpinnerModel.setNullable(ev.getNewValue() == null);
slopingWallHeightAtStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
slopingWallHeightAtStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
controller.setSlopingWallHeightAtStart(slopingWallHeightAtStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
}
});
// Create height at end label and its spinner bound to SLOPING_WALL_HEIGHT_AT_END controller property
this.slopingWallHeightAtEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallHeightAtEndLabel.text"));
final NullableSpinner.NullableSpinnerLengthModel slopingWallHeightAtEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.slopingWallHeightAtEndSpinner = new NullableSpinner(slopingWallHeightAtEndSpinnerModel);
slopingWallHeightAtEndSpinnerModel.setNullable(controller.getSlopingWallHeightAtEnd() == null);
slopingWallHeightAtEndSpinnerModel.setLength(controller.getSlopingWallHeightAtEnd());
final PropertyChangeListener slopingWallHeightAtEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
slopingWallHeightAtEndSpinnerModel.setNullable(ev.getNewValue() == null);
slopingWallHeightAtEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
slopingWallHeightAtEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
controller.setSlopingWallHeightAtEnd(slopingWallHeightAtEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
}
});
// Create thickness label and its spinner bound to THICKNESS controller property
this.thicknessLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "thicknessLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel thicknessSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength / 10);
this.thicknessSpinner = new NullableSpinner(thicknessSpinnerModel);
thicknessSpinnerModel.setNullable(controller.getThickness() == null);
thicknessSpinnerModel.setLength(controller.getThickness());
final PropertyChangeListener thicknessChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
thicknessSpinnerModel.setNullable(ev.getNewValue() == null);
thicknessSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
thicknessSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
controller.setThickness(thicknessSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
}
});
// Create arc extent label and its spinner bound to ARC_EXTENT_IN_DEGREES controller property
this.arcExtentLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "arcExtentLabel.text", unitName));
final NullableSpinner.NullableSpinnerNumberModel arcExtentSpinnerModel =
new NullableSpinner.NullableSpinnerNumberModel(new Float(0), new Float(-270), new Float(270), new Float(5));
this.arcExtentSpinner = new NullableSpinner(arcExtentSpinnerModel);
arcExtentSpinnerModel.setNullable(controller.getArcExtentInDegrees() == null);
arcExtentSpinnerModel.setValue(controller.getArcExtentInDegrees());
final PropertyChangeListener arcExtentChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
arcExtentSpinnerModel.setNullable(ev.getNewValue() == null);
arcExtentSpinnerModel.setValue(((Number)ev.getNewValue()).floatValue());
}
};
controller.addPropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
arcExtentSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
controller.setArcExtentInDegrees(((Number)arcExtentSpinnerModel.getValue()).floatValue());
controller.addPropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
}
});
// wallOrientationLabel shows an HTML explanation of wall orientation with an image URL in resource
this.wallOrientationLabel = new JLabel(preferences.getLocalizedString(
WallPanel.class, "wallOrientationLabel.text",
new ResourceURLContent(WallPanel.class, "resources/wallOrientation.png").getURL()),
JLabel.CENTER);
// Use same font for label as tooltips
this.wallOrientationLabel.setFont(UIManager.getFont("ToolTip.font"));
this.dialogTitle = preferences.getLocalizedString(WallPanel.class, "wall.title");
}
/**
* Updates left side color radio buttons.
*/
private void updateLeftSideColorRadioButtons(WallController controller) {
if (controller.getLeftSidePaint() == WallController.WallPaint.COLORED) {
this.leftSideColorRadioButton.setSelected(true);
} else if (controller.getLeftSidePaint() == WallController.WallPaint.TEXTURED) {
this.leftSideTextureRadioButton.setSelected(true);
} else { // null
SwingTools.deselectAllRadioButtons(this.leftSideColorRadioButton, this.leftSideTextureRadioButton);
}
}
/**
* Updates left side shininess radio buttons.
*/
private void updateLeftSideShininessRadioButtons(WallController controller) {
if (controller.getLeftSideShininess() == null) {
SwingTools.deselectAllRadioButtons(this.leftSideMattRadioButton, this.leftSideShinyRadioButton);
} else if (controller.getLeftSideShininess() == 0) {
this.leftSideMattRadioButton.setSelected(true);
} else { // null
this.leftSideShinyRadioButton.setSelected(true);
}
}
/**
* Updates right side color radio buttons.
*/
private void updateRightSideColorRadioButtons(WallController controller) {
if (controller.getRightSidePaint() == WallController.WallPaint.COLORED) {
this.rightSideColorRadioButton.setSelected(true);
} else if (controller.getRightSidePaint() == WallController.WallPaint.TEXTURED) {
this.rightSideTextureRadioButton.setSelected(true);
} else { // null
SwingTools.deselectAllRadioButtons(this.rightSideColorRadioButton, this.rightSideTextureRadioButton);
}
}
/**
* Updates right side shininess radio buttons.
*/
private void updateRightSideShininessRadioButtons(WallController controller) {
if (controller.getRightSideShininess() == null) {
SwingTools.deselectAllRadioButtons(this.rightSideMattRadioButton, this.rightSideShinyRadioButton);
} else if (controller.getRightSideShininess() == 0) {
this.rightSideMattRadioButton.setSelected(true);
} else { // null
this.rightSideShinyRadioButton.setSelected(true);
}
}
/**
* Updates top color radio buttons.
*/
private void updateTopColorRadioButtons(WallController controller) {
if (controller.getTopPaint() == WallController.WallPaint.COLORED) {
this.topColorRadioButton.setSelected(true);
} else if (controller.getTopPaint() == WallController.WallPaint.DEFAULT) {
this.topDefaultColorRadioButton.setSelected(true);
} else { // null
SwingTools.deselectAllRadioButtons(this.topColorRadioButton, this.topDefaultColorRadioButton);
}
}
/**
* Updates rectangular and sloping wall radio buttons.
*/
private void updateWallShapeRadioButtons(WallController controller) {
if (controller.getShape() == WallController.WallShape.SLOPING_WALL) {
this.slopingWallRadioButton.setSelected(true);
} else if (controller.getShape() == WallController.WallShape.RECTANGULAR_WALL) {
this.rectangularWallRadioButton.setSelected(true);
} else { // null
SwingTools.deselectAllRadioButtons(this.slopingWallRadioButton, this.rectangularWallRadioButton);
}
}
/**
* Sets components mnemonics and label / component associations.
*/
private void setMnemonics(UserPreferences preferences) {
if (!OperatingSystem.isMacOSX()) {
this.xStartLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "xLabel.mnemonic")).getKeyCode());
this.xStartLabel.setLabelFor(this.xStartSpinner);
this.yStartLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "yLabel.mnemonic")).getKeyCode());
this.yStartLabel.setLabelFor(this.yStartSpinner);
this.xEndLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "xLabel.mnemonic")).getKeyCode());
this.xEndLabel.setLabelFor(this.xEndSpinner);
this.yEndLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "yLabel.mnemonic")).getKeyCode());
this.yEndLabel.setLabelFor(this.yEndSpinner);
this.distanceToEndPointLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "distanceToEndPointLabel.mnemonic")).getKeyCode());
this.distanceToEndPointLabel.setLabelFor(this.distanceToEndPointSpinner);
this.leftSideColorRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "leftSideColorRadioButton.mnemonic")).getKeyCode());
this.leftSideTextureRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "leftSideTextureRadioButton.mnemonic")).getKeyCode());
this.leftSideMattRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "leftSideMattRadioButton.mnemonic")).getKeyCode());
this.leftSideShinyRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "leftSideShinyRadioButton.mnemonic")).getKeyCode());
this.rightSideColorRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "rightSideColorRadioButton.mnemonic")).getKeyCode());
this.rightSideTextureRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "rightSideTextureRadioButton.mnemonic")).getKeyCode());
this.rightSideMattRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "rightSideMattRadioButton.mnemonic")).getKeyCode());
this.rightSideShinyRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "rightSideShinyRadioButton.mnemonic")).getKeyCode());
this.patternLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
WallPanel.class, "patternLabel.mnemonic")).getKeyCode());
this.patternLabel.setLabelFor(this.patternComboBox);
this.topDefaultColorRadioButton.setMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
WallPanel.class,"topDefaultColorRadioButton.mnemonic")).getKeyCode());
this.topColorRadioButton.setMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
WallPanel.class,"topColorRadioButton.mnemonic")).getKeyCode());
this.rectangularWallRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "rectangularWallRadioButton.mnemonic")).getKeyCode());
this.rectangularWallHeightLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "rectangularWallHeightLabel.mnemonic")).getKeyCode());
this.rectangularWallHeightLabel.setLabelFor(this.rectangularWallHeightSpinner);
this.slopingWallRadioButton.setMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "slopingWallRadioButton.mnemonic")).getKeyCode());
this.slopingWallHeightAtStartLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "slopingWallHeightAtStartLabel.mnemonic")).getKeyCode());
this.slopingWallHeightAtStartLabel.setLabelFor(this.slopingWallHeightAtStartSpinner);
this.slopingWallHeightAtEndLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "slopingWallHeightAtEndLabel.mnemonic")).getKeyCode());
this.slopingWallHeightAtEndLabel.setLabelFor(this.slopingWallHeightAtEndSpinner);
this.thicknessLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "thicknessLabel.mnemonic")).getKeyCode());
this.thicknessLabel.setLabelFor(this.thicknessSpinner);
this.arcExtentLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(
preferences.getLocalizedString(WallPanel.class, "arcExtentLabel.mnemonic")).getKeyCode());
this.arcExtentLabel.setLabelFor(this.arcExtentSpinner);
}
}
/**
* Layouts panel components in panel with their labels.
*/
private void layoutComponents(UserPreferences preferences,
final WallController controller) {
int labelAlignment = OperatingSystem.isMacOSX()
? GridBagConstraints.LINE_END
: GridBagConstraints.LINE_START;
// First row
final JPanel startPointPanel = createTitledPanel(
preferences.getLocalizedString(WallPanel.class, "startPointPanel.title"),
new JComponent [] {this.xStartLabel, this.xStartSpinner,
this.yStartLabel, this.yStartSpinner}, true);
Insets rowInsets;
if (OperatingSystem.isMacOSXLeopardOrSuperior()) {
// User smaller insets for Mac OS X 10.5
rowInsets = new Insets(0, 0, 0, 0);
} else {
rowInsets = new Insets(0, 0, 5, 0);
}
add(startPointPanel, new GridBagConstraints(
0, 0, 2, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, rowInsets, 0, 0));
// Second row
final JPanel endPointPanel = createTitledPanel(
preferences.getLocalizedString(WallPanel.class, "endPointPanel.title"),
new JComponent [] {this.xEndLabel, this.xEndSpinner,
this.yEndLabel, this.yEndSpinner}, true);
// Add distance label and spinner at the end of second row of endPointPanel
endPointPanel.add(this.distanceToEndPointLabel, new GridBagConstraints(
0, 1, 3, 1, 1, 0, GridBagConstraints.LINE_END,
GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
endPointPanel.add(this.distanceToEndPointSpinner, new GridBagConstraints(
3, 1, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
add(endPointPanel, new GridBagConstraints(
0, 1, 2, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, rowInsets, 0, 0));
// Third row
JPanel leftSidePanel = createTitledPanel(
preferences.getLocalizedString(WallPanel.class, "leftSidePanel.title"),
new JComponent [] {this.leftSideColorRadioButton, this.leftSideColorButton,
this.leftSideTextureRadioButton, this.leftSideTextureComponent}, false);
leftSidePanel.add(new JSeparator(), new GridBagConstraints(
0, 2, 2, 1, 1, 0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(3, 0, 3, 0), 0, 0));
leftSidePanel.add(this.leftSideMattRadioButton, new GridBagConstraints(
0, 3, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
leftSidePanel.add(this.leftSideShinyRadioButton, new GridBagConstraints(
1, 3, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
add(leftSidePanel, new GridBagConstraints(
0, 2, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, rowInsets, 0, 0));
JPanel rightSidePanel = createTitledPanel(
preferences.getLocalizedString(WallPanel.class, "rightSidePanel.title"),
new JComponent [] {this.rightSideColorRadioButton, this.rightSideColorButton,
this.rightSideTextureRadioButton, this.rightSideTextureComponent}, false);
rightSidePanel.add(new JSeparator(), new GridBagConstraints(
0, 2, 2, 1, 1, 0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(3, 0, 3, 0), 0, 0));
rightSidePanel.add(this.rightSideMattRadioButton, new GridBagConstraints(
0, 3, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
rightSidePanel.add(this.rightSideShinyRadioButton, new GridBagConstraints(
1, 3, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
add(rightSidePanel, new GridBagConstraints(
1, 2, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, rowInsets, 0, 0));
// Forth row
JPanel topPanel = SwingTools.createTitledPanel(preferences.getLocalizedString(
WallPanel.class, "topPanel.title"));
int leftInset = new JRadioButton().getPreferredSize().width;
topPanel.add(this.patternLabel, new GridBagConstraints(
0, 0, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, leftInset, 3, 5), 0, 0));
topPanel.add(this.patternComboBox, new GridBagConstraints(
1, 0, 3, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 3, 0), 0, 0));
topPanel.add(this.topColorLabel, new GridBagConstraints(
0, 1, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, leftInset, 0, 5), 0, 0));
topPanel.add(this.topDefaultColorRadioButton, new GridBagConstraints(
1, 1, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
topPanel.add(this.topColorRadioButton, new GridBagConstraints(
2, 1, 1, 1, 0, 0, GridBagConstraints.LINE_END,
GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
topPanel.add(this.topColorButton, new GridBagConstraints(
3, 1, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
add(topPanel, new GridBagConstraints(
0, 3, 2, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, rowInsets, 0, 0));
// Fifth row
JPanel heightPanel = SwingTools.createTitledPanel(
preferences.getLocalizedString(WallPanel.class, "heightPanel.title"));
// First row of height panel
heightPanel.add(this.rectangularWallRadioButton, new GridBagConstraints(
0, 0, 5, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 2, 0), 0, 0));
// Second row of height panel
// Add a dummy label to align second and fourth row on radio buttons text
heightPanel.add(new JLabel(), new GridBagConstraints(
0, 1, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 5, 0), new JRadioButton().getPreferredSize().width + 2, 0));
heightPanel.add(this.rectangularWallHeightLabel, new GridBagConstraints(
1, 1, 1, 1, 1, 0, labelAlignment,
GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
heightPanel.add(this.rectangularWallHeightSpinner, new GridBagConstraints(
2, 1, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), -10, 0));
// Third row of height panel
heightPanel.add(this.slopingWallRadioButton, new GridBagConstraints(
0, 2, 5, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 2, 0), 0, 0));
// Fourth row of height panel
heightPanel.add(this.slopingWallHeightAtStartLabel, new GridBagConstraints(
1, 3, 1, 1, 1, 0, labelAlignment,
GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
heightPanel.add(this.slopingWallHeightAtStartSpinner, new GridBagConstraints(
2, 3, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5), -10, 0));
heightPanel.add(this.slopingWallHeightAtEndLabel, new GridBagConstraints(
3, 3, 1, 1, 1, 0, labelAlignment,
GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
heightPanel.add(this.slopingWallHeightAtEndSpinner, new GridBagConstraints(
4, 3, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), -10, 0));
add(heightPanel, new GridBagConstraints(
0, 4, 2, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, rowInsets, 0, 0));
// Sixth row
JPanel ticknessAndArcExtentPanel = new JPanel(new GridBagLayout());
ticknessAndArcExtentPanel.add(this.thicknessLabel, new GridBagConstraints(
0, 0, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5), 0, 0));
ticknessAndArcExtentPanel.add(this.thicknessSpinner, new GridBagConstraints(
1, 0, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
ticknessAndArcExtentPanel.add(this.arcExtentLabel, new GridBagConstraints(
2, 0, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5), 0, 0));
ticknessAndArcExtentPanel.add(this.arcExtentSpinner, new GridBagConstraints(
3, 0, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
add(ticknessAndArcExtentPanel, new GridBagConstraints(
0, 5, 2, 1, 0, 0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(5, 8, 10, 8), 0, 0));
// Last row
add(this.wallOrientationLabel, new GridBagConstraints(
0, 6, 2, 1, 0, 0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
// Make startPointPanel and endPointPanel visible depending on editable points property
controller.addPropertyChangeListener(WallController.Property.EDITABLE_POINTS,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
startPointPanel.setVisible(controller.isEditablePoints());
endPointPanel.setVisible(controller.isEditablePoints());
arcExtentLabel.setVisible(controller.isEditablePoints());
arcExtentSpinner.setVisible(controller.isEditablePoints());
}
});
startPointPanel.setVisible(controller.isEditablePoints());
endPointPanel.setVisible(controller.isEditablePoints());
this.arcExtentLabel.setVisible(controller.isEditablePoints());
this.arcExtentSpinner.setVisible(controller.isEditablePoints());
}
private JPanel createTitledPanel(String title, JComponent [] components, boolean horizontal) {
JPanel titledPanel = SwingTools.createTitledPanel(title);
if (horizontal) {
int labelAlignment = OperatingSystem.isMacOSX()
? GridBagConstraints.LINE_END
: GridBagConstraints.LINE_START;
Insets labelInsets = new Insets(0, 0, 0, 5);
Insets insets = new Insets(0, 0, 0, 5);
for (int i = 0; i < components.length - 1; i += 2) {
titledPanel.add(components [i], new GridBagConstraints(
i, 0, 1, 1, 1, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
titledPanel.add(components [i + 1], new GridBagConstraints(
i + 1, 0, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, insets, 0, 0));
}
titledPanel.add(components [components.length - 1], new GridBagConstraints(
components.length - 1, 0, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
} else {
for (int i = 0; i < components.length; i += 2) {
int bottomInset = i < components.length - 2 ? 2 : 0;
titledPanel.add(components [i], new GridBagConstraints(
0, i / 2, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE,
new Insets(0, 0, bottomInset , 5), 0, 0));
titledPanel.add(components [i + 1], new GridBagConstraints(
1, i / 2, 1, 1, 1, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, bottomInset, 0), 0, 0));
}
}
return titledPanel;
}
/**
* Displays this panel in a modal dialog box.
*/
public void displayView(View parentView) {
Component homeRoot = SwingUtilities.getRoot((Component)parentView);
if (homeRoot != null) {
JOptionPane optionPane = new JOptionPane(this,
JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JComponent parentComponent = SwingUtilities.getRootPane((JComponent)parentView);
if (parentView != null) {
optionPane.setComponentOrientation(parentComponent.getComponentOrientation());
}
JDialog dialog = optionPane.createDialog(parentComponent, this.dialogTitle);
Dimension screenSize = getToolkit().getScreenSize();
Insets screenInsets = getToolkit().getScreenInsets(getGraphicsConfiguration());
// Check dialog isn't too high
int screenHeight = screenSize.height - screenInsets.top - screenInsets.bottom;
if (OperatingSystem.isLinux() && screenHeight == screenSize.height) {
// Let's consider that under Linux at least an horizontal bar exists
screenHeight -= 30;
}
if (dialog.getHeight() > screenHeight) {
this.wallOrientationLabel.setVisible(false);
}
dialog.pack();
if (dialog.getHeight() > screenHeight) {
this.patternLabel.getParent().setVisible(false);
}
dialog.dispose();
}
JFormattedTextField thicknessTextField =
((JSpinner.DefaultEditor)thicknessSpinner.getEditor()).getTextField();
if (SwingTools.showConfirmDialog((JComponent)parentView,
this, this.dialogTitle, thicknessTextField) == JOptionPane.OK_OPTION) {
this.controller.modifyWalls();
}
}
}
| false | true | private void createComponents(UserPreferences preferences,
final WallController controller) {
// Get unit name matching current unit
String unitName = preferences.getLengthUnit().getName();
// Create X start label and its spinner bound to X_START controller property
this.xStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "xLabel.text", unitName));
final float maximumLength = preferences.getLengthUnit().getMaximumLength();
final NullableSpinner.NullableSpinnerLengthModel xStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.xStartSpinner = new NullableSpinner(xStartSpinnerModel);
xStartSpinnerModel.setNullable(controller.getXStart() == null);
xStartSpinnerModel.setLength(controller.getXStart());
final PropertyChangeListener xStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xStartSpinnerModel.setNullable(ev.getNewValue() == null);
xStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
xStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
controller.setXStart(xStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
}
});
// Create Y start label and its spinner bound to Y_START controller property
this.yStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel yStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.yStartSpinner = new NullableSpinner(yStartSpinnerModel);
yStartSpinnerModel.setNullable(controller.getYStart() == null);
yStartSpinnerModel.setLength(controller.getYStart());
final PropertyChangeListener yStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
yStartSpinnerModel.setNullable(ev.getNewValue() == null);
yStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
yStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
controller.setYStart(yStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
}
});
// Create X end label and its spinner bound to X_END controller property
this.xEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "xLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel xEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.xEndSpinner = new NullableSpinner(xEndSpinnerModel);
xEndSpinnerModel.setNullable(controller.getXEnd() == null);
xEndSpinnerModel.setLength(controller.getXEnd());
final PropertyChangeListener xEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xEndSpinnerModel.setNullable(ev.getNewValue() == null);
xEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
xEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
controller.setXEnd(xEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
}
});
// Create Y end label and its spinner bound to Y_END controller property
this.yEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel yEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.yEndSpinner = new NullableSpinner(yEndSpinnerModel);
yEndSpinnerModel.setNullable(controller.getYEnd() == null);
yEndSpinnerModel.setLength(controller.getYEnd());
final PropertyChangeListener yEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
yEndSpinnerModel.setNullable(ev.getNewValue() == null);
yEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
yEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
controller.setYEnd(yEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
}
});
// Create distance to end point label and its spinner bound to DISTANCE_TO_END_POINT controller property
this.distanceToEndPointLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "distanceToEndPointLabel.text", unitName));
float minimumLength = preferences.getLengthUnit().getMinimumLength();
final NullableSpinner.NullableSpinnerLengthModel distanceToEndPointSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, 2 * maximumLength * (float)Math.sqrt(2));
this.distanceToEndPointSpinner = new NullableSpinner(distanceToEndPointSpinnerModel);
distanceToEndPointSpinnerModel.setNullable(controller.getLength() == null);
distanceToEndPointSpinnerModel.setLength(controller.getLength());
final PropertyChangeListener distanceToEndPointChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
distanceToEndPointSpinnerModel.setNullable(ev.getNewValue() == null);
distanceToEndPointSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
distanceToEndPointSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
controller.setLength(distanceToEndPointSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
}
});
// Left side color and texture buttons bound to left side controller properties
this.leftSideColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideColorRadioButton.text"));
this.leftSideColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideColorRadioButton.isSelected()) {
controller.setLeftSidePaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateLeftSideColorRadioButtons(controller);
}
});
this.leftSideColorButton = new ColorButton(preferences);
this.leftSideColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "leftSideColorDialog.title"));
this.leftSideColorButton.setColor(controller.getLeftSideColor());
this.leftSideColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setLeftSideColor(leftSideColorButton.getColor());
controller.setLeftSidePaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
leftSideColorButton.setColor(controller.getLeftSideColor());
}
});
this.leftSideTextureRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideTextureRadioButton.text"));
this.leftSideTextureRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideTextureRadioButton.isSelected()) {
controller.setLeftSidePaint(WallController.WallPaint.TEXTURED);
}
}
});
this.leftSideTextureComponent = (JComponent)controller.getLeftSideTextureController().getView();
ButtonGroup leftSideColorButtonGroup = new ButtonGroup();
leftSideColorButtonGroup.add(this.leftSideColorRadioButton);
leftSideColorButtonGroup.add(this.leftSideTextureRadioButton);
updateLeftSideColorRadioButtons(controller);
// Left side shininess radio buttons bound to LEFT_SIDE_SHININESS controller property
this.leftSideMattRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideMattRadioButton.text"));
this.leftSideMattRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideMattRadioButton.isSelected()) {
controller.setLeftSideShininess(0f);
}
}
});
PropertyChangeListener leftSideShininessListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateLeftSideShininessRadioButtons(controller);
}
};
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_SHININESS,
leftSideShininessListener);
this.leftSideShinyRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideShinyRadioButton.text"));
this.leftSideShinyRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideShinyRadioButton.isSelected()) {
controller.setLeftSideShininess(0.25f);
}
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_SHININESS,
leftSideShininessListener);
ButtonGroup leftSideShininessButtonGroup = new ButtonGroup();
leftSideShininessButtonGroup.add(this.leftSideMattRadioButton);
leftSideShininessButtonGroup.add(this.leftSideShinyRadioButton);
updateLeftSideShininessRadioButtons(controller);
// Right side color and texture buttons bound to right side controller properties
this.rightSideColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideColorRadioButton.text"));
this.rightSideColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (rightSideColorRadioButton.isSelected()) {
controller.setRightSidePaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateRightSideColorRadioButtons(controller);
}
});
this.rightSideColorButton = new ColorButton(preferences);
this.rightSideColorButton.setColor(controller.getRightSideColor());
this.rightSideColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "rightSideColorDialog.title"));
this.rightSideColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setRightSideColor(rightSideColorButton.getColor());
controller.setRightSidePaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
rightSideColorButton.setColor(controller.getRightSideColor());
}
});
this.rightSideTextureRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideTextureRadioButton.text"));
this.rightSideTextureRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (rightSideTextureRadioButton.isSelected()) {
controller.setRightSidePaint(WallController.WallPaint.TEXTURED);
}
}
});
this.rightSideTextureComponent = (JComponent)controller.getRightSideTextureController().getView();
ButtonGroup rightSideColorButtonGroup = new ButtonGroup();
rightSideColorButtonGroup.add(this.rightSideColorRadioButton);
rightSideColorButtonGroup.add(this.rightSideTextureRadioButton);
updateRightSideColorRadioButtons(controller);
// Right side shininess radio buttons bound to LEFT_SIDE_SHININESS controller property
this.rightSideMattRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideMattRadioButton.text"));
this.rightSideMattRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rightSideMattRadioButton.isSelected()) {
controller.setRightSideShininess(0f);
}
}
});
PropertyChangeListener rightSideShininessListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateRightSideShininessRadioButtons(controller);
}
};
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_SHININESS,
rightSideShininessListener);
this.rightSideShinyRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideShinyRadioButton.text"));
this.rightSideShinyRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rightSideShinyRadioButton.isSelected()) {
controller.setRightSideShininess(0.25f);
}
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_SHININESS,
rightSideShininessListener);
ButtonGroup rightSideShininessButtonGroup = new ButtonGroup();
rightSideShininessButtonGroup.add(this.rightSideMattRadioButton);
rightSideShininessButtonGroup.add(this.rightSideShinyRadioButton);
updateRightSideShininessRadioButtons(controller);
// Top pattern and 3D color
this.patternLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "patternLabel.text"));
List<TextureImage> patterns = preferences.getPatternsCatalog().getPatterns();
if (controller.getPattern() == null) {
patterns = new ArrayList<TextureImage>(patterns);
patterns.add(0, null);
}
this.patternComboBox = new JComboBox(new DefaultComboBoxModel(patterns.toArray()));
this.patternComboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(final JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TextureImage pattern = (TextureImage)value;
final Component component = super.getListCellRendererComponent(
list, pattern == null ? " " : "", index, isSelected, cellHasFocus);
if (pattern != null) {
final BufferedImage patternImage = SwingTools.getPatternImage(
pattern, list.getBackground(), list.getForeground());
setIcon(new Icon() {
public int getIconWidth() {
return patternImage.getWidth() * 4 + 1;
}
public int getIconHeight() {
return patternImage.getHeight() + 2;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2D = (Graphics2D)g;
for (int i = 0; i < 4; i++) {
g2D.drawImage(patternImage, x + i * patternImage.getWidth(), y + 1, list);
}
g2D.setColor(list.getForeground());
g2D.drawRect(x, y, getIconWidth() - 2, getIconHeight() - 1);
}
});
}
return component;
}
});
this.patternComboBox.setSelectedItem(controller.getPattern());
this.patternComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
controller.setPattern((TextureImage)patternComboBox.getSelectedItem());
}
});
controller.addPropertyChangeListener(WallController.Property.PATTERN,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
patternComboBox.setSelectedItem(controller.getPattern());
}
});
this.topColorLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topColorLabel.text"));
this.topDefaultColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topDefaultColorRadioButton.text"));
this.topDefaultColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (topDefaultColorRadioButton.isSelected()) {
controller.setTopPaint(WallController.WallPaint.DEFAULT);
}
}
});
this.topColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topColorRadioButton.text"));
this.topColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (topColorRadioButton.isSelected()) {
controller.setTopPaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.TOP_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateTopColorRadioButtons(controller);
}
});
this.topColorButton = new ColorButton(preferences);
this.topColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "topColorDialog.title"));
this.topColorButton.setColor(controller.getTopColor());
this.topColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setTopColor(topColorButton.getColor());
controller.setTopPaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.TOP_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
topColorButton.setColor(controller.getTopColor());
}
});
ButtonGroup topColorGroup = new ButtonGroup();
topColorGroup.add(this.topDefaultColorRadioButton);
topColorGroup.add(this.topColorRadioButton);
updateTopColorRadioButtons(controller);
// Create height label and its spinner bound to RECTANGULAR_WALL_HEIGHT controller property
this.rectangularWallRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rectangularWallRadioButton.text"));
this.rectangularWallRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rectangularWallRadioButton.isSelected()) {
controller.setShape(WallController.WallShape.RECTANGULAR_WALL);
}
}
});
controller.addPropertyChangeListener(WallController.Property.SHAPE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateWallShapeRadioButtons(controller);
}
});
this.rectangularWallHeightLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rectangularWallHeightLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel rectangularWallHeightSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.rectangularWallHeightSpinner = new NullableSpinner(rectangularWallHeightSpinnerModel);
rectangularWallHeightSpinnerModel.setNullable(controller.getRectangularWallHeight() == null);
rectangularWallHeightSpinnerModel.setLength(controller.getRectangularWallHeight());
final PropertyChangeListener rectangularWallHeightChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
rectangularWallHeightSpinnerModel.setNullable(ev.getNewValue() == null);
rectangularWallHeightSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
rectangularWallHeightSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
controller.setRectangularWallHeight(rectangularWallHeightSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
}
});
this.slopingWallRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallRadioButton.text"));
this.slopingWallRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (slopingWallRadioButton.isSelected()) {
controller.setShape(WallController.WallShape.SLOPING_WALL);
}
}
});
ButtonGroup wallHeightButtonGroup = new ButtonGroup();
wallHeightButtonGroup.add(this.rectangularWallRadioButton);
wallHeightButtonGroup.add(this.slopingWallRadioButton);
updateWallShapeRadioButtons(controller);
// Create height at start label and its spinner bound to SLOPING_WALL_HEIGHT_AT_START controller property
this.slopingWallHeightAtStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallHeightAtStartLabel.text"));
final NullableSpinner.NullableSpinnerLengthModel slopingWallHeightAtStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.slopingWallHeightAtStartSpinner = new NullableSpinner(slopingWallHeightAtStartSpinnerModel);
slopingWallHeightAtStartSpinnerModel.setNullable(controller.getSlopingWallHeightAtStart() == null);
slopingWallHeightAtStartSpinnerModel.setLength(controller.getSlopingWallHeightAtStart());
final PropertyChangeListener slopingWallHeightAtStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
slopingWallHeightAtStartSpinnerModel.setNullable(ev.getNewValue() == null);
slopingWallHeightAtStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
slopingWallHeightAtStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
controller.setSlopingWallHeightAtStart(slopingWallHeightAtStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
}
});
// Create height at end label and its spinner bound to SLOPING_WALL_HEIGHT_AT_END controller property
this.slopingWallHeightAtEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallHeightAtEndLabel.text"));
final NullableSpinner.NullableSpinnerLengthModel slopingWallHeightAtEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.slopingWallHeightAtEndSpinner = new NullableSpinner(slopingWallHeightAtEndSpinnerModel);
slopingWallHeightAtEndSpinnerModel.setNullable(controller.getSlopingWallHeightAtEnd() == null);
slopingWallHeightAtEndSpinnerModel.setLength(controller.getSlopingWallHeightAtEnd());
final PropertyChangeListener slopingWallHeightAtEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
slopingWallHeightAtEndSpinnerModel.setNullable(ev.getNewValue() == null);
slopingWallHeightAtEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
slopingWallHeightAtEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
controller.setSlopingWallHeightAtEnd(slopingWallHeightAtEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
}
});
// Create thickness label and its spinner bound to THICKNESS controller property
this.thicknessLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "thicknessLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel thicknessSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength / 10);
this.thicknessSpinner = new NullableSpinner(thicknessSpinnerModel);
thicknessSpinnerModel.setNullable(controller.getThickness() == null);
thicknessSpinnerModel.setLength(controller.getThickness());
final PropertyChangeListener thicknessChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
thicknessSpinnerModel.setNullable(ev.getNewValue() == null);
thicknessSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
thicknessSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
controller.setThickness(thicknessSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
}
});
// Create arc extent label and its spinner bound to ARC_EXTENT_IN_DEGREES controller property
this.arcExtentLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "arcExtentLabel.text", unitName));
final NullableSpinner.NullableSpinnerNumberModel arcExtentSpinnerModel =
new NullableSpinner.NullableSpinnerNumberModel(new Float(0), new Float(-270), new Float(270), new Float(5));
this.arcExtentSpinner = new NullableSpinner(arcExtentSpinnerModel);
arcExtentSpinnerModel.setNullable(controller.getArcExtentInDegrees() == null);
arcExtentSpinnerModel.setValue(controller.getArcExtentInDegrees());
final PropertyChangeListener arcExtentChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
arcExtentSpinnerModel.setNullable(ev.getNewValue() == null);
arcExtentSpinnerModel.setValue(((Number)ev.getNewValue()).floatValue());
}
};
controller.addPropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
arcExtentSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
controller.setArcExtentInDegrees(((Number)arcExtentSpinnerModel.getValue()).floatValue());
controller.addPropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
}
});
// wallOrientationLabel shows an HTML explanation of wall orientation with an image URL in resource
this.wallOrientationLabel = new JLabel(preferences.getLocalizedString(
WallPanel.class, "wallOrientationLabel.text",
new ResourceURLContent(WallPanel.class, "resources/wallOrientation.png").getURL()),
JLabel.CENTER);
// Use same font for label as tooltips
this.wallOrientationLabel.setFont(UIManager.getFont("ToolTip.font"));
this.dialogTitle = preferences.getLocalizedString(WallPanel.class, "wall.title");
}
| private void createComponents(UserPreferences preferences,
final WallController controller) {
// Get unit name matching current unit
String unitName = preferences.getLengthUnit().getName();
// Create X start label and its spinner bound to X_START controller property
this.xStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "xLabel.text", unitName));
final float maximumLength = preferences.getLengthUnit().getMaximumLength();
final NullableSpinner.NullableSpinnerLengthModel xStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.xStartSpinner = new NullableSpinner(xStartSpinnerModel);
xStartSpinnerModel.setNullable(controller.getXStart() == null);
xStartSpinnerModel.setLength(controller.getXStart());
final PropertyChangeListener xStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xStartSpinnerModel.setNullable(ev.getNewValue() == null);
xStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
xStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
controller.setXStart(xStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.X_START, xStartChangeListener);
}
});
// Create Y start label and its spinner bound to Y_START controller property
this.yStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel yStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.yStartSpinner = new NullableSpinner(yStartSpinnerModel);
yStartSpinnerModel.setNullable(controller.getYStart() == null);
yStartSpinnerModel.setLength(controller.getYStart());
final PropertyChangeListener yStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
yStartSpinnerModel.setNullable(ev.getNewValue() == null);
yStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
yStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
controller.setYStart(yStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.Y_START, yStartChangeListener);
}
});
// Create X end label and its spinner bound to X_END controller property
this.xEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "xLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel xEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.xEndSpinner = new NullableSpinner(xEndSpinnerModel);
xEndSpinnerModel.setNullable(controller.getXEnd() == null);
xEndSpinnerModel.setLength(controller.getXEnd());
final PropertyChangeListener xEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xEndSpinnerModel.setNullable(ev.getNewValue() == null);
xEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
xEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
controller.setXEnd(xEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.X_END, xEndChangeListener);
}
});
// Create Y end label and its spinner bound to Y_END controller property
this.yEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel yEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -maximumLength, maximumLength);
this.yEndSpinner = new NullableSpinner(yEndSpinnerModel);
yEndSpinnerModel.setNullable(controller.getYEnd() == null);
yEndSpinnerModel.setLength(controller.getYEnd());
final PropertyChangeListener yEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
yEndSpinnerModel.setNullable(ev.getNewValue() == null);
yEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
yEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
controller.setYEnd(yEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.Y_END, yEndChangeListener);
}
});
// Create distance to end point label and its spinner bound to DISTANCE_TO_END_POINT controller property
this.distanceToEndPointLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "distanceToEndPointLabel.text", unitName));
float minimumLength = preferences.getLengthUnit().getMinimumLength();
final NullableSpinner.NullableSpinnerLengthModel distanceToEndPointSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, 2 * maximumLength * (float)Math.sqrt(2));
this.distanceToEndPointSpinner = new NullableSpinner(distanceToEndPointSpinnerModel);
distanceToEndPointSpinnerModel.setNullable(controller.getLength() == null);
distanceToEndPointSpinnerModel.setLength(controller.getDistanceToEndPoint());
final PropertyChangeListener distanceToEndPointChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
distanceToEndPointSpinnerModel.setNullable(ev.getNewValue() == null);
distanceToEndPointSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
distanceToEndPointSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
controller.setDistanceToEndPoint(distanceToEndPointSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.DISTANCE_TO_END_POINT,
distanceToEndPointChangeListener);
}
});
// Left side color and texture buttons bound to left side controller properties
this.leftSideColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideColorRadioButton.text"));
this.leftSideColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideColorRadioButton.isSelected()) {
controller.setLeftSidePaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateLeftSideColorRadioButtons(controller);
}
});
this.leftSideColorButton = new ColorButton(preferences);
this.leftSideColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "leftSideColorDialog.title"));
this.leftSideColorButton.setColor(controller.getLeftSideColor());
this.leftSideColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setLeftSideColor(leftSideColorButton.getColor());
controller.setLeftSidePaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
leftSideColorButton.setColor(controller.getLeftSideColor());
}
});
this.leftSideTextureRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideTextureRadioButton.text"));
this.leftSideTextureRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideTextureRadioButton.isSelected()) {
controller.setLeftSidePaint(WallController.WallPaint.TEXTURED);
}
}
});
this.leftSideTextureComponent = (JComponent)controller.getLeftSideTextureController().getView();
ButtonGroup leftSideColorButtonGroup = new ButtonGroup();
leftSideColorButtonGroup.add(this.leftSideColorRadioButton);
leftSideColorButtonGroup.add(this.leftSideTextureRadioButton);
updateLeftSideColorRadioButtons(controller);
// Left side shininess radio buttons bound to LEFT_SIDE_SHININESS controller property
this.leftSideMattRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideMattRadioButton.text"));
this.leftSideMattRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideMattRadioButton.isSelected()) {
controller.setLeftSideShininess(0f);
}
}
});
PropertyChangeListener leftSideShininessListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateLeftSideShininessRadioButtons(controller);
}
};
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_SHININESS,
leftSideShininessListener);
this.leftSideShinyRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "leftSideShinyRadioButton.text"));
this.leftSideShinyRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (leftSideShinyRadioButton.isSelected()) {
controller.setLeftSideShininess(0.25f);
}
}
});
controller.addPropertyChangeListener(WallController.Property.LEFT_SIDE_SHININESS,
leftSideShininessListener);
ButtonGroup leftSideShininessButtonGroup = new ButtonGroup();
leftSideShininessButtonGroup.add(this.leftSideMattRadioButton);
leftSideShininessButtonGroup.add(this.leftSideShinyRadioButton);
updateLeftSideShininessRadioButtons(controller);
// Right side color and texture buttons bound to right side controller properties
this.rightSideColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideColorRadioButton.text"));
this.rightSideColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (rightSideColorRadioButton.isSelected()) {
controller.setRightSidePaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateRightSideColorRadioButtons(controller);
}
});
this.rightSideColorButton = new ColorButton(preferences);
this.rightSideColorButton.setColor(controller.getRightSideColor());
this.rightSideColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "rightSideColorDialog.title"));
this.rightSideColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setRightSideColor(rightSideColorButton.getColor());
controller.setRightSidePaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
rightSideColorButton.setColor(controller.getRightSideColor());
}
});
this.rightSideTextureRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideTextureRadioButton.text"));
this.rightSideTextureRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (rightSideTextureRadioButton.isSelected()) {
controller.setRightSidePaint(WallController.WallPaint.TEXTURED);
}
}
});
this.rightSideTextureComponent = (JComponent)controller.getRightSideTextureController().getView();
ButtonGroup rightSideColorButtonGroup = new ButtonGroup();
rightSideColorButtonGroup.add(this.rightSideColorRadioButton);
rightSideColorButtonGroup.add(this.rightSideTextureRadioButton);
updateRightSideColorRadioButtons(controller);
// Right side shininess radio buttons bound to LEFT_SIDE_SHININESS controller property
this.rightSideMattRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideMattRadioButton.text"));
this.rightSideMattRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rightSideMattRadioButton.isSelected()) {
controller.setRightSideShininess(0f);
}
}
});
PropertyChangeListener rightSideShininessListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateRightSideShininessRadioButtons(controller);
}
};
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_SHININESS,
rightSideShininessListener);
this.rightSideShinyRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rightSideShinyRadioButton.text"));
this.rightSideShinyRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rightSideShinyRadioButton.isSelected()) {
controller.setRightSideShininess(0.25f);
}
}
});
controller.addPropertyChangeListener(WallController.Property.RIGHT_SIDE_SHININESS,
rightSideShininessListener);
ButtonGroup rightSideShininessButtonGroup = new ButtonGroup();
rightSideShininessButtonGroup.add(this.rightSideMattRadioButton);
rightSideShininessButtonGroup.add(this.rightSideShinyRadioButton);
updateRightSideShininessRadioButtons(controller);
// Top pattern and 3D color
this.patternLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "patternLabel.text"));
List<TextureImage> patterns = preferences.getPatternsCatalog().getPatterns();
if (controller.getPattern() == null) {
patterns = new ArrayList<TextureImage>(patterns);
patterns.add(0, null);
}
this.patternComboBox = new JComboBox(new DefaultComboBoxModel(patterns.toArray()));
this.patternComboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(final JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TextureImage pattern = (TextureImage)value;
final Component component = super.getListCellRendererComponent(
list, pattern == null ? " " : "", index, isSelected, cellHasFocus);
if (pattern != null) {
final BufferedImage patternImage = SwingTools.getPatternImage(
pattern, list.getBackground(), list.getForeground());
setIcon(new Icon() {
public int getIconWidth() {
return patternImage.getWidth() * 4 + 1;
}
public int getIconHeight() {
return patternImage.getHeight() + 2;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2D = (Graphics2D)g;
for (int i = 0; i < 4; i++) {
g2D.drawImage(patternImage, x + i * patternImage.getWidth(), y + 1, list);
}
g2D.setColor(list.getForeground());
g2D.drawRect(x, y, getIconWidth() - 2, getIconHeight() - 1);
}
});
}
return component;
}
});
this.patternComboBox.setSelectedItem(controller.getPattern());
this.patternComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
controller.setPattern((TextureImage)patternComboBox.getSelectedItem());
}
});
controller.addPropertyChangeListener(WallController.Property.PATTERN,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
patternComboBox.setSelectedItem(controller.getPattern());
}
});
this.topColorLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topColorLabel.text"));
this.topDefaultColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topDefaultColorRadioButton.text"));
this.topDefaultColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (topDefaultColorRadioButton.isSelected()) {
controller.setTopPaint(WallController.WallPaint.DEFAULT);
}
}
});
this.topColorRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "topColorRadioButton.text"));
this.topColorRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (topColorRadioButton.isSelected()) {
controller.setTopPaint(WallController.WallPaint.COLORED);
}
}
});
controller.addPropertyChangeListener(WallController.Property.TOP_PAINT,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateTopColorRadioButtons(controller);
}
});
this.topColorButton = new ColorButton(preferences);
this.topColorButton.setColorDialogTitle(preferences.getLocalizedString(
WallPanel.class, "topColorDialog.title"));
this.topColorButton.setColor(controller.getTopColor());
this.topColorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setTopColor(topColorButton.getColor());
controller.setTopPaint(WallController.WallPaint.COLORED);
}
});
controller.addPropertyChangeListener(WallController.Property.TOP_COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
topColorButton.setColor(controller.getTopColor());
}
});
ButtonGroup topColorGroup = new ButtonGroup();
topColorGroup.add(this.topDefaultColorRadioButton);
topColorGroup.add(this.topColorRadioButton);
updateTopColorRadioButtons(controller);
// Create height label and its spinner bound to RECTANGULAR_WALL_HEIGHT controller property
this.rectangularWallRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rectangularWallRadioButton.text"));
this.rectangularWallRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (rectangularWallRadioButton.isSelected()) {
controller.setShape(WallController.WallShape.RECTANGULAR_WALL);
}
}
});
controller.addPropertyChangeListener(WallController.Property.SHAPE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateWallShapeRadioButtons(controller);
}
});
this.rectangularWallHeightLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "rectangularWallHeightLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel rectangularWallHeightSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.rectangularWallHeightSpinner = new NullableSpinner(rectangularWallHeightSpinnerModel);
rectangularWallHeightSpinnerModel.setNullable(controller.getRectangularWallHeight() == null);
rectangularWallHeightSpinnerModel.setLength(controller.getRectangularWallHeight());
final PropertyChangeListener rectangularWallHeightChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
rectangularWallHeightSpinnerModel.setNullable(ev.getNewValue() == null);
rectangularWallHeightSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
rectangularWallHeightSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
controller.setRectangularWallHeight(rectangularWallHeightSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.RECTANGULAR_WALL_HEIGHT,
rectangularWallHeightChangeListener);
}
});
this.slopingWallRadioButton = new JRadioButton(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallRadioButton.text"));
this.slopingWallRadioButton.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
if (slopingWallRadioButton.isSelected()) {
controller.setShape(WallController.WallShape.SLOPING_WALL);
}
}
});
ButtonGroup wallHeightButtonGroup = new ButtonGroup();
wallHeightButtonGroup.add(this.rectangularWallRadioButton);
wallHeightButtonGroup.add(this.slopingWallRadioButton);
updateWallShapeRadioButtons(controller);
// Create height at start label and its spinner bound to SLOPING_WALL_HEIGHT_AT_START controller property
this.slopingWallHeightAtStartLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallHeightAtStartLabel.text"));
final NullableSpinner.NullableSpinnerLengthModel slopingWallHeightAtStartSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.slopingWallHeightAtStartSpinner = new NullableSpinner(slopingWallHeightAtStartSpinnerModel);
slopingWallHeightAtStartSpinnerModel.setNullable(controller.getSlopingWallHeightAtStart() == null);
slopingWallHeightAtStartSpinnerModel.setLength(controller.getSlopingWallHeightAtStart());
final PropertyChangeListener slopingWallHeightAtStartChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
slopingWallHeightAtStartSpinnerModel.setNullable(ev.getNewValue() == null);
slopingWallHeightAtStartSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
slopingWallHeightAtStartSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
controller.setSlopingWallHeightAtStart(slopingWallHeightAtStartSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_START,
slopingWallHeightAtStartChangeListener);
}
});
// Create height at end label and its spinner bound to SLOPING_WALL_HEIGHT_AT_END controller property
this.slopingWallHeightAtEndLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "slopingWallHeightAtEndLabel.text"));
final NullableSpinner.NullableSpinnerLengthModel slopingWallHeightAtEndSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength);
this.slopingWallHeightAtEndSpinner = new NullableSpinner(slopingWallHeightAtEndSpinnerModel);
slopingWallHeightAtEndSpinnerModel.setNullable(controller.getSlopingWallHeightAtEnd() == null);
slopingWallHeightAtEndSpinnerModel.setLength(controller.getSlopingWallHeightAtEnd());
final PropertyChangeListener slopingWallHeightAtEndChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
slopingWallHeightAtEndSpinnerModel.setNullable(ev.getNewValue() == null);
slopingWallHeightAtEndSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
slopingWallHeightAtEndSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
controller.setSlopingWallHeightAtEnd(slopingWallHeightAtEndSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.SLOPING_WALL_HEIGHT_AT_END,
slopingWallHeightAtEndChangeListener);
}
});
// Create thickness label and its spinner bound to THICKNESS controller property
this.thicknessLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "thicknessLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel thicknessSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, minimumLength, maximumLength / 10);
this.thicknessSpinner = new NullableSpinner(thicknessSpinnerModel);
thicknessSpinnerModel.setNullable(controller.getThickness() == null);
thicknessSpinnerModel.setLength(controller.getThickness());
final PropertyChangeListener thicknessChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
thicknessSpinnerModel.setNullable(ev.getNewValue() == null);
thicknessSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
thicknessSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
controller.setThickness(thicknessSpinnerModel.getLength());
controller.addPropertyChangeListener(WallController.Property.THICKNESS,
thicknessChangeListener);
}
});
// Create arc extent label and its spinner bound to ARC_EXTENT_IN_DEGREES controller property
this.arcExtentLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
WallPanel.class, "arcExtentLabel.text", unitName));
final NullableSpinner.NullableSpinnerNumberModel arcExtentSpinnerModel =
new NullableSpinner.NullableSpinnerNumberModel(new Float(0), new Float(-270), new Float(270), new Float(5));
this.arcExtentSpinner = new NullableSpinner(arcExtentSpinnerModel);
arcExtentSpinnerModel.setNullable(controller.getArcExtentInDegrees() == null);
arcExtentSpinnerModel.setValue(controller.getArcExtentInDegrees());
final PropertyChangeListener arcExtentChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
arcExtentSpinnerModel.setNullable(ev.getNewValue() == null);
arcExtentSpinnerModel.setValue(((Number)ev.getNewValue()).floatValue());
}
};
controller.addPropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
arcExtentSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
controller.setArcExtentInDegrees(((Number)arcExtentSpinnerModel.getValue()).floatValue());
controller.addPropertyChangeListener(WallController.Property.ARC_EXTENT_IN_DEGREES,
arcExtentChangeListener);
}
});
// wallOrientationLabel shows an HTML explanation of wall orientation with an image URL in resource
this.wallOrientationLabel = new JLabel(preferences.getLocalizedString(
WallPanel.class, "wallOrientationLabel.text",
new ResourceURLContent(WallPanel.class, "resources/wallOrientation.png").getURL()),
JLabel.CENTER);
// Use same font for label as tooltips
this.wallOrientationLabel.setFont(UIManager.getFont("ToolTip.font"));
this.dialogTitle = preferences.getLocalizedString(WallPanel.class, "wall.title");
}
|
diff --git a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPResourceLinker.java b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPResourceLinker.java
index 055f08b9..40adf2e2 100644
--- a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPResourceLinker.java
+++ b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPResourceLinker.java
@@ -1,1271 +1,1274 @@
/**
* Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below.
* 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
*
* Contributors:
* Cloudsmith
*
*/
package org.cloudsmith.geppetto.pp.dsl.linking;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_CLASSPARAMS;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_OVERRIDE;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import org.cloudsmith.geppetto.common.tracer.ITracer;
import org.cloudsmith.geppetto.pp.AttributeOperation;
import org.cloudsmith.geppetto.pp.AttributeOperations;
import org.cloudsmith.geppetto.pp.Case;
import org.cloudsmith.geppetto.pp.CaseExpression;
import org.cloudsmith.geppetto.pp.Definition;
import org.cloudsmith.geppetto.pp.ElseExpression;
import org.cloudsmith.geppetto.pp.ElseIfExpression;
import org.cloudsmith.geppetto.pp.ExprList;
import org.cloudsmith.geppetto.pp.Expression;
import org.cloudsmith.geppetto.pp.ExpressionTE;
import org.cloudsmith.geppetto.pp.FunctionCall;
import org.cloudsmith.geppetto.pp.HostClassDefinition;
import org.cloudsmith.geppetto.pp.IfExpression;
import org.cloudsmith.geppetto.pp.LiteralExpression;
import org.cloudsmith.geppetto.pp.LiteralNameOrReference;
import org.cloudsmith.geppetto.pp.NodeDefinition;
import org.cloudsmith.geppetto.pp.PPPackage;
import org.cloudsmith.geppetto.pp.ParenthesisedExpression;
import org.cloudsmith.geppetto.pp.PuppetManifest;
import org.cloudsmith.geppetto.pp.ResourceBody;
import org.cloudsmith.geppetto.pp.ResourceExpression;
import org.cloudsmith.geppetto.pp.SelectorEntry;
import org.cloudsmith.geppetto.pp.UnquotedString;
import org.cloudsmith.geppetto.pp.VariableExpression;
import org.cloudsmith.geppetto.pp.VariableTE;
import org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter;
import org.cloudsmith.geppetto.pp.adapters.ClassifierAdapterFactory;
import org.cloudsmith.geppetto.pp.dsl.PPDSLConstants;
import org.cloudsmith.geppetto.pp.dsl.adapters.PPImportedNamesAdapter;
import org.cloudsmith.geppetto.pp.dsl.adapters.PPImportedNamesAdapterFactory;
import org.cloudsmith.geppetto.pp.dsl.adapters.ResourcePropertiesAdapter;
import org.cloudsmith.geppetto.pp.dsl.adapters.ResourcePropertiesAdapterFactory;
import org.cloudsmith.geppetto.pp.dsl.contentassist.PPProposalsGenerator;
import org.cloudsmith.geppetto.pp.dsl.eval.PPStringConstantEvaluator;
import org.cloudsmith.geppetto.pp.dsl.linking.PPFinder.SearchResult;
import org.cloudsmith.geppetto.pp.dsl.linking.PPSearchPath.ISearchPathProvider;
import org.cloudsmith.geppetto.pp.dsl.validation.IPPDiagnostics;
import org.cloudsmith.geppetto.pp.dsl.validation.IValidationAdvisor;
import org.cloudsmith.geppetto.pp.dsl.validation.PPPatternHelper;
import org.cloudsmith.geppetto.pp.dsl.validation.ValidationPreference;
import org.cloudsmith.geppetto.pp.pptp.PPTPPackage;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.naming.IQualifiedNameConverter;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.internal.Lists;
import com.google.inject.name.Named;
/**
* Handles special linking of ResourceExpression, ResourceBody and Function references.
*/
public class PPResourceLinker implements IPPDiagnostics {
/**
* Access to runtime configurable debug trace.
*/
@Inject
@Named(PPDSLConstants.PP_DEBUG_LINKER)
private ITracer tracer;
/**
* Access to precompiled regular expressions
*/
@Inject
private PPPatternHelper patternHelper;
/**
* Access to the global index maintained by Xtext, is made via a special (non guice) provider
* that is aware of the context (builder, dirty editors, etc.). It is used to obtain the
* index for a particular resource. This special provider is obtained here.
*/
@Inject
private org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider indexProvider;
/**
* Classifies ResourceExpression based on its content (regular, override, etc).
*/
@Inject
private PPClassifier classifier;
/**
* PP FQN to/from Xtext QualifiedName converter.
*/
@Inject
private IQualifiedNameConverter converter;
@Inject
private PPProposalsGenerator proposer;
@Inject
private PPFinder ppFinder;
@Inject
private PPStringConstantEvaluator stringConstantEvaluator;
// Note that order is important
private final static EClass[] DEF_AND_TYPE = { PPTPPackage.Literals.TYPE, PPPackage.Literals.DEFINITION };
private static final EClass[] FUNC = { PPTPPackage.Literals.FUNCTION };
private final static EClass[] CLASS_AND_TYPE = {
PPPackage.Literals.HOST_CLASS_DEFINITION, PPTPPackage.Literals.TYPE };
private static String proposalIssue(String issue, String[] proposals) {
if(proposals == null || proposals.length == 0)
return issue;
return issue + IPPDiagnostics.ISSUE_PROPOSAL_SUFFIX;
}
private Resource resource;
@Inject
private ISearchPathProvider searchPathProvider;
private PPSearchPath searchPath;
@Inject
private Provider<IValidationAdvisor> validationAdvisorProvider;
// /**
// * Checks that a variable in the value expression tree does not reference another definition
// * argument, or variables defined inside the class body. This can only happen when the
// * value is a fully qualified name as the relative lookup already takes the scope into account.
// *
// * @param o
// * @param acceptor
// */
// private void _check(DefinitionArgument o, IMessageAcceptor acceptor) {
//
// }
private void _link(ExpressionTE o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
Expression expr = o.getExpression();
if(expr instanceof ParenthesisedExpression)
expr = ((ParenthesisedExpression) expr).getExpr();
String varName = null;
if(expr instanceof LiteralNameOrReference)
varName = ((LiteralNameOrReference) expr).getValue();
if(varName == null)
return; // it is some other type of expression - it is validated as expression
StringBuilder varName2 = new StringBuilder();
if(!varName.startsWith("$"))
varName2.append("$");
varName2.append(varName);
if(patternHelper.isVARIABLE(varName2.toString()))
internalLinkVariable(
expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, varName, importedNames, acceptor);
else
acceptor.acceptError(
"Not a valid variable name", expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE,
IPPDiagnostics.ISSUE__NOT_VARNAME);
}
/**
* polymorph {@link #link(EObject, IMessageAcceptor)}
*/
private void _link(FunctionCall o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
// if not a name, then there is nothing to link, and this error is handled
// elsewhere
if(!(o.getLeftExpr() instanceof LiteralNameOrReference))
return;
String name = ((LiteralNameOrReference) o.getLeftExpr()).getValue();
final SearchResult searchResult = ppFinder.findFunction(o, name, importedNames);
final List<IEObjectDescription> found = searchResult.getAdjusted(); // findFunction(o, name, importedNames);
if(found.size() > 0) {
// record resolution at resource level
importedNames.addResolved(found);
internalLinkFunctionArguments(name, o, importedNames, acceptor);
return; // ok, found
}
if(searchResult.getRaw().size() > 0) {
// Not a hard error, it may be valid with a different path
// not found on path, but exists somewhere in what is visible
// record resolution at resource level
importedNames.addResolved(searchResult.getRaw());
internalLinkFunctionArguments(name, o, importedNames, acceptor);
acceptor.acceptWarning("Found outside current path: '" + name + "'", o.getLeftExpr(), //
IPPDiagnostics.ISSUE__NOT_ON_PATH //
);
return; // sort of ok
}
String[] proposals = proposer.computeProposals(name, ppFinder.getExportedDescriptions(), searchPath, FUNC);
acceptor.acceptError("Unknown function: '" + name + "'", o.getLeftExpr(), //
proposalIssue(IPPDiagnostics.ISSUE__UNKNOWN_FUNCTION_REFERENCE, proposals), //
proposals);
// record failure at resource level
importedNames.addUnresolved(converter.toQualifiedName(name));
}
private void _link(HostClassDefinition o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
LiteralExpression parent = o.getParent();
if(parent == null)
return;
String parentString = null;
if(parent.eClass() == PPPackage.Literals.LITERAL_DEFAULT)
parentString = "default";
else if(parent.eClass() == PPPackage.Literals.LITERAL_NAME_OR_REFERENCE)
parentString = ((LiteralNameOrReference) parent).getValue();
if(parentString == null || parentString.length() < 1)
return;
SearchResult searchResult = ppFinder.findHostClasses(o, parentString, importedNames);
List<IEObjectDescription> descs = searchResult.getAdjusted();
if(descs.size() > 0) {
// make list only contain unique references
descs = Lists.newArrayList(Sets.newHashSet(descs));
// record resolution at resource level
importedNames.addResolved(descs);
if(descs.size() > 1) {
// this is an ambiguous link - multiple targets available and order depends on the
// order at runtime (may not be the same).
importedNames.addAmbiguous(descs);
acceptor.acceptWarning(
"Ambiguous reference to: '" + parentString + "' found in: " +
visibleResourceList(o.eResource(), descs), o,
PPPackage.Literals.HOST_CLASS_DEFINITION__PARENT,
IPPDiagnostics.ISSUE__RESOURCE_AMBIGUOUS_REFERENCE,
proposer.computeDistinctProposals(parentString, descs));
}
// must check for circularity
List<QualifiedName> visited = Lists.newArrayList();
visited.add(converter.toQualifiedName(o.getClassName()));
checkCircularInheritence(o, descs, visited, acceptor, importedNames);
}
else if(searchResult.getRaw().size() > 0) {
List<IEObjectDescription> raw = searchResult.getAdjusted();
// Sort of ok, it is not on the current path
// record resolution at resource level, so recompile knows about the dependencies
importedNames.addResolved(raw);
acceptor.acceptWarning(
"Found outside currect search path: '" + parentString + "'", o,
PPPackage.Literals.HOST_CLASS_DEFINITION__PARENT, IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
else {
// record unresolved name at resource level
importedNames.addUnresolved(converter.toQualifiedName(parentString));
// ... and finally, if there was neither a type nor a definition reference
String[] proposals = proposer.computeProposals(
parentString, ppFinder.getExportedDescriptions(), searchPath, CLASS_AND_TYPE);
acceptor.acceptError(
"Unknown class: '" + parentString + "'", o, //
PPPackage.Literals.HOST_CLASS_DEFINITION__PARENT,
proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE, proposals), //
proposals);
}
}
/**
* polymorph {@link #link(EObject, IMessageAcceptor)}
*/
private void _link(ResourceBody o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor,
boolean profileThis) {
ResourceExpression resource = (ResourceExpression) o.eContainer();
ClassifierAdapter adapter = ClassifierAdapterFactory.eINSTANCE.adapt(resource);
if(adapter.getClassifier() == ClassifierAdapter.UNKNOWN) {
classifier.classify(resource);
adapter = ClassifierAdapterFactory.eINSTANCE.adapt(resource);
}
if(adapter.getClassifier() == RESOURCE_IS_CLASSPARAMS) {
// pp: class { classname : parameter => value ... }
final String className = stringConstantEvaluator.doToString(o.getNameExpr());
if(className == null) {
acceptor.acceptError(
"Not a valid class reference", o, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
IPPDiagnostics.ISSUE__NOT_CLASSREF);
return; // not meaningful to continue
}
SearchResult searchResult = ppFinder.findHostClasses(o, className, importedNames);
List<IEObjectDescription> descs = searchResult.getAdjusted();
if(descs.size() < 1) {
if(searchResult.getRaw().size() > 0) {
// Sort of ok
importedNames.addResolved(searchResult.getRaw());
acceptor.acceptWarning(
"Found outside currect search path (parameters not validated): '" + className + "'", o,
PPPackage.Literals.RESOURCE_BODY__NAME_EXPR, IPPDiagnostics.ISSUE__NOT_ON_PATH);
return; // skip validating parameters
}
// Add unresolved info at resource level
importedNames.addUnresolved(converter.toQualifiedName(className));
String[] proposals = proposer.computeProposals(
className, ppFinder.getExportedDescriptions(), searchPath, CLASS_AND_TYPE);
acceptor.acceptError(
"Unknown class: '" + className + "'", o, //
PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE, proposals), //
proposals);
return; // not meaningful to continue (do not report errors for each "inner name")
}
if(descs.size() > 0) {
descs = Lists.newArrayList(Sets.newHashSet(descs));
// Report resolution at resource level
importedNames.addResolved(descs);
if(descs.size() > 1) {
// this is an ambiguous link - multiple targets available and order depends on the
// order at runtime (may not be the same). ISSUE: o can be a ResourceBody
importedNames.addAmbiguous(descs);
acceptor.acceptWarning(
"Ambiguous reference to: '" + className + "' found in: " +
visibleResourceList(o.eResource(), descs), o,
PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
IPPDiagnostics.ISSUE__RESOURCE_AMBIGUOUS_REFERENCE,
proposer.computeDistinctProposals(className, descs));
}
// use the first description found to find parameters
IEObjectDescription desc = descs.get(0);
AttributeOperations aos = o.getAttributes();
if(aos != null)
for(AttributeOperation ao : aos.getAttributes()) {
QualifiedName fqn = desc.getQualifiedName().append(ao.getKey());
// Accept name if there is at least one type/definition that lists the key
// NOTE/TODO: If there are other problems (multiple definitions with same name etc,
// the property could be ok in one, but not in another instance.
// finding that A'::x exists but not A''::x requires a lot more work
if(ppFinder.findAttributes(o, fqn, importedNames).getAdjusted().size() > 0)
continue; // found one such parameter == ok
String[] proposals = proposer.computeAttributeProposals(
fqn, ppFinder.getExportedDescriptions(), searchPath);
acceptor.acceptError(
"Unknown parameter: '" + ao.getKey() + "' in definition: '" + desc.getName() + "'", ao,
PPPackage.Literals.ATTRIBUTE_OPERATION__KEY,
proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_PROPERTY, proposals), proposals);
}
}
}
else if(adapter.getClassifier() == RESOURCE_IS_OVERRIDE) {
// do nothing
}
else {
// normal resource
IEObjectDescription desc = (IEObjectDescription) adapter.getTargetObjectDescription();
// do not flag undefined parameters as errors if type is unknown
if(desc != null) {
AttributeOperations aos = o.getAttributes();
List<AttributeOperation> nameVariables = Lists.newArrayList();
if(aos != null)
for(AttributeOperation ao : aos.getAttributes()) {
QualifiedName fqn = desc.getQualifiedName().append(ao.getKey());
// Accept name if there is at least one type/definition that lists the key
// NOTE/TODO: If there are other problems (multiple definitions with same name etc,
// the property could be ok in one, but not in another instance.
// finding that A'::x exists but not A''::x requires a lot more work
List<IEObjectDescription> foundAttributes = ppFinder.findAttributes(o, fqn, importedNames).getAdjusted();
// if the ao is a namevar reference, remember it so uniqueness can be validated
if(foundAttributes.size() > 0) {
if(containsNameVar(foundAttributes))
nameVariables.add(ao);
continue; // found one such parameter == ok
}
// if the reference is to "name" (and it was not found), then this is a deprecated
// reference to the namevar
if("name".equals(ao.getKey())) {
nameVariables.add(ao);
acceptor.acceptWarning(
"Deprecated use of the alias 'name' for resource name parameter. Use the type's real name variable.",
ao, PPPackage.Literals.ATTRIBUTE_OPERATION__KEY,
IPPDiagnostics.ISSUE__RESOURCE_DEPRECATED_NAME_ALIAS);
continue;
}
String[] proposals = proposer.computeAttributeProposals(
fqn, ppFinder.getExportedDescriptions(), searchPath);
acceptor.acceptError(
"Unknown parameter: '" + ao.getKey() + "' in definition: '" + desc.getName() + "'", ao,
PPPackage.Literals.ATTRIBUTE_OPERATION__KEY,
proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_PROPERTY, proposals), proposals);
}
if(nameVariables.size() > 1) {
for(AttributeOperation ao : nameVariables)
acceptor.acceptError(
"Duplicate resource name specification", ao, PPPackage.Literals.ATTRIBUTE_OPERATION__KEY,
IPPDiagnostics.ISSUE__RESOURCE_DUPLICATE_NAME_PARAMETER);
}
}
}
}
/**
* polymorph {@link #link(EObject, IMessageAcceptor)}
*/
private void _link(ResourceExpression o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
classifier.classify(o);
ClassifierAdapter adapter = ClassifierAdapterFactory.eINSTANCE.adapt(o);
int resourceType = adapter.getClassifier();
String resourceTypeName = adapter.getResourceTypeName();
// Should not really happen, but if a workspace state is maintained with old things...
if(resourceTypeName == null)
return;
// If resource is good, and not 'class', then it must have a known reference type.
// the resource type - also requires getting the type name from the override's expression).
if(resourceType == RESOURCE_IS_CLASSPARAMS) {
// resource is pp: class { classname : parameter => value }
// do nothing
}
else if(resourceType == RESOURCE_IS_OVERRIDE) {
// TODO: possibly check a resource override if the expression is constant (or it is impossible to lookup
// do nothing
}
else {
// normal resource
SearchResult searchResult = ppFinder.findDefinitions(o, resourceTypeName, importedNames);
List<IEObjectDescription> descs = searchResult.getAdjusted(); // findDefinitions(o, resourceTypeName, importedNames);
if(descs.size() > 0) {
// make list only contain unique references
descs = Lists.newArrayList(Sets.newHashSet(descs));
removeDisqualifiedContainers(descs, o);
// if any remain, pick the first type (or the first if there are no types)
IEObjectDescription usedResolution = null;
if(descs.size() > 0) {
usedResolution = getFirstTypeDescription(descs);
adapter.setTargetObject(usedResolution);
}
if(descs.size() > 1) {
// this is an ambiguous link - multiple targets available and order depends on the
// order at runtime (may not be the same).
importedNames.addAmbiguous(descs);
acceptor.acceptWarning(
"Ambiguous reference to: '" + resourceTypeName + "' found in: " +
visibleResourceList(o.eResource(), descs), o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR,
IPPDiagnostics.ISSUE__RESOURCE_AMBIGUOUS_REFERENCE,
proposer.computeDistinctProposals(resourceTypeName, descs));
}
// Add resolved information at resource level
if(usedResolution != null)
importedNames.addResolved(usedResolution);
else
importedNames.addResolved(descs);
}
else if(searchResult.getRaw().size() > 0) {
// sort of ok
importedNames.addResolved(searchResult.getRaw());
// do not record the type
acceptor.acceptWarning(
"Found outside search path: '" + resourceTypeName + "'", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
// only report unresolved if no raw (since if not found adjusted, error is reported as warning)
if(searchResult.getRaw().size() < 1) {
// ... and finally, if there was neither a type nor a definition reference
if(adapter.getResourceType() == null && adapter.getTargetObjectDescription() == null) {
// Add unresolved info at resource level
importedNames.addUnresolved(converter.toQualifiedName(resourceTypeName));
String[] proposals = proposer.computeProposals(
resourceTypeName, ppFinder.getExportedDescriptions(), searchPath, DEF_AND_TYPE);
acceptor.acceptError(
"Unknown resource type: '" + resourceTypeName + "'", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, //
proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE, proposals), //
proposals);
}
}
}
}
private void _link(VariableExpression o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
// a definition of a variable (as opposed to a reference) is a leftExpr in an assignment expression
if(o.eContainer().eClass() == PPPackage.Literals.ASSIGNMENT_EXPRESSION &&
PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR == o.eContainingFeature())
return; // is a definition
internalLinkVariable(
o, PPPackage.Literals.VARIABLE_EXPRESSION__VAR_NAME, o.getVarName(), importedNames, acceptor);
}
private void _link(VariableTE o, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
internalLinkVariable(o, PPPackage.Literals.VARIABLE_TE__VAR_NAME, o.getVarName(), importedNames, acceptor);
}
private IValidationAdvisor advisor() {
return validationAdvisorProvider.get();
}
/**
* Returns false if it is impossible that the given expression can result in a valid class
* reference at runtime.
*
* TODO: this is a really stupid way of doing "type inference", but better than nothing.
*
* @param e
* @return
*/
private boolean canBeAClassReference(Expression e) {
switch(e.eClass().getClassifierID()) {
case PPPackage.HOST_CLASS_DEFINITION:
case PPPackage.ASSIGNMENT_EXPRESSION:
case PPPackage.NODE_DEFINITION:
case PPPackage.DEFINITION:
case PPPackage.IMPORT_EXPRESSION:
case PPPackage.RELATIONAL_EXPRESSION:
case PPPackage.RESOURCE_EXPRESSION:
case PPPackage.IF_EXPRESSION:
case PPPackage.SELECTOR_EXPRESSION:
case PPPackage.AND_EXPRESSION:
case PPPackage.OR_EXPRESSION:
case PPPackage.CASE_EXPRESSION:
case PPPackage.EQUALITY_EXPRESSION:
case PPPackage.RELATIONSHIP_EXPRESSION:
return false;
}
return true;
}
private void checkCircularInheritence(HostClassDefinition o, Collection<IEObjectDescription> descs,
List<QualifiedName> stack, IMessageAcceptor acceptor, PPImportedNamesAdapter importedNames) {
for(IEObjectDescription d : descs) {
QualifiedName name = d.getName();
if(stack.contains(name)) {
// Gotcha!
acceptor.acceptError( //
"Circular inheritence", o, //
PPPackage.Literals.HOST_CLASS_DEFINITION__PARENT, //
IPPDiagnostics.ISSUE__CIRCULAR_INHERITENCE);
return; // no use continuing
}
stack.add(name);
String parentName = d.getUserData(PPDSLConstants.PARENT_NAME_DATA);
if(parentName == null || parentName.length() == 0)
continue;
SearchResult searchResult = ppFinder.findHostClasses(d.getEObjectOrProxy(), parentName, importedNames);
List<IEObjectDescription> parents = searchResult.getAdjusted(); // findHostClasses(d.getEObjectOrProxy(), parentName, importedNames);
checkCircularInheritence(o, parents, stack, acceptor, importedNames);
}
}
private boolean containsNameVar(List<IEObjectDescription> descriptions) {
for(IEObjectDescription d : descriptions)
if("true".equals(d.getUserData(PPDSLConstants.PARAMETER_NAMEVAR)))
return true;
return false;
}
private boolean containsRegularExpression(EObject o) {
if(o.eClass().getClassifierID() == PPPackage.LITERAL_REGEX)
return true;
TreeIterator<EObject> itor = o.eAllContents();
while(itor.hasNext())
if(itor.next().eClass().getClassifierID() == PPPackage.LITERAL_REGEX)
return true;
return false;
}
/**
* Returns the first type description. If none is found, the first description is returned.
*
* @param descriptions
* @return
*/
private IEObjectDescription getFirstTypeDescription(List<IEObjectDescription> descriptions) {
for(IEObjectDescription e : descriptions) {
if(e.getEClass() == PPTPPackage.Literals.TYPE)
return e;
}
return descriptions.get(0);
}
/**
* Link well known functions that must have references to defined things.
*
* @param o
* @param importedNames
* @param acceptor
*/
private void internalLinkFunctionArguments(String name, FunctionCall o, PPImportedNamesAdapter importedNames,
IMessageAcceptor acceptor) {
// have 0:M classes as arguments
if("require".equals(name) || "include".equals(name)) {
int parameterIndex = -1;
for(Expression pe : o.getParameters()) {
parameterIndex++;
String className = stringConstantEvaluator.doToString(pe);
if(className != null) {
SearchResult searchResult = ppFinder.findHostClasses(o, className, importedNames);
List<IEObjectDescription> foundClasses = searchResult.getAdjusted(); // findHostClasses(o, className, importedNames);
if(foundClasses.size() > 1) {
// ambiguous
importedNames.addAmbiguous(foundClasses);
acceptor.acceptWarning(
"Ambiguous reference to: '" + className + "' found in: " +
visibleResourceList(o.eResource(), foundClasses), o,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, parameterIndex,
IPPDiagnostics.ISSUE__RESOURCE_AMBIGUOUS_REFERENCE,
proposer.computeDistinctProposals(className, foundClasses));
}
else if(foundClasses.size() < 1) {
if(searchResult.getRaw().size() > 0) {
// sort of ok
importedNames.addResolved(searchResult.getRaw());
acceptor.acceptWarning(
"Found outside current search path: '" + className + "'", o,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, parameterIndex,
IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
else {
// not found
// record unresolved name at resource level
importedNames.addUnresolved(converter.toQualifiedName(className));
String[] p = proposer.computeProposals(
className, ppFinder.getExportedDescriptions(), searchPath, CLASS_AND_TYPE);
acceptor.acceptError(
"Unknown class: '" + className + "'", o, //
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, parameterIndex,
proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE, p), //
p);
}
}
else {
// found
importedNames.addResolved(foundClasses);
}
}
else {
// warning or error depending on if this is a reasonable class reference expr or not
if(canBeAClassReference(pe)) {
acceptor.acceptWarning(
"Can not determine until runtime if this is valid class reference", //
o, //
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, parameterIndex,
IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE);
}
else {
acceptor.acceptError(
"Not an acceptable parameter. Function '" + name + "' requires a class reference.", //
o, //
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, parameterIndex,
IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE);
}
}
}
// there should have been at least one argument
if(parameterIndex < 0) {
acceptor.acceptError("Call to '" + name + "' must have at least one argument.", o, //
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, //
IPPDiagnostics.ISSUE__REQUIRED_EXPRESSION);
}
}
}
private void internalLinkFunctionArguments(String name, LiteralNameOrReference s, EList<Expression> statements,
int idx, PPImportedNamesAdapter importedNames, IMessageAcceptor acceptor) {
// have 0:M classes as arguments
if("require".equals(name) || "include".equals(name)) {
// there should have been at least one argument
if(idx >= statements.size()) {
acceptor.acceptError("Call to '" + name + "' must have at least one argument.", s, //
PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, //
IPPDiagnostics.ISSUE__REQUIRED_EXPRESSION);
return;
}
Expression param = statements.get(idx);
List<Expression> parameterList = null;
if(param instanceof ExprList)
parameterList = ((ExprList) param).getExpressions();
else
parameterList = Lists.newArrayList(param);
int parameterIndex = -1;
for(Expression pe : parameterList) {
parameterIndex++;
String className = stringConstantEvaluator.doToString(pe);
if(className != null) {
SearchResult searchResult = ppFinder.findHostClasses(s, className, importedNames);
List<IEObjectDescription> foundClasses = searchResult.getAdjusted(); // findHostClasses(o, className, importedNames);
if(foundClasses.size() > 1) {
// ambiguous
importedNames.addAmbiguous(foundClasses);
if(param instanceof ExprList)
acceptor.acceptWarning(
"Ambiguous reference to: '" + className + "' found in: " +
visibleResourceList(s.eResource(), foundClasses), //
param, //
PPPackage.Literals.EXPR_LIST__EXPRESSIONS,
parameterIndex, //
IPPDiagnostics.ISSUE__RESOURCE_AMBIGUOUS_REFERENCE,
proposer.computeDistinctProposals(className, foundClasses));
else
acceptor.acceptWarning(
"Ambiguous reference to: '" + className + "' found in: " +
visibleResourceList(s.eResource(), foundClasses), //
param.eContainer(), param.eContainingFeature(),
idx, //
IPPDiagnostics.ISSUE__RESOURCE_AMBIGUOUS_REFERENCE,
proposer.computeDistinctProposals(className, foundClasses));
}
else if(foundClasses.size() < 1) {
if(searchResult.getRaw().size() > 0) {
// sort of ok
importedNames.addResolved(searchResult.getRaw());
if(param instanceof ExprList)
acceptor.acceptWarning(
"Found outside current search path: '" + className + "'", param,
PPPackage.Literals.EXPR_LIST__EXPRESSIONS, parameterIndex,
IPPDiagnostics.ISSUE__NOT_ON_PATH);
else
acceptor.acceptWarning("Found outside current search path: '" + className + "'", //
param.eContainer(), param.eContainingFeature(), idx, // IPPDiagnostics.ISSUE__NOT_ON_PATH);
IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
else {
// not found
// record unresolved name at resource level
importedNames.addUnresolved(converter.toQualifiedName(className));
String[] proposals = proposer.computeProposals(
className, ppFinder.getExportedDescriptions(), searchPath, CLASS_AND_TYPE);
String issueCode = proposalIssue(IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE, proposals);
if(param instanceof ExprList) {
acceptor.acceptError("Unknown class: '" + className + "'", //
param, //
PPPackage.Literals.EXPR_LIST__EXPRESSIONS, parameterIndex, //
issueCode, //
proposals);
}
else {
acceptor.acceptError("Unknown class: '" + className + "'", //
param.eContainer(), param.eContainingFeature(), idx, //
issueCode, //
proposals);
}
}
}
else {
// found
importedNames.addResolved(foundClasses);
}
}
else {
// warning or error depending on if this is a reasonable class reference expr or not
String msg = null;
boolean error = false;
if(canBeAClassReference(pe)) {
msg = "Can not determine until runtime if this is valid class reference";
}
else {
msg = "Not an acceptable parameter. Function '" + name + "' requires a class reference.";
error = true;
}
if(param instanceof ExprList)
acceptor.accept(error
? Severity.ERROR
: Severity.WARNING, msg, //
param, //
PPPackage.Literals.EXPR_LIST__EXPRESSIONS, parameterIndex, //
IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE);
else
acceptor.accept(error
? Severity.ERROR
: Severity.WARNING, msg, //
param.eContainer(), param.eContainingFeature(), idx, //
IPPDiagnostics.ISSUE__RESOURCE_UNKNOWN_TYPE);
}
}
}
}
/**
* Produces an error if the given EObject o is not contained (nested) in an expression that injects
* the result of a regular expression evaluation (i.e. $0 - $n).
* The injecting expressions are if, elseif, case (entry), case expression, and selector entry.
*
* TODO: Check if there are (less obvious) expressions
*
* @param o
* @param varName
* @param attr
* @param acceptor
*/
private void internalLinkRegexpVariable(EObject o, String varName, EAttribute attr, IMessageAcceptor acceptor) {
// upp the containment chain
for(EObject p = o.eContainer() /* , contained = o */; p != null; /* contained = p, */p = p.eContainer()) {
switch(p.eClass().getClassifierID()) {
case PPPackage.IF_EXPRESSION:
// o is either in cond, then or else part
// TODO: pedantic, check position in cond, must have regexp to the left.
if(containsRegularExpression(((IfExpression) p).getCondExpr()))
return;
break;
case PPPackage.ELSE_IF_EXPRESSION:
// o is either in cond, then or else part
// TODO: pedantic, check position in cond, must have regexp to the left.
if(containsRegularExpression(((ElseIfExpression) p).getCondExpr()))
return;
break;
case PPPackage.SELECTOR_ENTRY:
// TODO: pedantic, check position in leftExpr, must have regexp to the left.
if(containsRegularExpression(((SelectorEntry) p).getLeftExpr()))
return;
break;
// TODO: CHECK IF THIS ISOTHERIC CASE IS SUPPORTED
// case PPPackage.SELECTOR_EXPRESSION:
// if(containsRegularExpression(((SelectorExpression)p).get))
// return;
// break;
case PPPackage.CASE:
// i.e. case expr { v0, v1, v2 : statements }
for(EObject v : ((Case) p).getValues())
if(containsRegularExpression(v))
return;
break;
case PPPackage.CASE_EXPRESSION:
// TODO: Investigate if this is allowed i.e.:
// case $α =~ /regexp { true : $a = $0; false : $a = $0 }
if(containsRegularExpression(((CaseExpression) p).getSwitchExpr()))
return;
break;
}
}
acceptor.acceptWarning(
"Corresponding regular expression not found. Value of '" + varName +
"' can only be undefined at this point: '" + varName + "'", o, attr,
IPPDiagnostics.ISSUE__UNKNOWN_REGEXP);
}
/**
* Links/validates unparenthesized function calls.
*
* @param statements
* @param acceptor
*/
private void internalLinkUnparenthesisedCall(EList<Expression> statements, PPImportedNamesAdapter importedNames,
IMessageAcceptor acceptor) {
if(statements == null || statements.size() == 0)
return;
each_top: for(int i = 0; i < statements.size(); i++) {
Expression s = statements.get(i);
// -- may be a non parenthesized function call
if(s instanceof LiteralNameOrReference) {
// there must be one more expression in the list (a single argument, or
// an Expression list
// TODO: different issue, can be fixed by adding "()" if this is a function call without
// parameters, but difficult as validator does not know if function exists (would need
// an adapter to be able to pick this up in validation).
if((i + 1) >= statements.size()) {
continue each_top; // error reported by validation.
}
// the next expression is consumed as a single arg, or an expr list
// TODO: if there are expressions that can not be used as arguments check them here
i++;
// Expression arg = statements.get(i); // not used yet...
String name = ((LiteralNameOrReference) s).getValue();
SearchResult searchResult = ppFinder.findFunction(s, name, importedNames);
if(searchResult.getAdjusted().size() > 0 || searchResult.getRaw().size() > 0) {
internalLinkFunctionArguments(
name, (LiteralNameOrReference) s, statements, i, importedNames, acceptor);
if(searchResult.getAdjusted().size() < 1)
acceptor.acceptWarning("Found outside current path: '" + name + "'", s, //
IPPDiagnostics.ISSUE__NOT_ON_PATH);
continue each_top; // ok, found
}
String[] proposals = proposer.computeProposals(
name, ppFinder.getExportedDescriptions(), searchPath, FUNC);
acceptor.acceptError(
"Unknown function: '" + name + "'", s, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE,
proposalIssue(IPPDiagnostics.ISSUE__UNKNOWN_FUNCTION_REFERENCE, proposals), //
proposals);
continue each_top;
}
}
}
private void internalLinkVariable(EObject o, EAttribute attr, String varName, PPImportedNamesAdapter importedNames,
IMessageAcceptor acceptor) {
boolean qualified = false;
boolean global = false;
boolean disqualified = false;
QualifiedName qName = null;
SearchResult searchResult = null;
boolean existsAdjusted = false; // variable found as stated
boolean existsOutside = false; // if not found, reflects if found outside search path
try {
qName = converter.toQualifiedName(varName);
if(patternHelper.isDECIMALVAR(varName)) {
internalLinkRegexpVariable(o, varName, attr, acceptor);
return;
}
qualified = qName.getSegmentCount() > 1;
global = qName.getFirstSegment().length() == 0;
searchResult = ppFinder.findVariable(o, qName, importedNames);
// remove all references to not yet initialized variables
disqualified = (0 != removeDisqualifiedVariables(searchResult.getRaw(), o));
if(disqualified) // adjusted can not have disqualified entries if raw did not have them
removeDisqualifiedVariables(searchResult.getAdjusted(), o);
existsAdjusted = searchResult.getAdjusted().size() > 0;
existsOutside = existsAdjusted
? false // we are not interested in that it may be both adjusted and raw
: searchResult.getRaw().size() > 0;
}
catch(IllegalArgumentException iae) {
// Can happen if there is something seriously wrong with the qualified name, should be caught by
// validation - just ignore it here
return;
}
IValidationAdvisor advisor = advisor();
boolean mustExist = true;
if(qualified && global) { // && !(existsAdjusted || existsOutside)) {
// TODO: Possible future improvement when more global variables are known.
// if reported as error now, almost all global variables would be flagged as errors.
// Future enhancement could warn about those that are not found (resolved at runtime).
mustExist = false;
}
// Record facts at resource level about where variable was found
if(existsAdjusted)
importedNames.addResolved(searchResult.getAdjusted());
else if(existsOutside)
importedNames.addResolved(searchResult.getRaw());
if(mustExist) {
if(!(existsAdjusted || existsOutside)) {
importedNames.addUnresolved(qName);
// found nowhere
if(qualified || advisor.unqualifiedVariables().isWarningOrError()) {
StringBuilder message = new StringBuilder();
if(disqualified)
message.append("Reference to not yet initialized variable");
else
message.append(qualified
? "Unknown variable: '"
: "Unqualified and Unknown variable: '");
message.append(varName);
message.append("'");
String issue = disqualified
? IPPDiagnostics.ISSUE__UNINITIALIZED_VARIABLE
: IPPDiagnostics.ISSUE__UNKNOWN_VARIABLE;
if(disqualified || advisor.unqualifiedVariables() == ValidationPreference.ERROR)
acceptor.acceptError(message.toString(), o, attr, issue);
else
acceptor.acceptWarning(message.toString(), o, attr, issue);
}
}
else if(!existsAdjusted && existsOutside) {
// found outside
if(qualified || advisor.unqualifiedVariables().isWarningOrError())
acceptor.acceptWarning(
"Found outside current search path variable: '" + varName + "'", o, attr,
IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
}
}
/**
* Returns true if the descriptions resource path is the same as for the given object and
* the fragment path of the given object starts with the fragment path of the description.
*
* (An alternative impl would be to first check if they are from the same resource - if so,
* it is know that this resource is loaded (since we have the given o) and it should
* be possible to search up the containment chain.
*
* @param desc
* @param o
* @return
*/
private boolean isParent(IEObjectDescription desc, EObject o) {
URI descUri = desc.getEObjectURI();
URI oUri = o.eResource().getURI();
if(!descUri.path().equals(oUri.path()))
return false;
// same resource, if desc's fragment is in at the start of the path, then o is contained
boolean result = o.eResource().getURIFragment(o).startsWith(descUri.fragment());
return result;
}
/**
* Link all resources in the model
*
* @param model
* @param acceptor
*/
public void link(EObject model, IMessageAcceptor acceptor, boolean profileThis) {
ppFinder.configure(model);
resource = model.eResource();
searchPath = searchPathProvider.get(resource);
// clear names remembered in the past
PPImportedNamesAdapter importedNames = PPImportedNamesAdapterFactory.eINSTANCE.adapt(resource);
importedNames.clear();
IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(resource);
IResourceDescription descr = descriptionIndex.getResourceDescription(resource.getURI());
if(descr == null) {
if(tracer.isTracing()) {
tracer.trace("Cleaning resource: " + resource.getURI().path());
}
return;
}
if(tracer.isTracing())
tracer.trace("Linking resource: ", resource.getURI().path(), "{");
// Need to get everything in the resource, not just the content of the PuppetManifest (as the manifest has top level
// expressions that need linking).
TreeIterator<EObject> everything = resource.getAllContents();
// it is important that ResourceExpresion are linked before ResourceBodyExpression (but that should
// be ok with the tree iterator as the bodies are contained).
while(everything.hasNext()) {
EObject o = everything.next();
EClass clazz = o.eClass();
switch(clazz.getClassifierID()) {
case PPPackage.EXPRESSION_TE:
_link((ExpressionTE) o, importedNames, acceptor);
break;
case PPPackage.VARIABLE_TE:
_link((VariableTE) o, importedNames, acceptor);
break;
case PPPackage.VARIABLE_EXPRESSION:
_link((VariableExpression) o, importedNames, acceptor);
break;
case PPPackage.RESOURCE_EXPRESSION:
_link((ResourceExpression) o, importedNames, acceptor);
break;
case PPPackage.RESOURCE_BODY:
_link((ResourceBody) o, importedNames, acceptor, profileThis);
break;
case PPPackage.FUNCTION_CALL:
_link((FunctionCall) o, importedNames, acceptor);
break;
// these are needed to link un-parenthesised function calls
case PPPackage.PUPPET_MANIFEST:
internalLinkUnparenthesisedCall(((PuppetManifest) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.IF_EXPRESSION:
internalLinkUnparenthesisedCall(((IfExpression) o).getThenStatements(), importedNames, acceptor);
break;
case PPPackage.ELSE_EXPRESSION:
internalLinkUnparenthesisedCall(((ElseExpression) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.ELSE_IF_EXPRESSION:
internalLinkUnparenthesisedCall(((ElseIfExpression) o).getThenStatements(), importedNames, acceptor);
break;
case PPPackage.NODE_DEFINITION:
internalLinkUnparenthesisedCall(((NodeDefinition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.DEFINITION:
internalLinkUnparenthesisedCall(((Definition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.CASE:
internalLinkUnparenthesisedCall(((Case) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.HOST_CLASS_DEFINITION:
_link((HostClassDefinition) o, importedNames, acceptor);
internalLinkUnparenthesisedCall(((HostClassDefinition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.UNQUOTED_STRING:
Expression expr = ((UnquotedString) o).getExpression();
if(expr != null && expr instanceof LiteralNameOrReference) {
//
String varName = ((LiteralNameOrReference) expr).getValue();
StringBuilder varName2 = new StringBuilder();
if(!varName.startsWith("$"))
varName2.append("$");
varName2.append(varName);
if(patternHelper.isVARIABLE(varName2.toString()))
internalLinkVariable(
expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, varName, importedNames,
acceptor);
else
acceptor.acceptError(
"Not a valid variable name", expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE,
IPPDiagnostics.ISSUE__NOT_VARNAME);
}
break;
// case PPPackage.DEFINITION_ARGUMENT:
// _check((DefinitionArgument) o, acceptor);
// break;
}
}
if(tracer.isTracing())
tracer.trace("}");
}
/**
* Surgically remove all disqualified descriptions (those that are HostClass and a container
* of the given object 'o'.
*
* @param descs
* @param o
*/
private void removeDisqualifiedContainers(List<IEObjectDescription> descs, EObject o) {
if(descs == null)
return;
ListIterator<IEObjectDescription> litor = descs.listIterator();
while(litor.hasNext()) {
IEObjectDescription x = litor.next();
if(x.getEClass() == PPPackage.Literals.DEFINITION || !isParent(x, o))
continue;
litor.remove();
}
}
/**
* Remove variables/entries that are not yet initialized. These are the values
* defined in the same name and type if the variable is contained in a definition argument
*
* <p>
* e.g. in define selfref($selfa = $selfref::selfa, $selfb=$selfa::x) { $x=10 } none of the references to selfa, or x are disqualified.
*
* @param descs
* @param o
* @return the number of disqualified variables removed from the list
*/
private int removeDisqualifiedVariables(List<IEObjectDescription> descs, EObject o) {
if(descs == null || descs.size() == 0)
return 0;
EObject p = o;
while(p != null && p.eClass().getClassifierID() != PPPackage.DEFINITION_ARGUMENT)
p = p.eContainer();
if(p == null)
return 0; // not in a definition argument value tree
// p is a DefinitionArgument at this point, we want it's parent being an abstract Definition
EObject d = p.eContainer();
if(d == null)
return 0; // broken model
d = d.eContainer();
final String definitionFragment = d.eResource().getURIFragment(d);
+ final String definitionURI = d.eResource().getURI().toString();
int removedCount = 0;
ListIterator<IEObjectDescription> litor = descs.listIterator();
while(litor.hasNext()) {
IEObjectDescription x = litor.next();
- if(x.getEObjectURI().fragment().startsWith(definitionFragment)) {
+ URI xURI = x.getEObjectURI();
+ // if in the same resource, and contain by the same EObject
+ if(xURI.toString().startsWith(definitionURI) && xURI.fragment().startsWith(definitionFragment)) {
litor.remove();
removedCount++;
}
}
return removedCount;
}
/**
* Collects the (unique) set of resource paths and returns a message with <=5 (+ ... and x others).
*
* @param descriptors
* @return
*/
private String visibleResourceList(Resource r, List<IEObjectDescription> descriptors) {
ResourcePropertiesAdapter adapter = ResourcePropertiesAdapterFactory.eINSTANCE.adapt(r);
URI root = (URI) adapter.get(PPDSLConstants.RESOURCE_PROPERTY__ROOT_URI);
// collect the (unique) resource paths
List<String> resources = Lists.newArrayList();
for(IEObjectDescription d : descriptors) {
URI uri = EcoreUtil.getURI(d.getEObjectOrProxy());
if(root != null) {
uri = uri.deresolve(root.appendSegment(""));
}
boolean isPptpResource = "pptp".equals(uri.fileExtension());
String path = isPptpResource
? uri.lastSegment().replace(".pptp", "")
: uri.devicePath();
if(!resources.contains(path))
resources.add(path);
}
StringBuffer buf = new StringBuffer();
buf.append(resources.size());
buf.append(" resource");
buf.append(resources.size() > 1
? "s ["
: " [");
int count = 0;
// if there are 4 include all, else limit to 3 - typically 2 (fresh user mistake) or is *many*
final int countCap = resources.size() == 4
? 4
: 3;
for(String s : resources) {
if(count > 0)
buf.append(", ");
buf.append(s);
if(count++ > countCap) {
buf.append("and ");
buf.append(resources.size() - countCap);
buf.append(" other files...");
break;
}
}
buf.append("]");
return buf.toString();
}
}
| false | true | private void internalLinkVariable(EObject o, EAttribute attr, String varName, PPImportedNamesAdapter importedNames,
IMessageAcceptor acceptor) {
boolean qualified = false;
boolean global = false;
boolean disqualified = false;
QualifiedName qName = null;
SearchResult searchResult = null;
boolean existsAdjusted = false; // variable found as stated
boolean existsOutside = false; // if not found, reflects if found outside search path
try {
qName = converter.toQualifiedName(varName);
if(patternHelper.isDECIMALVAR(varName)) {
internalLinkRegexpVariable(o, varName, attr, acceptor);
return;
}
qualified = qName.getSegmentCount() > 1;
global = qName.getFirstSegment().length() == 0;
searchResult = ppFinder.findVariable(o, qName, importedNames);
// remove all references to not yet initialized variables
disqualified = (0 != removeDisqualifiedVariables(searchResult.getRaw(), o));
if(disqualified) // adjusted can not have disqualified entries if raw did not have them
removeDisqualifiedVariables(searchResult.getAdjusted(), o);
existsAdjusted = searchResult.getAdjusted().size() > 0;
existsOutside = existsAdjusted
? false // we are not interested in that it may be both adjusted and raw
: searchResult.getRaw().size() > 0;
}
catch(IllegalArgumentException iae) {
// Can happen if there is something seriously wrong with the qualified name, should be caught by
// validation - just ignore it here
return;
}
IValidationAdvisor advisor = advisor();
boolean mustExist = true;
if(qualified && global) { // && !(existsAdjusted || existsOutside)) {
// TODO: Possible future improvement when more global variables are known.
// if reported as error now, almost all global variables would be flagged as errors.
// Future enhancement could warn about those that are not found (resolved at runtime).
mustExist = false;
}
// Record facts at resource level about where variable was found
if(existsAdjusted)
importedNames.addResolved(searchResult.getAdjusted());
else if(existsOutside)
importedNames.addResolved(searchResult.getRaw());
if(mustExist) {
if(!(existsAdjusted || existsOutside)) {
importedNames.addUnresolved(qName);
// found nowhere
if(qualified || advisor.unqualifiedVariables().isWarningOrError()) {
StringBuilder message = new StringBuilder();
if(disqualified)
message.append("Reference to not yet initialized variable");
else
message.append(qualified
? "Unknown variable: '"
: "Unqualified and Unknown variable: '");
message.append(varName);
message.append("'");
String issue = disqualified
? IPPDiagnostics.ISSUE__UNINITIALIZED_VARIABLE
: IPPDiagnostics.ISSUE__UNKNOWN_VARIABLE;
if(disqualified || advisor.unqualifiedVariables() == ValidationPreference.ERROR)
acceptor.acceptError(message.toString(), o, attr, issue);
else
acceptor.acceptWarning(message.toString(), o, attr, issue);
}
}
else if(!existsAdjusted && existsOutside) {
// found outside
if(qualified || advisor.unqualifiedVariables().isWarningOrError())
acceptor.acceptWarning(
"Found outside current search path variable: '" + varName + "'", o, attr,
IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
}
}
/**
* Returns true if the descriptions resource path is the same as for the given object and
* the fragment path of the given object starts with the fragment path of the description.
*
* (An alternative impl would be to first check if they are from the same resource - if so,
* it is know that this resource is loaded (since we have the given o) and it should
* be possible to search up the containment chain.
*
* @param desc
* @param o
* @return
*/
private boolean isParent(IEObjectDescription desc, EObject o) {
URI descUri = desc.getEObjectURI();
URI oUri = o.eResource().getURI();
if(!descUri.path().equals(oUri.path()))
return false;
// same resource, if desc's fragment is in at the start of the path, then o is contained
boolean result = o.eResource().getURIFragment(o).startsWith(descUri.fragment());
return result;
}
/**
* Link all resources in the model
*
* @param model
* @param acceptor
*/
public void link(EObject model, IMessageAcceptor acceptor, boolean profileThis) {
ppFinder.configure(model);
resource = model.eResource();
searchPath = searchPathProvider.get(resource);
// clear names remembered in the past
PPImportedNamesAdapter importedNames = PPImportedNamesAdapterFactory.eINSTANCE.adapt(resource);
importedNames.clear();
IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(resource);
IResourceDescription descr = descriptionIndex.getResourceDescription(resource.getURI());
if(descr == null) {
if(tracer.isTracing()) {
tracer.trace("Cleaning resource: " + resource.getURI().path());
}
return;
}
if(tracer.isTracing())
tracer.trace("Linking resource: ", resource.getURI().path(), "{");
// Need to get everything in the resource, not just the content of the PuppetManifest (as the manifest has top level
// expressions that need linking).
TreeIterator<EObject> everything = resource.getAllContents();
// it is important that ResourceExpresion are linked before ResourceBodyExpression (but that should
// be ok with the tree iterator as the bodies are contained).
while(everything.hasNext()) {
EObject o = everything.next();
EClass clazz = o.eClass();
switch(clazz.getClassifierID()) {
case PPPackage.EXPRESSION_TE:
_link((ExpressionTE) o, importedNames, acceptor);
break;
case PPPackage.VARIABLE_TE:
_link((VariableTE) o, importedNames, acceptor);
break;
case PPPackage.VARIABLE_EXPRESSION:
_link((VariableExpression) o, importedNames, acceptor);
break;
case PPPackage.RESOURCE_EXPRESSION:
_link((ResourceExpression) o, importedNames, acceptor);
break;
case PPPackage.RESOURCE_BODY:
_link((ResourceBody) o, importedNames, acceptor, profileThis);
break;
case PPPackage.FUNCTION_CALL:
_link((FunctionCall) o, importedNames, acceptor);
break;
// these are needed to link un-parenthesised function calls
case PPPackage.PUPPET_MANIFEST:
internalLinkUnparenthesisedCall(((PuppetManifest) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.IF_EXPRESSION:
internalLinkUnparenthesisedCall(((IfExpression) o).getThenStatements(), importedNames, acceptor);
break;
case PPPackage.ELSE_EXPRESSION:
internalLinkUnparenthesisedCall(((ElseExpression) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.ELSE_IF_EXPRESSION:
internalLinkUnparenthesisedCall(((ElseIfExpression) o).getThenStatements(), importedNames, acceptor);
break;
case PPPackage.NODE_DEFINITION:
internalLinkUnparenthesisedCall(((NodeDefinition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.DEFINITION:
internalLinkUnparenthesisedCall(((Definition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.CASE:
internalLinkUnparenthesisedCall(((Case) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.HOST_CLASS_DEFINITION:
_link((HostClassDefinition) o, importedNames, acceptor);
internalLinkUnparenthesisedCall(((HostClassDefinition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.UNQUOTED_STRING:
Expression expr = ((UnquotedString) o).getExpression();
if(expr != null && expr instanceof LiteralNameOrReference) {
//
String varName = ((LiteralNameOrReference) expr).getValue();
StringBuilder varName2 = new StringBuilder();
if(!varName.startsWith("$"))
varName2.append("$");
varName2.append(varName);
if(patternHelper.isVARIABLE(varName2.toString()))
internalLinkVariable(
expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, varName, importedNames,
acceptor);
else
acceptor.acceptError(
"Not a valid variable name", expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE,
IPPDiagnostics.ISSUE__NOT_VARNAME);
}
break;
// case PPPackage.DEFINITION_ARGUMENT:
// _check((DefinitionArgument) o, acceptor);
// break;
}
}
if(tracer.isTracing())
tracer.trace("}");
}
/**
* Surgically remove all disqualified descriptions (those that are HostClass and a container
* of the given object 'o'.
*
* @param descs
* @param o
*/
private void removeDisqualifiedContainers(List<IEObjectDescription> descs, EObject o) {
if(descs == null)
return;
ListIterator<IEObjectDescription> litor = descs.listIterator();
while(litor.hasNext()) {
IEObjectDescription x = litor.next();
if(x.getEClass() == PPPackage.Literals.DEFINITION || !isParent(x, o))
continue;
litor.remove();
}
}
/**
* Remove variables/entries that are not yet initialized. These are the values
* defined in the same name and type if the variable is contained in a definition argument
*
* <p>
* e.g. in define selfref($selfa = $selfref::selfa, $selfb=$selfa::x) { $x=10 } none of the references to selfa, or x are disqualified.
*
* @param descs
* @param o
* @return the number of disqualified variables removed from the list
*/
private int removeDisqualifiedVariables(List<IEObjectDescription> descs, EObject o) {
if(descs == null || descs.size() == 0)
return 0;
EObject p = o;
while(p != null && p.eClass().getClassifierID() != PPPackage.DEFINITION_ARGUMENT)
p = p.eContainer();
if(p == null)
return 0; // not in a definition argument value tree
// p is a DefinitionArgument at this point, we want it's parent being an abstract Definition
EObject d = p.eContainer();
if(d == null)
return 0; // broken model
d = d.eContainer();
final String definitionFragment = d.eResource().getURIFragment(d);
int removedCount = 0;
ListIterator<IEObjectDescription> litor = descs.listIterator();
while(litor.hasNext()) {
IEObjectDescription x = litor.next();
if(x.getEObjectURI().fragment().startsWith(definitionFragment)) {
litor.remove();
removedCount++;
}
}
return removedCount;
}
/**
* Collects the (unique) set of resource paths and returns a message with <=5 (+ ... and x others).
*
* @param descriptors
* @return
*/
private String visibleResourceList(Resource r, List<IEObjectDescription> descriptors) {
ResourcePropertiesAdapter adapter = ResourcePropertiesAdapterFactory.eINSTANCE.adapt(r);
URI root = (URI) adapter.get(PPDSLConstants.RESOURCE_PROPERTY__ROOT_URI);
// collect the (unique) resource paths
List<String> resources = Lists.newArrayList();
for(IEObjectDescription d : descriptors) {
URI uri = EcoreUtil.getURI(d.getEObjectOrProxy());
if(root != null) {
uri = uri.deresolve(root.appendSegment(""));
}
boolean isPptpResource = "pptp".equals(uri.fileExtension());
String path = isPptpResource
? uri.lastSegment().replace(".pptp", "")
: uri.devicePath();
if(!resources.contains(path))
resources.add(path);
}
StringBuffer buf = new StringBuffer();
buf.append(resources.size());
buf.append(" resource");
buf.append(resources.size() > 1
? "s ["
: " [");
int count = 0;
// if there are 4 include all, else limit to 3 - typically 2 (fresh user mistake) or is *many*
final int countCap = resources.size() == 4
? 4
: 3;
for(String s : resources) {
if(count > 0)
buf.append(", ");
buf.append(s);
if(count++ > countCap) {
buf.append("and ");
buf.append(resources.size() - countCap);
buf.append(" other files...");
break;
}
}
buf.append("]");
return buf.toString();
}
}
| private void internalLinkVariable(EObject o, EAttribute attr, String varName, PPImportedNamesAdapter importedNames,
IMessageAcceptor acceptor) {
boolean qualified = false;
boolean global = false;
boolean disqualified = false;
QualifiedName qName = null;
SearchResult searchResult = null;
boolean existsAdjusted = false; // variable found as stated
boolean existsOutside = false; // if not found, reflects if found outside search path
try {
qName = converter.toQualifiedName(varName);
if(patternHelper.isDECIMALVAR(varName)) {
internalLinkRegexpVariable(o, varName, attr, acceptor);
return;
}
qualified = qName.getSegmentCount() > 1;
global = qName.getFirstSegment().length() == 0;
searchResult = ppFinder.findVariable(o, qName, importedNames);
// remove all references to not yet initialized variables
disqualified = (0 != removeDisqualifiedVariables(searchResult.getRaw(), o));
if(disqualified) // adjusted can not have disqualified entries if raw did not have them
removeDisqualifiedVariables(searchResult.getAdjusted(), o);
existsAdjusted = searchResult.getAdjusted().size() > 0;
existsOutside = existsAdjusted
? false // we are not interested in that it may be both adjusted and raw
: searchResult.getRaw().size() > 0;
}
catch(IllegalArgumentException iae) {
// Can happen if there is something seriously wrong with the qualified name, should be caught by
// validation - just ignore it here
return;
}
IValidationAdvisor advisor = advisor();
boolean mustExist = true;
if(qualified && global) { // && !(existsAdjusted || existsOutside)) {
// TODO: Possible future improvement when more global variables are known.
// if reported as error now, almost all global variables would be flagged as errors.
// Future enhancement could warn about those that are not found (resolved at runtime).
mustExist = false;
}
// Record facts at resource level about where variable was found
if(existsAdjusted)
importedNames.addResolved(searchResult.getAdjusted());
else if(existsOutside)
importedNames.addResolved(searchResult.getRaw());
if(mustExist) {
if(!(existsAdjusted || existsOutside)) {
importedNames.addUnresolved(qName);
// found nowhere
if(qualified || advisor.unqualifiedVariables().isWarningOrError()) {
StringBuilder message = new StringBuilder();
if(disqualified)
message.append("Reference to not yet initialized variable");
else
message.append(qualified
? "Unknown variable: '"
: "Unqualified and Unknown variable: '");
message.append(varName);
message.append("'");
String issue = disqualified
? IPPDiagnostics.ISSUE__UNINITIALIZED_VARIABLE
: IPPDiagnostics.ISSUE__UNKNOWN_VARIABLE;
if(disqualified || advisor.unqualifiedVariables() == ValidationPreference.ERROR)
acceptor.acceptError(message.toString(), o, attr, issue);
else
acceptor.acceptWarning(message.toString(), o, attr, issue);
}
}
else if(!existsAdjusted && existsOutside) {
// found outside
if(qualified || advisor.unqualifiedVariables().isWarningOrError())
acceptor.acceptWarning(
"Found outside current search path variable: '" + varName + "'", o, attr,
IPPDiagnostics.ISSUE__NOT_ON_PATH);
}
}
}
/**
* Returns true if the descriptions resource path is the same as for the given object and
* the fragment path of the given object starts with the fragment path of the description.
*
* (An alternative impl would be to first check if they are from the same resource - if so,
* it is know that this resource is loaded (since we have the given o) and it should
* be possible to search up the containment chain.
*
* @param desc
* @param o
* @return
*/
private boolean isParent(IEObjectDescription desc, EObject o) {
URI descUri = desc.getEObjectURI();
URI oUri = o.eResource().getURI();
if(!descUri.path().equals(oUri.path()))
return false;
// same resource, if desc's fragment is in at the start of the path, then o is contained
boolean result = o.eResource().getURIFragment(o).startsWith(descUri.fragment());
return result;
}
/**
* Link all resources in the model
*
* @param model
* @param acceptor
*/
public void link(EObject model, IMessageAcceptor acceptor, boolean profileThis) {
ppFinder.configure(model);
resource = model.eResource();
searchPath = searchPathProvider.get(resource);
// clear names remembered in the past
PPImportedNamesAdapter importedNames = PPImportedNamesAdapterFactory.eINSTANCE.adapt(resource);
importedNames.clear();
IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(resource);
IResourceDescription descr = descriptionIndex.getResourceDescription(resource.getURI());
if(descr == null) {
if(tracer.isTracing()) {
tracer.trace("Cleaning resource: " + resource.getURI().path());
}
return;
}
if(tracer.isTracing())
tracer.trace("Linking resource: ", resource.getURI().path(), "{");
// Need to get everything in the resource, not just the content of the PuppetManifest (as the manifest has top level
// expressions that need linking).
TreeIterator<EObject> everything = resource.getAllContents();
// it is important that ResourceExpresion are linked before ResourceBodyExpression (but that should
// be ok with the tree iterator as the bodies are contained).
while(everything.hasNext()) {
EObject o = everything.next();
EClass clazz = o.eClass();
switch(clazz.getClassifierID()) {
case PPPackage.EXPRESSION_TE:
_link((ExpressionTE) o, importedNames, acceptor);
break;
case PPPackage.VARIABLE_TE:
_link((VariableTE) o, importedNames, acceptor);
break;
case PPPackage.VARIABLE_EXPRESSION:
_link((VariableExpression) o, importedNames, acceptor);
break;
case PPPackage.RESOURCE_EXPRESSION:
_link((ResourceExpression) o, importedNames, acceptor);
break;
case PPPackage.RESOURCE_BODY:
_link((ResourceBody) o, importedNames, acceptor, profileThis);
break;
case PPPackage.FUNCTION_CALL:
_link((FunctionCall) o, importedNames, acceptor);
break;
// these are needed to link un-parenthesised function calls
case PPPackage.PUPPET_MANIFEST:
internalLinkUnparenthesisedCall(((PuppetManifest) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.IF_EXPRESSION:
internalLinkUnparenthesisedCall(((IfExpression) o).getThenStatements(), importedNames, acceptor);
break;
case PPPackage.ELSE_EXPRESSION:
internalLinkUnparenthesisedCall(((ElseExpression) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.ELSE_IF_EXPRESSION:
internalLinkUnparenthesisedCall(((ElseIfExpression) o).getThenStatements(), importedNames, acceptor);
break;
case PPPackage.NODE_DEFINITION:
internalLinkUnparenthesisedCall(((NodeDefinition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.DEFINITION:
internalLinkUnparenthesisedCall(((Definition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.CASE:
internalLinkUnparenthesisedCall(((Case) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.HOST_CLASS_DEFINITION:
_link((HostClassDefinition) o, importedNames, acceptor);
internalLinkUnparenthesisedCall(((HostClassDefinition) o).getStatements(), importedNames, acceptor);
break;
case PPPackage.UNQUOTED_STRING:
Expression expr = ((UnquotedString) o).getExpression();
if(expr != null && expr instanceof LiteralNameOrReference) {
//
String varName = ((LiteralNameOrReference) expr).getValue();
StringBuilder varName2 = new StringBuilder();
if(!varName.startsWith("$"))
varName2.append("$");
varName2.append(varName);
if(patternHelper.isVARIABLE(varName2.toString()))
internalLinkVariable(
expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, varName, importedNames,
acceptor);
else
acceptor.acceptError(
"Not a valid variable name", expr, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE,
IPPDiagnostics.ISSUE__NOT_VARNAME);
}
break;
// case PPPackage.DEFINITION_ARGUMENT:
// _check((DefinitionArgument) o, acceptor);
// break;
}
}
if(tracer.isTracing())
tracer.trace("}");
}
/**
* Surgically remove all disqualified descriptions (those that are HostClass and a container
* of the given object 'o'.
*
* @param descs
* @param o
*/
private void removeDisqualifiedContainers(List<IEObjectDescription> descs, EObject o) {
if(descs == null)
return;
ListIterator<IEObjectDescription> litor = descs.listIterator();
while(litor.hasNext()) {
IEObjectDescription x = litor.next();
if(x.getEClass() == PPPackage.Literals.DEFINITION || !isParent(x, o))
continue;
litor.remove();
}
}
/**
* Remove variables/entries that are not yet initialized. These are the values
* defined in the same name and type if the variable is contained in a definition argument
*
* <p>
* e.g. in define selfref($selfa = $selfref::selfa, $selfb=$selfa::x) { $x=10 } none of the references to selfa, or x are disqualified.
*
* @param descs
* @param o
* @return the number of disqualified variables removed from the list
*/
private int removeDisqualifiedVariables(List<IEObjectDescription> descs, EObject o) {
if(descs == null || descs.size() == 0)
return 0;
EObject p = o;
while(p != null && p.eClass().getClassifierID() != PPPackage.DEFINITION_ARGUMENT)
p = p.eContainer();
if(p == null)
return 0; // not in a definition argument value tree
// p is a DefinitionArgument at this point, we want it's parent being an abstract Definition
EObject d = p.eContainer();
if(d == null)
return 0; // broken model
d = d.eContainer();
final String definitionFragment = d.eResource().getURIFragment(d);
final String definitionURI = d.eResource().getURI().toString();
int removedCount = 0;
ListIterator<IEObjectDescription> litor = descs.listIterator();
while(litor.hasNext()) {
IEObjectDescription x = litor.next();
URI xURI = x.getEObjectURI();
// if in the same resource, and contain by the same EObject
if(xURI.toString().startsWith(definitionURI) && xURI.fragment().startsWith(definitionFragment)) {
litor.remove();
removedCount++;
}
}
return removedCount;
}
/**
* Collects the (unique) set of resource paths and returns a message with <=5 (+ ... and x others).
*
* @param descriptors
* @return
*/
private String visibleResourceList(Resource r, List<IEObjectDescription> descriptors) {
ResourcePropertiesAdapter adapter = ResourcePropertiesAdapterFactory.eINSTANCE.adapt(r);
URI root = (URI) adapter.get(PPDSLConstants.RESOURCE_PROPERTY__ROOT_URI);
// collect the (unique) resource paths
List<String> resources = Lists.newArrayList();
for(IEObjectDescription d : descriptors) {
URI uri = EcoreUtil.getURI(d.getEObjectOrProxy());
if(root != null) {
uri = uri.deresolve(root.appendSegment(""));
}
boolean isPptpResource = "pptp".equals(uri.fileExtension());
String path = isPptpResource
? uri.lastSegment().replace(".pptp", "")
: uri.devicePath();
if(!resources.contains(path))
resources.add(path);
}
StringBuffer buf = new StringBuffer();
buf.append(resources.size());
buf.append(" resource");
buf.append(resources.size() > 1
? "s ["
: " [");
int count = 0;
// if there are 4 include all, else limit to 3 - typically 2 (fresh user mistake) or is *many*
final int countCap = resources.size() == 4
? 4
: 3;
for(String s : resources) {
if(count > 0)
buf.append(", ");
buf.append(s);
if(count++ > countCap) {
buf.append("and ");
buf.append(resources.size() - countCap);
buf.append(" other files...");
break;
}
}
buf.append("]");
return buf.toString();
}
}
|
diff --git a/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java b/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java
index 65060ece..634ebe6f 100644
--- a/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java
+++ b/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java
@@ -1,235 +1,236 @@
/*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2013 ICM-UW
*
* CoAnSys 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.
* CoAnSys 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 CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.deduplication.document;
import pl.edu.icm.coansys.commons.java.DocumentWrapperUtils;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.edu.icm.coansys.commons.spring.DiReduceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.hadoop.conf.Configuration;
import org.springframework.beans.factory.annotation.Value;
import pl.edu.icm.coansys.deduplication.document.keygenerator.WorkKeyGenerator;
import pl.edu.icm.coansys.models.DocumentProtos;
/**
*
* @author Łukasz Dumiszewski
*
*/
@Service("duplicateWorkDetectReduceService")
public class DuplicateWorkDetectReduceService implements DiReduceService<Text, BytesWritable, Text, Text> {
//@SuppressWarnings("unused")
private static Logger log = LoggerFactory.getLogger(DuplicateWorkDetectReduceService.class);
@Autowired
private DuplicateWorkService duplicateWorkService;
@Autowired
private WorkKeyGenerator keyGen;
private int initialMaxDocsSetSize;
private int maxDocsSetSizeInc;
private int maxSplitLevel;
//******************** DiReduceService Implementation ********************
@Override
public void reduce(Text key, Iterable<BytesWritable> values, Reducer<Text, BytesWritable, Text, Text>.Context context) throws IOException, InterruptedException {
log.info("starting reduce, key: " + key.toString());
List<DocumentProtos.DocumentMetadata> documents = DocumentWrapperUtils.extractDocumentMetadata(key, values);
long startTime = new Date().getTime();
Configuration conf = context.getConfiguration();
initialMaxDocsSetSize = conf.getInt("INITIAL_MAX_DOCS_SET_SIZE", initialMaxDocsSetSize);
maxDocsSetSizeInc = conf.getInt("MAX_DOCS_SET_SIZE_INC", maxDocsSetSizeInc);
maxSplitLevel = conf.getInt("MAX_SPLIT_LEVEL", maxSplitLevel);
process(key, context, documents, 0, initialMaxDocsSetSize);
log.info("time [msec]: " + (new Date().getTime()-startTime));
}
//******************** PRIVATE ********************
/**
* Processes the given documents: finds duplicates and saves them to the context under the same, common key.
* If the number of the passed documents is greater than the <b>maxNumberOfDocuments</b> then the documents are split into smaller parts and
* then the method is recursively invoked for each one of those parts.
* @param key a common key of the documents
* @param level the recursive depth of the method used to generate a proper key of the passed documents. The greater the level the longer (and more unique) the
* generated key.
*/
void process(Text key, Reducer<Text, BytesWritable, Text, Text>.Context context, List<DocumentProtos.DocumentMetadata> documents, int level, int maxNumberOfDocuments) throws IOException, InterruptedException {
String dashes = getDashes(level);
log.info(dashes+ "start process, key: {}, number of documents: {}", key.toString(), documents.size());
if (documents.size()<2) {
log.info(dashes+ "one document only, ommiting");
return;
}
int lev = level + 1;
int maxNumOfDocs = maxNumberOfDocuments;
if (documents.size()>maxNumOfDocs) {
Map<Text, List<DocumentProtos.DocumentMetadata>> documentPacks = splitDocuments(key, documents, lev);
log.info(dashes+ "documents split into: {} packs", documentPacks.size());
for (Map.Entry<Text, List<DocumentProtos.DocumentMetadata>> docs : documentPacks.entrySet()) {
if (docs.getValue().size()==documents.size()) { // docs were not splitted, the generated key is the same for all the titles, may happen if the documents have the same short title, e.g. news in brief
maxNumOfDocs+=maxDocsSetSizeInc;
}
process(docs.getKey(), context, docs.getValue(), lev, maxNumOfDocs);
}
} else {
if (isDebugMode(context.getConfiguration())) {
duplicateWorkService.findDuplicates(documents, context);
} else {
Map<Integer, Set<DocumentProtos.DocumentMetadata>> duplicateWorksMap = duplicateWorkService.findDuplicates(documents, null);
saveDuplicatesToContext(duplicateWorksMap, key, context);
}
context.progress();
}
log.info(dashes+ "end process, key: {}", key);
}
private String getDashes(int level) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<=level; i++) {
sb.append("-");
}
return sb.toString();
}
private boolean isDebugMode(Configuration conf) {
if (conf == null) {
return false;
}
String debugOptionValue = conf.get("DEDUPLICATION_DEBUG_MODE", "false");
return debugOptionValue.equals("true");
}
/**
* Splits the passed documents into smaller parts. The documents are divided into smaller packs according to the generated keys.
* The keys are generated by using the {@link WorkKeyGenerator.generateKey(doc, level)} method.
*/
Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments(Text key, List<DocumentProtos.DocumentMetadata> documents, int level) {
// check if set was forced to split; if yes, keep the suffix
String keyStr = key.toString();
String suffix = "";
if (keyStr.contains("-")) {
String[] parts = keyStr.split("-");
suffix = parts[1];
}
Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments = Maps.newHashMap();
for (DocumentProtos.DocumentMetadata doc : documents) {
String newKeyStr = keyGen.generateKey(doc, level);
if (!suffix.isEmpty()) {
newKeyStr = newKeyStr + "-" + suffix;
}
Text newKey = new Text(newKeyStr);
List<DocumentProtos.DocumentMetadata> list = splitDocuments.get(newKey);
if (list == null) {
list = Lists.newArrayList();
splitDocuments.put(newKey, list);
}
list.add(doc);
}
if (level > maxSplitLevel && splitDocuments.size() == 1) {
//force split into 2 parts
Text commonKey = splitDocuments.keySet().iterator().next();
String commonKeyStr = commonKey.toString();
if (!commonKeyStr.contains("-")) {
commonKeyStr += "-";
}
Text firstKey = new Text(commonKeyStr + "0");
Text secondKey = new Text(commonKeyStr + "1");
List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(commonKey);
int items = fullList.size();
List<DocumentProtos.DocumentMetadata> firstHalf = fullList.subList(0, items/2);
List<DocumentProtos.DocumentMetadata> secondHalf = fullList.subList(items/2, items);
+ splitDocuments.clear();
splitDocuments.put(firstKey, firstHalf);
splitDocuments.put(secondKey, secondHalf);
}
return splitDocuments;
}
private void saveDuplicatesToContext(Map<Integer, Set<DocumentProtos.DocumentMetadata>> sameWorksMap, Text key, Reducer<Text, BytesWritable, Text, Text>.Context context)
throws IOException, InterruptedException {
for (Map.Entry<Integer, Set<DocumentProtos.DocumentMetadata>> entry : sameWorksMap.entrySet()) {
String sameWorksKey = key.toString() + "_" + entry.getKey();
for (DocumentProtos.DocumentMetadata doc : entry.getValue()) {
context.write(new Text(sameWorksKey), new Text(doc.getKey()));
}
}
}
@Value("1000")
public void setBeginPackSize(int beginPackSize) {
this.initialMaxDocsSetSize = beginPackSize;
}
@Value("200")
public void setPackSizeInc(int packSizeInc) {
this.maxDocsSetSizeInc = packSizeInc;
}
@Value("10")
public void setMaxSplitLevels(int maxSplitLevels) {
this.maxSplitLevel = maxSplitLevels;
}
static enum UnparseableIssue { UNPARSEABLE };
}
| true | true | Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments(Text key, List<DocumentProtos.DocumentMetadata> documents, int level) {
// check if set was forced to split; if yes, keep the suffix
String keyStr = key.toString();
String suffix = "";
if (keyStr.contains("-")) {
String[] parts = keyStr.split("-");
suffix = parts[1];
}
Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments = Maps.newHashMap();
for (DocumentProtos.DocumentMetadata doc : documents) {
String newKeyStr = keyGen.generateKey(doc, level);
if (!suffix.isEmpty()) {
newKeyStr = newKeyStr + "-" + suffix;
}
Text newKey = new Text(newKeyStr);
List<DocumentProtos.DocumentMetadata> list = splitDocuments.get(newKey);
if (list == null) {
list = Lists.newArrayList();
splitDocuments.put(newKey, list);
}
list.add(doc);
}
if (level > maxSplitLevel && splitDocuments.size() == 1) {
//force split into 2 parts
Text commonKey = splitDocuments.keySet().iterator().next();
String commonKeyStr = commonKey.toString();
if (!commonKeyStr.contains("-")) {
commonKeyStr += "-";
}
Text firstKey = new Text(commonKeyStr + "0");
Text secondKey = new Text(commonKeyStr + "1");
List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(commonKey);
int items = fullList.size();
List<DocumentProtos.DocumentMetadata> firstHalf = fullList.subList(0, items/2);
List<DocumentProtos.DocumentMetadata> secondHalf = fullList.subList(items/2, items);
splitDocuments.put(firstKey, firstHalf);
splitDocuments.put(secondKey, secondHalf);
}
return splitDocuments;
}
| Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments(Text key, List<DocumentProtos.DocumentMetadata> documents, int level) {
// check if set was forced to split; if yes, keep the suffix
String keyStr = key.toString();
String suffix = "";
if (keyStr.contains("-")) {
String[] parts = keyStr.split("-");
suffix = parts[1];
}
Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments = Maps.newHashMap();
for (DocumentProtos.DocumentMetadata doc : documents) {
String newKeyStr = keyGen.generateKey(doc, level);
if (!suffix.isEmpty()) {
newKeyStr = newKeyStr + "-" + suffix;
}
Text newKey = new Text(newKeyStr);
List<DocumentProtos.DocumentMetadata> list = splitDocuments.get(newKey);
if (list == null) {
list = Lists.newArrayList();
splitDocuments.put(newKey, list);
}
list.add(doc);
}
if (level > maxSplitLevel && splitDocuments.size() == 1) {
//force split into 2 parts
Text commonKey = splitDocuments.keySet().iterator().next();
String commonKeyStr = commonKey.toString();
if (!commonKeyStr.contains("-")) {
commonKeyStr += "-";
}
Text firstKey = new Text(commonKeyStr + "0");
Text secondKey = new Text(commonKeyStr + "1");
List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(commonKey);
int items = fullList.size();
List<DocumentProtos.DocumentMetadata> firstHalf = fullList.subList(0, items/2);
List<DocumentProtos.DocumentMetadata> secondHalf = fullList.subList(items/2, items);
splitDocuments.clear();
splitDocuments.put(firstKey, firstHalf);
splitDocuments.put(secondKey, secondHalf);
}
return splitDocuments;
}
|
diff --git a/modules/connectors/jdbc/connector/org/apache/lcf/crawler/connectors/jdbc/JDBCConnector.java b/modules/connectors/jdbc/connector/org/apache/lcf/crawler/connectors/jdbc/JDBCConnector.java
index 461843908..c8d39fcae 100644
--- a/modules/connectors/jdbc/connector/org/apache/lcf/crawler/connectors/jdbc/JDBCConnector.java
+++ b/modules/connectors/jdbc/connector/org/apache/lcf/crawler/connectors/jdbc/JDBCConnector.java
@@ -1,1090 +1,1093 @@
/* $Id$ */
/**
* 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.lcf.crawler.connectors.jdbc;
import org.apache.lcf.core.interfaces.*;
import org.apache.lcf.agents.interfaces.*;
import org.apache.lcf.crawler.interfaces.*;
import org.apache.lcf.crawler.system.Logging;
import org.apache.lcf.core.database.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.io.*;
import java.util.*;
/** This interface describes an instance of a connection between a repository and LCF's
* standard "pull" ingestion agent.
*
* Each instance of this interface is used in only one thread at a time. Connection Pooling
* on these kinds of objects is performed by the factory which instantiates repository connectors
* from symbolic names and config parameters, and is pooled by these parameters. That is, a pooled connector
* handle is used only if all the connection parameters for the handle match.
*
* Implementers of this interface should provide a default constructor which has this signature:
*
* xxx();
*
* Connectors are either configured or not. If configured, they will persist in a pool, and be
* reused multiple times. Certain methods of a connector may be called before the connector is
* configured. This includes basically all methods that permit inspection of the connector's
* capabilities. The complete list is:
*
*
* The purpose of the repository connector is to allow documents to be fetched from the repository.
*
* Each repository connector describes a set of documents that are known only to that connector.
* It therefore establishes a space of document identifiers. Each connector will only ever be
* asked to deal with identifiers that have in some way originated from the connector.
*
* Documents are fetched in three stages. First, the getDocuments() method is called in the connector
* implementation. This returns a set of document identifiers. The document identifiers are used to
* obtain the current document version strings in the second stage, using the getDocumentVersions() method.
* The last stage is processDocuments(), which queues up any additional documents needed, and also ingests.
* This method will not be called if the document version seems to indicate that no document change took
* place.
*/
public class JDBCConnector extends org.apache.lcf.crawler.connectors.BaseRepositoryConnector
{
public static final String _rcsid = "@(#)$Id$";
// Activities that we know about
protected final static String ACTIVITY_EXTERNAL_QUERY = "external query";
// Activities list
protected static final String[] activitiesList = new String[]{ACTIVITY_EXTERNAL_QUERY};
/** Deny access token for default authority */
private final static String defaultAuthorityDenyToken = "McAdAuthority_MC_DEAD_AUTHORITY";
protected JDBCConnection connection = null;
protected String jdbcProvider = null;
protected String host = null;
protected String databaseName = null;
protected String userName = null;
protected String password = null;
/** Constructor.
*/
public JDBCConnector()
{
}
/** Set up a session */
protected void getSession()
throws LCFException
{
if (connection == null)
{
if (jdbcProvider == null || jdbcProvider.length() == 0)
throw new LCFException("Missing parameter '"+JDBCConstants.providerParameter+"'");
if (host == null || host.length() == 0)
throw new LCFException("Missing parameter '"+JDBCConstants.hostParameter+"'");
connection = new JDBCConnection(jdbcProvider,host,databaseName,userName,password);
}
}
/** Return the list of activities that this connector supports (i.e. writes into the log).
*@return the list.
*/
public String[] getActivitiesList()
{
return activitiesList;
}
/** Return the path for the UI interface JSP elements.
* These JSP's must be provided to allow the connector to be configured, and to
* permit it to present document filtering specification information in the UI.
* This method should return the name of the folder, under the <webapp>/connectors/
* area, where the appropriate JSP's can be found. The name should NOT have a slash in it.
*@return the folder part
*/
public String getJSPFolder()
{
return "jdbc";
}
/** Model. Depending on what people enter for the seeding query, this could be either ALL or
* could be less than that. So, I've decided it will be at least the adds and changes, and
* won't include the deletes.
*/
public int getConnectorModel()
{
return MODEL_ADD_CHANGE;
}
/** Connect. The configuration parameters are included.
*@param configParams are the configuration parameters for this connection.
*/
public void connect(ConfigParams configParams)
{
super.connect(configParams);
jdbcProvider = configParams.getParameter(JDBCConstants.providerParameter);
host = configParams.getParameter(JDBCConstants.hostParameter);
databaseName = configParams.getParameter(JDBCConstants.databaseNameParameter);
userName= configParams.getParameter(JDBCConstants.databaseUserName);
password = configParams.getObfuscatedParameter(JDBCConstants.databasePassword);
}
/** Check status of connection.
*/
public String check()
throws LCFException
{
try
{
getSession();
// Attempt to fetch a connection; if this succeeds we pass
connection.testConnection();
return super.check();
}
catch (ServiceInterruption e)
{
if (Logging.connectors.isDebugEnabled())
Logging.connectors.debug("Service interruption in check(): "+e.getMessage(),e);
return "Transient error: "+e.getMessage();
}
}
/** Close the connection. Call this before discarding the repository connector.
*/
public void disconnect()
throws LCFException
{
connection = null;
host = null;
jdbcProvider = null;
databaseName = null;
userName = null;
password = null;
super.disconnect();
}
/** Get the bin name string for a document identifier. The bin name describes the queue to which the
* document will be assigned for throttling purposes. Throttling controls the rate at which items in a
* given queue are fetched; it does not say anything about the overall fetch rate, which may operate on
* multiple queues or bins.
* For example, if you implement a web crawler, a good choice of bin name would be the server name, since
* that is likely to correspond to a real resource that will need real throttle protection.
*@param documentIdentifier is the document identifier.
*@return the bin name.
*/
public String[] getBinNames(String documentIdentifier)
{
return new String[]{host};
}
/** Queue "seed" documents. Seed documents are the starting places for crawling activity. Documents
* are seeded when this method calls appropriate methods in the passed in ISeedingActivity object.
*
* This method can choose to find repository changes that happen only during the specified time interval.
* The seeds recorded by this method will be viewed by the framework based on what the
* getConnectorModel() method returns.
*
* It is not a big problem if the connector chooses to create more seeds than are
* strictly necessary; it is merely a question of overall work required.
*
* The times passed to this method may be interpreted for greatest efficiency. The time ranges
* any given job uses with this connector will not overlap, but will proceed starting at 0 and going
* to the "current time", each time the job is run. For continuous crawling jobs, this method will
* be called once, when the job starts, and at various periodic intervals as the job executes.
*
* When a job's specification is changed, the framework automatically resets the seeding start time to 0. The
* seeding start time may also be set to 0 on each job run, depending on the connector model returned by
* getConnectorModel().
*
* Note that it is always ok to send MORE documents rather than less to this method.
*@param activities is the interface this method should use to perform whatever framework actions are desired.
*@param spec is a document specification (that comes from the job).
*@param startTime is the beginning of the time range to consider, inclusive.
*@param endTime is the end of the time range to consider, exclusive.
*@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
*/
public void addSeedDocuments(ISeedingActivity activities, DocumentSpecification spec,
long startTime, long endTime, int jobMode)
throws LCFException, ServiceInterruption
{
getSession();
// Set up the query
TableSpec ts = new TableSpec(spec);
VariableMap vm = new VariableMap();
addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName);
addVariable(vm,JDBCConstants.startTimeVariable,startTime);
addVariable(vm,JDBCConstants.endTimeVariable,endTime);
// Do the substitution
ArrayList paramList = new ArrayList();
StringBuffer sb = new StringBuffer();
substituteQuery(ts.idQuery,vm,sb,paramList);
IDynamicResultSet idSet;
String queryText = sb.toString();
long startQueryTime = System.currentTimeMillis();
try
{
idSet = connection.executeUncachedQuery(queryText,paramList,-1);
}
catch (ServiceInterruption e)
{
// If failure, record the failure.
activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "ERROR", e.getMessage(), null);
throw e;
}
catch (LCFException e)
{
// If failure, record the failure.
activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "ERROR", e.getMessage(), null);
throw e;
}
try
{
// If success, record that too.
activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "OK", null, null);
while (true)
{
IResultRow row = idSet.getNextRow();
if (row == null)
break;
Object o = row.getValue(JDBCConstants.idReturnColumnName);
if (o == null)
throw new LCFException("Bad seed query; doesn't return 'id' column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\".");
String idValue = o.toString();
activities.addSeedDocument(idValue);
}
}
finally
{
idSet.close();
}
}
/** Get document versions given an array of document identifiers.
* This method is called for EVERY document that is considered. It is
* therefore important to perform as little work as possible here.
*@param documentIdentifiers is the array of local document identifiers, as understood by this connector.
*@param oldVersions is the corresponding array of version strings that have been saved for the document identifiers.
* A null value indicates that this is a first-time fetch, while an empty string indicates that the previous document
* had an empty version string.
*@param activities is the interface this method should use to perform whatever framework actions are desired.
*@param spec is the current document specification for the current job. If there is a dependency on this
* specification, then the version string should include the pertinent data, so that reingestion will occur
* when the specification changes. This is primarily useful for metadata.
*@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
*@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one.
*@return the corresponding version strings, with null in the places where the document no longer exists.
* Empty version strings indicate that there is no versioning ability for the corresponding document, and the document
* will always be processed.
*/
public String[] getDocumentVersions(String[] documentIdentifiers, String[] oldVersions, IVersionActivity activities,
DocumentSpecification spec, int jobMode, boolean usesDefaultAuthority)
throws LCFException, ServiceInterruption
{
getSession();
TableSpec ts = new TableSpec(spec);
String[] acls = getAcls(spec);
// Sort these,
java.util.Arrays.sort(acls);
String[] versionsReturned = new String[documentIdentifiers.length];
// If there is no version query, then always return empty string for all documents.
// This will mean that processDocuments will be called
// for all. ProcessDocuments will then be responsible for doing document deletes itself,
// based on the query results.
if (ts.versionQuery == null || ts.versionQuery.length() == 0)
{
int i = 0;
while (i < versionsReturned.length)
{
versionsReturned[i++] = "";
}
return versionsReturned;
}
// If there IS a versions query, do it. First set up the variables, then do the substitution.
VariableMap vm = new VariableMap();
addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName);
addConstant(vm,JDBCConstants.versionReturnVariable,JDBCConstants.versionReturnColumnName);
if (!addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,null))
return new String[0];
// Do the substitution
ArrayList paramList = new ArrayList();
StringBuffer sb = new StringBuffer();
substituteQuery(ts.versionQuery,vm,sb,paramList);
// Now, build a result return, and a hash table so we can correlate the returned values with the place to put them.
// We presume that if the row is missing, the document is gone.
Map map = new HashMap();
int j = 0;
while (j < documentIdentifiers.length)
{
map.put(documentIdentifiers[j],new Integer(j));
versionsReturned[j] = "";
j++;
}
// Fire off the query!
IDynamicResultSet result;
String queryText = sb.toString();
long startTime = System.currentTimeMillis();
try
{
result = connection.executeUncachedQuery(queryText,paramList,-1);
}
catch (LCFException e)
{
// If failure, record the failure.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "ERROR", e.getMessage(), null);
throw e;
}
// If success, record that too.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "OK", null, null);
try
{
// Now, go through resultset
while (true)
{
IResultRow row = result.getNextRow();
if (row == null)
break;
Object o = row.getValue(JDBCConstants.idReturnColumnName);
if (o == null)
throw new LCFException("Bad version query; doesn't return 'id' column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\".");
String idValue = o.toString();
o = row.getValue(JDBCConstants.versionReturnColumnName);
String versionValue;
// Null version is OK; make it a ""
if (o == null)
versionValue = "";
else
{
// A real version string! Any acls must be added to the front, if they are present...
sb = new StringBuffer();
packList(sb,acls,'+');
if (acls.length > 0 && usesDefaultAuthority)
{
sb.append('+');
pack(sb,defaultAuthorityDenyToken,'+');
}
else
sb.append('-');
sb.append(o.toString()).append("=").append(ts.dataQuery);
versionValue = sb.toString();
}
// Versions that are "", when processed, will have their acls fetched at that time...
versionsReturned[((Integer)map.get(idValue)).intValue()] = versionValue;
}
}
finally
{
result.close();
}
return versionsReturned;
}
/** Process a set of documents.
* This is the method that should cause each document to be fetched, processed, and the results either added
* to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
* The document specification allows this class to filter what is done based on the job.
*@param documentIdentifiers is the set of document identifiers to process.
*@param versions is the corresponding document versions to process, as returned by getDocumentVersions() above.
* The implementation may choose to ignore this parameter and always process the current version.
*@param activities is the interface this method should use to queue up new document references
* and ingest documents.
*@param spec is the document specification.
*@param scanOnly is an array corresponding to the document identifiers. It is set to true to indicate when the processing
* should only find other references, and should not actually call the ingestion methods.
*/
public void processDocuments(String[] documentIdentifiers, String[] versions, IProcessActivity activities, DocumentSpecification spec, boolean[] scanOnly)
throws LCFException, ServiceInterruption
{
getSession();
TableSpec ts = new TableSpec(spec);
String[] specAcls = null;
// For all the documents not marked "scan only", form a query and pick up the contents.
// If the contents is not found, then explicitly call the delete action method.
VariableMap vm = new VariableMap();
addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName);
addConstant(vm,JDBCConstants.urlReturnVariable,JDBCConstants.urlReturnColumnName);
addConstant(vm,JDBCConstants.dataReturnVariable,JDBCConstants.dataReturnColumnName);
if (!addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,scanOnly))
return;
// Do the substitution
ArrayList paramList = new ArrayList();
StringBuffer sb = new StringBuffer();
substituteQuery(ts.dataQuery,vm,sb,paramList);
int i;
// Build a map of versions we are allowed to ingest
Map map = new HashMap();
i = 0;
while (i < documentIdentifiers.length)
{
if (!scanOnly[i])
{
// Version strings at this point should never be null; the CF interprets nulls as
// meaning that delete must occur. Empty strings are possible though.
map.put(documentIdentifiers[i],versions[i]);
}
i++;
}
// Execute the query
IDynamicResultSet result;
String queryText = sb.toString();
long startTime = System.currentTimeMillis();
try
{
result = connection.executeUncachedQuery(queryText,paramList,-1);
}
catch (LCFException e)
{
// If failure, record the failure.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "ERROR", e.getMessage(), null);
throw e;
}
// If success, record that too.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "OK", null, null);
try
{
while (true)
{
IResultRow row = result.getNextRow();
if (row == null)
break;
Object o = row.getValue(JDBCConstants.idReturnColumnName);
if (o == null)
throw new LCFException("Bad document query; doesn't return 'id' column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\".");
String id = readAsString(o);
String version = (String)map.get(id);
if (version != null)
{
// This document was marked as "not scan only", so we expect to find it.
if (Logging.connectors.isDebugEnabled())
Logging.connectors.debug("JDBC: Document data result found for '"+id+"'");
o = row.getValue(JDBCConstants.urlReturnColumnName);
if (o != null)
{
// This is not right - url can apparently be a BinaryInput
String url = readAsString(o);
boolean validURL;
try
{
// Check to be sure url is valid
new java.net.URI(url);
validURL = true;
}
catch (java.net.URISyntaxException e)
{
validURL = false;
}
if (validURL)
{
// Process the document itself
Object contents = row.getValue(JDBCConstants.dataReturnColumnName);
// Null data is allowed; we just ignore these
if (contents != null)
{
// We will ingest something, so remove this id from the map in order that we know what we still
// need to delete when all done.
map.remove(id);
if (contents instanceof BinaryInput)
{
// An ingestion will take place for this document.
RepositoryDocument rd = new RepositoryDocument();
// Set up any acls
String[] accessAcls = null;
String[] denyAcls = null;
if (version.length() == 0)
{
// Version is empty string, therefore acl information must be gathered from spec
if (specAcls == null)
specAcls = getAcls(spec);
accessAcls = specAcls;
// Note: This should really depend on whether the connection uses the default AD authority or not, but most of the time
// this is true. Unfortunately, without an API change, we don't get the "usesDefaultAuthority" flag passed into
// processDocuments() at this time; when that is changed, make the following conditional on that flag being true.
- denyAcls = new String[]{defaultAuthorityDenyToken};
+ if (specAcls.length != 0)
+ denyAcls = new String[]{defaultAuthorityDenyToken};
+ else
+ denyAcls = new String[0];
}
else
{
// Unpack access tokens and the deny token too
ArrayList acls = new ArrayList();
StringBuffer denyAclBuffer = new StringBuffer();
int startPos = unpackList(acls,version,0,'+');
if (startPos < version.length() && version.charAt(startPos++) == '+')
{
startPos = unpack(denyAclBuffer,version,startPos,'+');
}
// Turn into acls and add into description
accessAcls = new String[acls.size()];
int j = 0;
while (j < accessAcls.length)
{
accessAcls[j] = (String)acls.get(j);
j++;
}
// Deny acl too
if (denyAclBuffer.length() > 0)
{
denyAcls = new String[]{denyAclBuffer.toString()};
}
}
if (accessAcls != null)
rd.setACL(accessAcls);
if (denyAcls != null)
rd.setDenyACL(denyAcls);
BinaryInput bi = (BinaryInput)contents;
try
{
// Read the stream
InputStream is = bi.getStream();
try
{
rd.setBinary(is,bi.getLength());
activities.ingestDocument(id, version, url, rd);
}
finally
{
is.close();
}
}
catch (java.net.SocketTimeoutException e)
{
throw new LCFException("Socket timeout reading database data: "+e.getMessage(),e);
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("Error reading database data: "+e.getMessage(),e);
}
finally
{
bi.discard();
}
}
else
{
// Turn it into a string, and then into a stream
String value = contents.toString();
try
{
byte[] bytes = value.getBytes("utf-8");
RepositoryDocument rd = new RepositoryDocument();
InputStream is = new ByteArrayInputStream(bytes);
try
{
rd.setBinary(is,bytes.length);
activities.ingestDocument(id, version, url, rd);
}
finally
{
is.close();
}
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("Error reading database data: "+e.getMessage(),e);
}
}
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' seems to have null data - skipping");
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' has an illegal url: '"+url+"' - skipping");
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' has a null url - skipping");
}
}
// Now, go through the original id's, and see which ones are still in the map. These
// did not appear in the result and are presumed to be gone from the database, and thus must be deleted.
i = 0;
while (i < documentIdentifiers.length)
{
if (!scanOnly[i])
{
String documentIdentifier = documentIdentifiers[i];
if (map.get(documentIdentifier) != null)
{
// This means we did not see it (or data for it) in the result set. Delete it!
activities.deleteDocument(documentIdentifier);
}
}
i++;
}
}
finally
{
result.close();
}
}
/** Get the maximum number of documents to amalgamate together into one batch, for this connector.
*@return the maximum number. 0 indicates "unlimited".
*/
public int getMaxDocumentRequest()
{
// This is a number that is comfortably processed by the query processor as part of an IN clause.
return 100;
}
// These are protected helper methods
/** Add starttime and endtime query variables
*/
protected static void addVariable(VariableMap map, String varName, long variable)
{
ArrayList params = new ArrayList();
params.add(new Long(variable));
map.addVariable(varName,"?",params);
}
/** Add string query variables
*/
protected static void addVariable(VariableMap map, String varName, String variable)
{
ArrayList params = new ArrayList();
params.add(variable);
map.addVariable(varName,"?",params);
}
/** Add string query constants
*/
protected static void addConstant(VariableMap map, String varName, String value)
{
map.addVariable(varName,value,null);
}
/** Build an idlist variable, and add it to the specified variable map.
*/
protected static boolean addIDList(VariableMap map, String varName, String[] documentIdentifiers, boolean[] scanOnly)
{
ArrayList params = new ArrayList();
StringBuffer sb = new StringBuffer(" (");
int i = 0;
int k = 0;
while (i < documentIdentifiers.length)
{
if (scanOnly == null || !scanOnly[i])
{
if (k > 0)
sb.append(",");
String documentIdentifier = documentIdentifiers[i];
sb.append("?");
params.add(documentIdentifier);
k++;
}
i++;
}
sb.append(") ");
map.addVariable(varName,sb.toString(),params);
return (k > 0);
}
/** Given a query, and a parameter map, substitute it.
* Each variable substitutes the string, and it also substitutes zero or more query parameters.
*/
protected static void substituteQuery(String inputString, VariableMap inputMap, StringBuffer outputQuery, ArrayList outputParams)
throws LCFException
{
// We are looking for strings that look like this: $(something)
// Right at the moment we don't care even about quotes, so we just want to look for $(.
int startIndex = 0;
while (true)
{
int nextIndex = inputString.indexOf("$(",startIndex);
if (nextIndex == -1)
{
outputQuery.append(inputString.substring(startIndex));
break;
}
int endIndex = inputString.indexOf(")",nextIndex);
if (endIndex == -1)
{
outputQuery.append(inputString.substring(startIndex));
break;
}
String variableName = inputString.substring(nextIndex+2,endIndex);
VariableMapItem item = inputMap.getVariable(variableName);
if (item == null)
throw new LCFException("No such substitution variable: $("+variableName+")");
outputQuery.append(inputString.substring(startIndex,nextIndex));
outputQuery.append(item.getValue());
ArrayList inputParams = item.getParameters();
if (inputParams != null)
{
int i = 0;
while (i < inputParams.size())
{
Object x = inputParams.get(i++);
outputParams.add(x);
}
}
startIndex = endIndex+1;
}
}
/** Grab forced acl out of document specification.
*@param spec is the document specification.
*@return the acls.
*/
protected static String[] getAcls(DocumentSpecification spec)
{
HashMap map = new HashMap();
int i = 0;
while (i < spec.getChildCount())
{
SpecificationNode sn = spec.getChild(i++);
if (sn.getType().equals("access"))
{
String token = sn.getAttributeValue("token");
map.put(token,token);
}
}
String[] rval = new String[map.size()];
Iterator iter = map.keySet().iterator();
i = 0;
while (iter.hasNext())
{
rval[i++] = (String)iter.next();
}
return rval;
}
/** Stuffer for packing a single string with an end delimiter */
protected static void pack(StringBuffer output, String value, char delimiter)
{
int i = 0;
while (i < value.length())
{
char x = value.charAt(i++);
if (x == '\\' || x == delimiter)
output.append('\\');
output.append(x);
}
output.append(delimiter);
}
/** Unstuffer for the above. */
protected static int unpack(StringBuffer sb, String value, int startPosition, char delimiter)
{
while (startPosition < value.length())
{
char x = value.charAt(startPosition++);
if (x == '\\')
{
if (startPosition < value.length())
x = value.charAt(startPosition++);
}
else if (x == delimiter)
break;
sb.append(x);
}
return startPosition;
}
/** Stuffer for packing lists of fixed length */
protected static void packFixedList(StringBuffer output, String[] values, char delimiter)
{
int i = 0;
while (i < values.length)
{
pack(output,values[i++],delimiter);
}
}
/** Unstuffer for unpacking lists of fixed length */
protected static int unpackFixedList(String[] output, String value, int startPosition, char delimiter)
{
StringBuffer sb = new StringBuffer();
int i = 0;
while (i < output.length)
{
sb.setLength(0);
startPosition = unpack(sb,value,startPosition,delimiter);
output[i++] = sb.toString();
}
return startPosition;
}
/** Stuffer for packing lists of variable length */
protected static void packList(StringBuffer output, ArrayList values, char delimiter)
{
pack(output,Integer.toString(values.size()),delimiter);
int i = 0;
while (i < values.size())
{
pack(output,values.get(i++).toString(),delimiter);
}
}
/** Another stuffer for packing lists of variable length */
protected static void packList(StringBuffer output, String[] values, char delimiter)
{
pack(output,Integer.toString(values.length),delimiter);
int i = 0;
while (i < values.length)
{
pack(output,values[i++],delimiter);
}
}
/** Unstuffer for unpacking lists of variable length.
*@param output is the array to write the unpacked result into.
*@param value is the value to unpack.
*@param startPosition is the place to start the unpack.
*@param delimiter is the character to use between values.
*@return the next position beyond the end of the list.
*/
protected static int unpackList(ArrayList output, String value, int startPosition, char delimiter)
{
StringBuffer sb = new StringBuffer();
startPosition = unpack(sb,value,startPosition,delimiter);
try
{
int count = Integer.parseInt(sb.toString());
int i = 0;
while (i < count)
{
sb.setLength(0);
startPosition = unpack(sb,value,startPosition,delimiter);
output.add(sb.toString());
i++;
}
}
catch (NumberFormatException e)
{
}
return startPosition;
}
/** Create an entity identifier from a querystring and a parameter list.
*/
protected static String createQueryString(String queryText, ArrayList paramList)
{
StringBuffer sb = new StringBuffer(queryText);
sb.append("; arguments = (");
int i = 0;
while (i < paramList.size())
{
if (i > 0)
sb.append(",");
Object parameter = paramList.get(i++);
if (parameter instanceof String)
sb.append(quoteSQLString((String)parameter));
else
sb.append(parameter.toString());
}
sb.append(")");
return sb.toString();
}
/** Quote a sql string.
*/
protected static String quoteSQLString(String input)
{
StringBuffer sb = new StringBuffer("\'");
int i = 0;
while (i < input.length())
{
char x = input.charAt(i++);
if (x == '\'')
sb.append('\'').append(x);
else if (x >= 0 && x < ' ')
sb.append(' ');
else
sb.append(x);
}
sb.append("\'");
return sb.toString();
}
/** Make sure we read this field as a string */
protected static String readAsString(Object o)
throws LCFException
{
if (o instanceof BinaryInput)
{
// Convert this input to a string, since mssql can mess us up with the wrong column types here.
BinaryInput bi = (BinaryInput)o;
try
{
InputStream is = bi.getStream();
try
{
InputStreamReader reader = new InputStreamReader(is,"utf-8");
StringBuffer sb = new StringBuffer();
while (true)
{
int x = reader.read();
if (x == -1)
break;
sb.append((char)x);
}
return sb.toString();
}
finally
{
is.close();
}
}
catch (IOException e)
{
throw new LCFException(e.getMessage(),e);
}
finally
{
bi.doneWithStream();
}
}
else
{
return o.toString();
}
}
/** Variable map entry.
*/
protected static class VariableMapItem
{
protected String value;
protected ArrayList params;
/** Constructor.
*/
public VariableMapItem(String value, ArrayList params)
{
this.value = value;
this.params = params;
}
/** Get value.
*/
public String getValue()
{
return value;
}
/** Get parameters.
*/
public ArrayList getParameters()
{
return params;
}
}
/** Variable map.
*/
protected static class VariableMap
{
protected Map variableMap = new HashMap();
/** Constructor
*/
public VariableMap()
{
}
/** Add a variable map entry */
public void addVariable(String variableName, String value, ArrayList parameters)
{
VariableMapItem e = new VariableMapItem(value,parameters);
variableMap.put(variableName,e);
}
/** Get a variable map entry */
public VariableMapItem getVariable(String variableName)
{
return (VariableMapItem)variableMap.get(variableName);
}
}
/** This class represents data gleaned from a document specification, in a more usable form.
*/
protected static class TableSpec
{
public String idQuery;
public String versionQuery;
public String dataQuery;
public TableSpec(DocumentSpecification ds)
{
int i = 0;
while (i < ds.getChildCount())
{
SpecificationNode sn = ds.getChild(i++);
if (sn.getType().equals(org.apache.lcf.crawler.connectors.jdbc.JDBCConstants.idQueryNode))
idQuery = sn.getValue();
else if (sn.getType().equals(org.apache.lcf.crawler.connectors.jdbc.JDBCConstants.versionQueryNode))
versionQuery = sn.getValue();
else if (sn.getType().equals(org.apache.lcf.crawler.connectors.jdbc.JDBCConstants.dataQueryNode))
dataQuery = sn.getValue();
}
}
}
}
| true | true | public void processDocuments(String[] documentIdentifiers, String[] versions, IProcessActivity activities, DocumentSpecification spec, boolean[] scanOnly)
throws LCFException, ServiceInterruption
{
getSession();
TableSpec ts = new TableSpec(spec);
String[] specAcls = null;
// For all the documents not marked "scan only", form a query and pick up the contents.
// If the contents is not found, then explicitly call the delete action method.
VariableMap vm = new VariableMap();
addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName);
addConstant(vm,JDBCConstants.urlReturnVariable,JDBCConstants.urlReturnColumnName);
addConstant(vm,JDBCConstants.dataReturnVariable,JDBCConstants.dataReturnColumnName);
if (!addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,scanOnly))
return;
// Do the substitution
ArrayList paramList = new ArrayList();
StringBuffer sb = new StringBuffer();
substituteQuery(ts.dataQuery,vm,sb,paramList);
int i;
// Build a map of versions we are allowed to ingest
Map map = new HashMap();
i = 0;
while (i < documentIdentifiers.length)
{
if (!scanOnly[i])
{
// Version strings at this point should never be null; the CF interprets nulls as
// meaning that delete must occur. Empty strings are possible though.
map.put(documentIdentifiers[i],versions[i]);
}
i++;
}
// Execute the query
IDynamicResultSet result;
String queryText = sb.toString();
long startTime = System.currentTimeMillis();
try
{
result = connection.executeUncachedQuery(queryText,paramList,-1);
}
catch (LCFException e)
{
// If failure, record the failure.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "ERROR", e.getMessage(), null);
throw e;
}
// If success, record that too.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "OK", null, null);
try
{
while (true)
{
IResultRow row = result.getNextRow();
if (row == null)
break;
Object o = row.getValue(JDBCConstants.idReturnColumnName);
if (o == null)
throw new LCFException("Bad document query; doesn't return 'id' column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\".");
String id = readAsString(o);
String version = (String)map.get(id);
if (version != null)
{
// This document was marked as "not scan only", so we expect to find it.
if (Logging.connectors.isDebugEnabled())
Logging.connectors.debug("JDBC: Document data result found for '"+id+"'");
o = row.getValue(JDBCConstants.urlReturnColumnName);
if (o != null)
{
// This is not right - url can apparently be a BinaryInput
String url = readAsString(o);
boolean validURL;
try
{
// Check to be sure url is valid
new java.net.URI(url);
validURL = true;
}
catch (java.net.URISyntaxException e)
{
validURL = false;
}
if (validURL)
{
// Process the document itself
Object contents = row.getValue(JDBCConstants.dataReturnColumnName);
// Null data is allowed; we just ignore these
if (contents != null)
{
// We will ingest something, so remove this id from the map in order that we know what we still
// need to delete when all done.
map.remove(id);
if (contents instanceof BinaryInput)
{
// An ingestion will take place for this document.
RepositoryDocument rd = new RepositoryDocument();
// Set up any acls
String[] accessAcls = null;
String[] denyAcls = null;
if (version.length() == 0)
{
// Version is empty string, therefore acl information must be gathered from spec
if (specAcls == null)
specAcls = getAcls(spec);
accessAcls = specAcls;
// Note: This should really depend on whether the connection uses the default AD authority or not, but most of the time
// this is true. Unfortunately, without an API change, we don't get the "usesDefaultAuthority" flag passed into
// processDocuments() at this time; when that is changed, make the following conditional on that flag being true.
denyAcls = new String[]{defaultAuthorityDenyToken};
}
else
{
// Unpack access tokens and the deny token too
ArrayList acls = new ArrayList();
StringBuffer denyAclBuffer = new StringBuffer();
int startPos = unpackList(acls,version,0,'+');
if (startPos < version.length() && version.charAt(startPos++) == '+')
{
startPos = unpack(denyAclBuffer,version,startPos,'+');
}
// Turn into acls and add into description
accessAcls = new String[acls.size()];
int j = 0;
while (j < accessAcls.length)
{
accessAcls[j] = (String)acls.get(j);
j++;
}
// Deny acl too
if (denyAclBuffer.length() > 0)
{
denyAcls = new String[]{denyAclBuffer.toString()};
}
}
if (accessAcls != null)
rd.setACL(accessAcls);
if (denyAcls != null)
rd.setDenyACL(denyAcls);
BinaryInput bi = (BinaryInput)contents;
try
{
// Read the stream
InputStream is = bi.getStream();
try
{
rd.setBinary(is,bi.getLength());
activities.ingestDocument(id, version, url, rd);
}
finally
{
is.close();
}
}
catch (java.net.SocketTimeoutException e)
{
throw new LCFException("Socket timeout reading database data: "+e.getMessage(),e);
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("Error reading database data: "+e.getMessage(),e);
}
finally
{
bi.discard();
}
}
else
{
// Turn it into a string, and then into a stream
String value = contents.toString();
try
{
byte[] bytes = value.getBytes("utf-8");
RepositoryDocument rd = new RepositoryDocument();
InputStream is = new ByteArrayInputStream(bytes);
try
{
rd.setBinary(is,bytes.length);
activities.ingestDocument(id, version, url, rd);
}
finally
{
is.close();
}
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("Error reading database data: "+e.getMessage(),e);
}
}
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' seems to have null data - skipping");
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' has an illegal url: '"+url+"' - skipping");
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' has a null url - skipping");
}
}
// Now, go through the original id's, and see which ones are still in the map. These
// did not appear in the result and are presumed to be gone from the database, and thus must be deleted.
i = 0;
while (i < documentIdentifiers.length)
{
if (!scanOnly[i])
{
String documentIdentifier = documentIdentifiers[i];
if (map.get(documentIdentifier) != null)
{
// This means we did not see it (or data for it) in the result set. Delete it!
activities.deleteDocument(documentIdentifier);
}
}
i++;
}
}
finally
{
result.close();
}
}
| public void processDocuments(String[] documentIdentifiers, String[] versions, IProcessActivity activities, DocumentSpecification spec, boolean[] scanOnly)
throws LCFException, ServiceInterruption
{
getSession();
TableSpec ts = new TableSpec(spec);
String[] specAcls = null;
// For all the documents not marked "scan only", form a query and pick up the contents.
// If the contents is not found, then explicitly call the delete action method.
VariableMap vm = new VariableMap();
addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName);
addConstant(vm,JDBCConstants.urlReturnVariable,JDBCConstants.urlReturnColumnName);
addConstant(vm,JDBCConstants.dataReturnVariable,JDBCConstants.dataReturnColumnName);
if (!addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,scanOnly))
return;
// Do the substitution
ArrayList paramList = new ArrayList();
StringBuffer sb = new StringBuffer();
substituteQuery(ts.dataQuery,vm,sb,paramList);
int i;
// Build a map of versions we are allowed to ingest
Map map = new HashMap();
i = 0;
while (i < documentIdentifiers.length)
{
if (!scanOnly[i])
{
// Version strings at this point should never be null; the CF interprets nulls as
// meaning that delete must occur. Empty strings are possible though.
map.put(documentIdentifiers[i],versions[i]);
}
i++;
}
// Execute the query
IDynamicResultSet result;
String queryText = sb.toString();
long startTime = System.currentTimeMillis();
try
{
result = connection.executeUncachedQuery(queryText,paramList,-1);
}
catch (LCFException e)
{
// If failure, record the failure.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "ERROR", e.getMessage(), null);
throw e;
}
// If success, record that too.
activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null,
createQueryString(queryText,paramList), "OK", null, null);
try
{
while (true)
{
IResultRow row = result.getNextRow();
if (row == null)
break;
Object o = row.getValue(JDBCConstants.idReturnColumnName);
if (o == null)
throw new LCFException("Bad document query; doesn't return 'id' column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\".");
String id = readAsString(o);
String version = (String)map.get(id);
if (version != null)
{
// This document was marked as "not scan only", so we expect to find it.
if (Logging.connectors.isDebugEnabled())
Logging.connectors.debug("JDBC: Document data result found for '"+id+"'");
o = row.getValue(JDBCConstants.urlReturnColumnName);
if (o != null)
{
// This is not right - url can apparently be a BinaryInput
String url = readAsString(o);
boolean validURL;
try
{
// Check to be sure url is valid
new java.net.URI(url);
validURL = true;
}
catch (java.net.URISyntaxException e)
{
validURL = false;
}
if (validURL)
{
// Process the document itself
Object contents = row.getValue(JDBCConstants.dataReturnColumnName);
// Null data is allowed; we just ignore these
if (contents != null)
{
// We will ingest something, so remove this id from the map in order that we know what we still
// need to delete when all done.
map.remove(id);
if (contents instanceof BinaryInput)
{
// An ingestion will take place for this document.
RepositoryDocument rd = new RepositoryDocument();
// Set up any acls
String[] accessAcls = null;
String[] denyAcls = null;
if (version.length() == 0)
{
// Version is empty string, therefore acl information must be gathered from spec
if (specAcls == null)
specAcls = getAcls(spec);
accessAcls = specAcls;
// Note: This should really depend on whether the connection uses the default AD authority or not, but most of the time
// this is true. Unfortunately, without an API change, we don't get the "usesDefaultAuthority" flag passed into
// processDocuments() at this time; when that is changed, make the following conditional on that flag being true.
if (specAcls.length != 0)
denyAcls = new String[]{defaultAuthorityDenyToken};
else
denyAcls = new String[0];
}
else
{
// Unpack access tokens and the deny token too
ArrayList acls = new ArrayList();
StringBuffer denyAclBuffer = new StringBuffer();
int startPos = unpackList(acls,version,0,'+');
if (startPos < version.length() && version.charAt(startPos++) == '+')
{
startPos = unpack(denyAclBuffer,version,startPos,'+');
}
// Turn into acls and add into description
accessAcls = new String[acls.size()];
int j = 0;
while (j < accessAcls.length)
{
accessAcls[j] = (String)acls.get(j);
j++;
}
// Deny acl too
if (denyAclBuffer.length() > 0)
{
denyAcls = new String[]{denyAclBuffer.toString()};
}
}
if (accessAcls != null)
rd.setACL(accessAcls);
if (denyAcls != null)
rd.setDenyACL(denyAcls);
BinaryInput bi = (BinaryInput)contents;
try
{
// Read the stream
InputStream is = bi.getStream();
try
{
rd.setBinary(is,bi.getLength());
activities.ingestDocument(id, version, url, rd);
}
finally
{
is.close();
}
}
catch (java.net.SocketTimeoutException e)
{
throw new LCFException("Socket timeout reading database data: "+e.getMessage(),e);
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("Error reading database data: "+e.getMessage(),e);
}
finally
{
bi.discard();
}
}
else
{
// Turn it into a string, and then into a stream
String value = contents.toString();
try
{
byte[] bytes = value.getBytes("utf-8");
RepositoryDocument rd = new RepositoryDocument();
InputStream is = new ByteArrayInputStream(bytes);
try
{
rd.setBinary(is,bytes.length);
activities.ingestDocument(id, version, url, rd);
}
finally
{
is.close();
}
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("Error reading database data: "+e.getMessage(),e);
}
}
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' seems to have null data - skipping");
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' has an illegal url: '"+url+"' - skipping");
}
else
Logging.connectors.warn("JDBC: Document '"+id+"' has a null url - skipping");
}
}
// Now, go through the original id's, and see which ones are still in the map. These
// did not appear in the result and are presumed to be gone from the database, and thus must be deleted.
i = 0;
while (i < documentIdentifiers.length)
{
if (!scanOnly[i])
{
String documentIdentifier = documentIdentifiers[i];
if (map.get(documentIdentifier) != null)
{
// This means we did not see it (or data for it) in the result set. Delete it!
activities.deleteDocument(documentIdentifier);
}
}
i++;
}
}
finally
{
result.close();
}
}
|
diff --git a/src/main/java/de/cismet/cids/navigator/utils/NavigatorCidsBeanPersistService.java b/src/main/java/de/cismet/cids/navigator/utils/NavigatorCidsBeanPersistService.java
index 5ff80a9..d34faad 100644
--- a/src/main/java/de/cismet/cids/navigator/utils/NavigatorCidsBeanPersistService.java
+++ b/src/main/java/de/cismet/cids/navigator/utils/NavigatorCidsBeanPersistService.java
@@ -1,40 +1,40 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.navigator.utils;
import Sirius.navigator.connection.SessionManager;
import Sirius.server.middleware.types.MetaObject;
import Sirius.server.newuser.User;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cids.utils.CidsBeanPersistService;
/**
*
* @author thorsten
*
*
*/
@org.openide.util.lookup.ServiceProvider(service = CidsBeanPersistService.class)
public class NavigatorCidsBeanPersistService implements CidsBeanPersistService {
public CidsBean persistCidsBean(CidsBean cidsBean) throws Exception {
- MetaObject MetaObject=cidsBean.getMetaObject();
- String domain = MetaObject.getDomain();
+ MetaObject metaObject=cidsBean.getMetaObject();
+ String domain = metaObject.getDomain();
User user = SessionManager.getSession().getUser();
- if (MetaObject.getStatus() == MetaObject.MODIFIED) {
- SessionManager.getConnection().updateMetaObject(user, MetaObject, domain);
- return SessionManager.getConnection().getMetaObject(user, MetaObject.getID(), MetaObject.getClassID(), domain).getBean();
- } else if (MetaObject.getStatus() == MetaObject.TO_DELETE) {
- SessionManager.getConnection().deleteMetaObject(user, MetaObject, domain);
+ if (metaObject.getStatus() == metaObject.MODIFIED) {
+ SessionManager.getConnection().updateMetaObject(user, metaObject, domain);
+ return SessionManager.getConnection().getMetaObject(user, metaObject.getID(), metaObject.getClassID(), domain).getBean();
+ } else if (metaObject.getStatus() == metaObject.TO_DELETE) {
+ SessionManager.getConnection().deleteMetaObject(user, metaObject, domain);
return null;
- } else if (MetaObject.getStatus() == MetaObject.NEW) {
- MetaObject mo = SessionManager.getConnection().insertMetaObject(user, MetaObject, domain);
+ } else if (metaObject.getStatus() == metaObject.NEW) {
+ MetaObject mo = SessionManager.getConnection().insertMetaObject(user, metaObject, domain);
if (mo != null) {
return mo.getBean();
}
}
return null;
}
}
| false | true | public CidsBean persistCidsBean(CidsBean cidsBean) throws Exception {
MetaObject MetaObject=cidsBean.getMetaObject();
String domain = MetaObject.getDomain();
User user = SessionManager.getSession().getUser();
if (MetaObject.getStatus() == MetaObject.MODIFIED) {
SessionManager.getConnection().updateMetaObject(user, MetaObject, domain);
return SessionManager.getConnection().getMetaObject(user, MetaObject.getID(), MetaObject.getClassID(), domain).getBean();
} else if (MetaObject.getStatus() == MetaObject.TO_DELETE) {
SessionManager.getConnection().deleteMetaObject(user, MetaObject, domain);
return null;
} else if (MetaObject.getStatus() == MetaObject.NEW) {
MetaObject mo = SessionManager.getConnection().insertMetaObject(user, MetaObject, domain);
if (mo != null) {
return mo.getBean();
}
}
return null;
}
| public CidsBean persistCidsBean(CidsBean cidsBean) throws Exception {
MetaObject metaObject=cidsBean.getMetaObject();
String domain = metaObject.getDomain();
User user = SessionManager.getSession().getUser();
if (metaObject.getStatus() == metaObject.MODIFIED) {
SessionManager.getConnection().updateMetaObject(user, metaObject, domain);
return SessionManager.getConnection().getMetaObject(user, metaObject.getID(), metaObject.getClassID(), domain).getBean();
} else if (metaObject.getStatus() == metaObject.TO_DELETE) {
SessionManager.getConnection().deleteMetaObject(user, metaObject, domain);
return null;
} else if (metaObject.getStatus() == metaObject.NEW) {
MetaObject mo = SessionManager.getConnection().insertMetaObject(user, metaObject, domain);
if (mo != null) {
return mo.getBean();
}
}
return null;
}
|
diff --git a/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineNative.java b/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineNative.java
index 9e20f30f..bd8bca3b 100644
--- a/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineNative.java
+++ b/gwtquery-core/src/main/java/com/google/gwt/query/client/impl/SelectorEngineNative.java
@@ -1,56 +1,56 @@
/*
* Copyright 2011, The gwtquery team.
*
* 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.google.gwt.query.client.impl;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
/**
* Runtime selector engine implementation for browsers with native
* querySelectorAll support.
*/
public class SelectorEngineNative extends SelectorEngineImpl {
public static String NATIVE_EXCEPTIONS_REGEXP = ".*(:contains|!=|:first|:last|:even|:odd).*";
private static HasSelector impl;
public SelectorEngineNative() {
if (impl == null) {
impl = GWT.create(HasSelector.class);
}
}
public NodeList<Element> select(String selector, Node ctx) {
// querySelectorAllImpl does not support ids starting with a digit.
if (selector.matches("#[\\w\\-]+")) {
- return SelectorEngine.veryQuickId(ctx, selector.substring(1));
+ return SelectorEngine.veryQuickId(selector.substring(1), ctx);
} else if (!SelectorEngine.hasQuerySelector || selector.matches(NATIVE_EXCEPTIONS_REGEXP)) {
return impl.select(selector, ctx);
} else {
try {
return SelectorEngine.querySelectorAllImpl(selector, ctx);
} catch (Exception e) {
System.err.println("ERROR SelectorEngineNative " + e.getMessage()
+ " " + selector + ", falling back to "
+ impl.getClass().getName().replaceAll(".*\\.", ""));
return impl.select(selector, ctx);
}
}
}
}
| true | true | public NodeList<Element> select(String selector, Node ctx) {
// querySelectorAllImpl does not support ids starting with a digit.
if (selector.matches("#[\\w\\-]+")) {
return SelectorEngine.veryQuickId(ctx, selector.substring(1));
} else if (!SelectorEngine.hasQuerySelector || selector.matches(NATIVE_EXCEPTIONS_REGEXP)) {
return impl.select(selector, ctx);
} else {
try {
return SelectorEngine.querySelectorAllImpl(selector, ctx);
} catch (Exception e) {
System.err.println("ERROR SelectorEngineNative " + e.getMessage()
+ " " + selector + ", falling back to "
+ impl.getClass().getName().replaceAll(".*\\.", ""));
return impl.select(selector, ctx);
}
}
}
| public NodeList<Element> select(String selector, Node ctx) {
// querySelectorAllImpl does not support ids starting with a digit.
if (selector.matches("#[\\w\\-]+")) {
return SelectorEngine.veryQuickId(selector.substring(1), ctx);
} else if (!SelectorEngine.hasQuerySelector || selector.matches(NATIVE_EXCEPTIONS_REGEXP)) {
return impl.select(selector, ctx);
} else {
try {
return SelectorEngine.querySelectorAllImpl(selector, ctx);
} catch (Exception e) {
System.err.println("ERROR SelectorEngineNative " + e.getMessage()
+ " " + selector + ", falling back to "
+ impl.getClass().getName().replaceAll(".*\\.", ""));
return impl.select(selector, ctx);
}
}
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/eventhandler/HostLeftAloneInSessionHandler.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/eventhandler/HostLeftAloneInSessionHandler.java
index 6575f5e8a..f36c283e5 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/eventhandler/HostLeftAloneInSessionHandler.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/eventhandler/HostLeftAloneInSessionHandler.java
@@ -1,100 +1,103 @@
package de.fu_berlin.inf.dpp.ui.eventhandler;
import org.apache.log4j.Logger;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.User;
import de.fu_berlin.inf.dpp.observables.ProjectNegotiationObservable;
import de.fu_berlin.inf.dpp.preferences.PreferenceConstants;
import de.fu_berlin.inf.dpp.project.AbstractSarosSessionListener;
import de.fu_berlin.inf.dpp.project.AbstractSharedProjectListener;
import de.fu_berlin.inf.dpp.project.ISarosSession;
import de.fu_berlin.inf.dpp.project.ISharedProjectListener;
import de.fu_berlin.inf.dpp.project.SarosSessionManager;
import de.fu_berlin.inf.dpp.ui.Messages;
import de.fu_berlin.inf.dpp.ui.util.CollaborationUtils;
import de.fu_berlin.inf.dpp.ui.views.SarosView;
import de.fu_berlin.inf.dpp.util.Utils;
/**
* Checks if the host remains alone after a user left the session. If so, ask if
* the session should be closed (optionally remember choice for workspace...)
*
* @author Alexander Waldmann ([email protected])
*/
public class HostLeftAloneInSessionHandler {
private static Logger log = Logger
.getLogger(HostLeftAloneInSessionHandler.class);
@Inject
Saros saros;
protected final SarosSessionManager sessionManager;
private ISharedProjectListener projectListener;
public HostLeftAloneInSessionHandler(SarosSessionManager sManager,
final ProjectNegotiationObservable processes) {
sessionManager = sManager;
projectListener = new AbstractSharedProjectListener() {
@Override
public void userLeft(User user) {
log.debug("sessionManager.userLeft");
ISarosSession session = sessionManager.getSarosSession();
if (session.getParticipants().size() == 1) {
- // only ask to close session if there are no running
- // negotiation processes because if there are, and the last
- // user "left", it was because he cancelled an
- // IncomingProjectNegotiation, and the session will be
- // closed anyway.
+ /*
+ * only ask to close session if there are no running
+ * negotiation processes because if there are, and the last
+ * user "left", it was because he cancelled an
+ * IncomingProjectNegotiation, and the session will be
+ * closed anyway.
+ */
if (processes.getProcesses().size() == 0) {
handleHostLeftAlone();
}
}
}
};
// register our sharedProjectListener when a session is started..
sessionManager
.addSarosSessionListener(new AbstractSarosSessionListener() {
@Override
public void sessionEnded(ISarosSession oldSarosSession) {
- // we need to clear any open notifications because there
- // might be stuff left, like follow mode notifications,
- // or "buddy joined" notification in case a buddy joined
- // the session but aborted the incoming project
- // negotiation...
+ /*
+ * we need to clear any open notifications because there
+ * might be stuff left, like follow mode notifications, or
+ * "buddy joined" notification in case a buddy joined the
+ * session but aborted the incoming project negotiation...
+ */
SarosView.clearNotifications();
}
@Override
public void sessionStarted(ISarosSession newSarosSession) {
sessionManager.getSarosSession().addListener(
projectListener);
}
});
}
public void handleHostLeftAlone() {
String stopSessionPreference = saros.getPreferenceStore().getString(
PreferenceConstants.STOP_EMPTY_SESSIONS);
boolean stopSession = true;
// if user did not save a decision in preferences yet: ask!
if (!stopSessionPreference.equals("false")
&& !stopSessionPreference.equals("true")) {
stopSession = Utils.popUpRememberDecisionDialog(
Messages.HostLeftAloneInSessionDialog_title,
Messages.HostLeftAloneInSessionDialog_message, saros,
PreferenceConstants.STOP_EMPTY_SESSIONS);
} else {
stopSession = stopSessionPreference.equals("true");
}
if (stopSession) {
CollaborationUtils.leaveSession(sessionManager);
}
}
}
| false | true | public HostLeftAloneInSessionHandler(SarosSessionManager sManager,
final ProjectNegotiationObservable processes) {
sessionManager = sManager;
projectListener = new AbstractSharedProjectListener() {
@Override
public void userLeft(User user) {
log.debug("sessionManager.userLeft");
ISarosSession session = sessionManager.getSarosSession();
if (session.getParticipants().size() == 1) {
// only ask to close session if there are no running
// negotiation processes because if there are, and the last
// user "left", it was because he cancelled an
// IncomingProjectNegotiation, and the session will be
// closed anyway.
if (processes.getProcesses().size() == 0) {
handleHostLeftAlone();
}
}
}
};
// register our sharedProjectListener when a session is started..
sessionManager
.addSarosSessionListener(new AbstractSarosSessionListener() {
@Override
public void sessionEnded(ISarosSession oldSarosSession) {
// we need to clear any open notifications because there
// might be stuff left, like follow mode notifications,
// or "buddy joined" notification in case a buddy joined
// the session but aborted the incoming project
// negotiation...
SarosView.clearNotifications();
}
@Override
public void sessionStarted(ISarosSession newSarosSession) {
sessionManager.getSarosSession().addListener(
projectListener);
}
});
}
| public HostLeftAloneInSessionHandler(SarosSessionManager sManager,
final ProjectNegotiationObservable processes) {
sessionManager = sManager;
projectListener = new AbstractSharedProjectListener() {
@Override
public void userLeft(User user) {
log.debug("sessionManager.userLeft");
ISarosSession session = sessionManager.getSarosSession();
if (session.getParticipants().size() == 1) {
/*
* only ask to close session if there are no running
* negotiation processes because if there are, and the last
* user "left", it was because he cancelled an
* IncomingProjectNegotiation, and the session will be
* closed anyway.
*/
if (processes.getProcesses().size() == 0) {
handleHostLeftAlone();
}
}
}
};
// register our sharedProjectListener when a session is started..
sessionManager
.addSarosSessionListener(new AbstractSarosSessionListener() {
@Override
public void sessionEnded(ISarosSession oldSarosSession) {
/*
* we need to clear any open notifications because there
* might be stuff left, like follow mode notifications, or
* "buddy joined" notification in case a buddy joined the
* session but aborted the incoming project negotiation...
*/
SarosView.clearNotifications();
}
@Override
public void sessionStarted(ISarosSession newSarosSession) {
sessionManager.getSarosSession().addListener(
projectListener);
}
});
}
|
diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java b/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java
index dcf910f0c..058dc978e 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java
@@ -1,168 +1,168 @@
package org.apache.lucene.store;
/*
* 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.IOException;
import org.apache.lucene.util.LuceneTestCase;
/**
* Used by MockRAMDirectory to create an output stream that
* will throw an IOException on fake disk full, track max
* disk space actually used, and maybe throw random
* IOExceptions.
*/
public class MockIndexOutputWrapper extends IndexOutput {
private MockDirectoryWrapper dir;
private final IndexOutput delegate;
private boolean first=true;
final String name;
byte[] singleByte = new byte[1];
/** Construct an empty output buffer. */
public MockIndexOutputWrapper(MockDirectoryWrapper dir, IndexOutput delegate, String name) {
this.dir = dir;
this.name = name;
this.delegate = delegate;
}
@Override
public void close() throws IOException {
try {
dir.maybeThrowDeterministicException();
} finally {
delegate.close();
if (dir.trackDiskUsage) {
// Now compute actual disk usage & track the maxUsedSize
// in the MockDirectoryWrapper:
long size = dir.getRecomputedActualSizeInBytes();
if (size > dir.maxUsedSize) {
dir.maxUsedSize = size;
}
}
dir.removeIndexOutput(this, name);
}
}
@Override
public void flush() throws IOException {
dir.maybeThrowDeterministicException();
delegate.flush();
}
@Override
public void writeByte(byte b) throws IOException {
singleByte[0] = b;
writeBytes(singleByte, 0, 1);
}
@Override
public void writeBytes(byte[] b, int offset, int len) throws IOException {
long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.sizeInBytes();
long realUsage = 0;
- if (dir.rateLimiter != null && len >= 10) {
+ if (dir.rateLimiter != null && len >= 1000) {
dir.rateLimiter.pause(len);
}
// If MockRAMDir crashed since we were opened, then
// don't write anything:
if (dir.crashed)
throw new IOException("MockRAMDirectory was crashed; cannot write to " + name);
// Enforce disk full:
if (dir.maxSize != 0 && freeSpace <= len) {
// Compute the real disk free. This will greatly slow
// down our test but makes it more accurate:
realUsage = dir.getRecomputedActualSizeInBytes();
freeSpace = dir.maxSize - realUsage;
}
if (dir.maxSize != 0 && freeSpace <= len) {
if (freeSpace > 0) {
realUsage += freeSpace;
delegate.writeBytes(b, offset, (int) freeSpace);
}
if (realUsage > dir.maxUsedSize) {
dir.maxUsedSize = realUsage;
}
String message = "fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + delegate.length();
if (freeSpace > 0) {
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
if (LuceneTestCase.VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": MDW: now throw fake disk full");
new Throwable().printStackTrace(System.out);
}
throw new IOException(message);
} else {
if (dir.randomState.nextInt(200) == 0) {
final int half = len/2;
delegate.writeBytes(b, offset, half);
Thread.yield();
delegate.writeBytes(b, offset+half, len-half);
} else {
delegate.writeBytes(b, offset, len);
}
}
dir.maybeThrowDeterministicException();
if (first) {
// Maybe throw random exception; only do this on first
// write to a new file:
first = false;
dir.maybeThrowIOException(name);
}
}
@Override
public long getFilePointer() {
return delegate.getFilePointer();
}
@Override
public void seek(long pos) throws IOException {
delegate.seek(pos);
}
@Override
public long length() throws IOException {
return delegate.length();
}
@Override
public void setLength(long length) throws IOException {
delegate.setLength(length);
}
@Override
public void copyBytes(DataInput input, long numBytes) throws IOException {
delegate.copyBytes(input, numBytes);
// TODO: we may need to check disk full here as well
dir.maybeThrowDeterministicException();
}
@Override
public String toString() {
return "MockIndexOutputWrapper(" + delegate + ")";
}
}
| true | true | public void writeBytes(byte[] b, int offset, int len) throws IOException {
long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.sizeInBytes();
long realUsage = 0;
if (dir.rateLimiter != null && len >= 10) {
dir.rateLimiter.pause(len);
}
// If MockRAMDir crashed since we were opened, then
// don't write anything:
if (dir.crashed)
throw new IOException("MockRAMDirectory was crashed; cannot write to " + name);
// Enforce disk full:
if (dir.maxSize != 0 && freeSpace <= len) {
// Compute the real disk free. This will greatly slow
// down our test but makes it more accurate:
realUsage = dir.getRecomputedActualSizeInBytes();
freeSpace = dir.maxSize - realUsage;
}
if (dir.maxSize != 0 && freeSpace <= len) {
if (freeSpace > 0) {
realUsage += freeSpace;
delegate.writeBytes(b, offset, (int) freeSpace);
}
if (realUsage > dir.maxUsedSize) {
dir.maxUsedSize = realUsage;
}
String message = "fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + delegate.length();
if (freeSpace > 0) {
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
if (LuceneTestCase.VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": MDW: now throw fake disk full");
new Throwable().printStackTrace(System.out);
}
throw new IOException(message);
} else {
if (dir.randomState.nextInt(200) == 0) {
final int half = len/2;
delegate.writeBytes(b, offset, half);
Thread.yield();
delegate.writeBytes(b, offset+half, len-half);
} else {
delegate.writeBytes(b, offset, len);
}
}
dir.maybeThrowDeterministicException();
if (first) {
// Maybe throw random exception; only do this on first
// write to a new file:
first = false;
dir.maybeThrowIOException(name);
}
}
| public void writeBytes(byte[] b, int offset, int len) throws IOException {
long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.sizeInBytes();
long realUsage = 0;
if (dir.rateLimiter != null && len >= 1000) {
dir.rateLimiter.pause(len);
}
// If MockRAMDir crashed since we were opened, then
// don't write anything:
if (dir.crashed)
throw new IOException("MockRAMDirectory was crashed; cannot write to " + name);
// Enforce disk full:
if (dir.maxSize != 0 && freeSpace <= len) {
// Compute the real disk free. This will greatly slow
// down our test but makes it more accurate:
realUsage = dir.getRecomputedActualSizeInBytes();
freeSpace = dir.maxSize - realUsage;
}
if (dir.maxSize != 0 && freeSpace <= len) {
if (freeSpace > 0) {
realUsage += freeSpace;
delegate.writeBytes(b, offset, (int) freeSpace);
}
if (realUsage > dir.maxUsedSize) {
dir.maxUsedSize = realUsage;
}
String message = "fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + delegate.length();
if (freeSpace > 0) {
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
if (LuceneTestCase.VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": MDW: now throw fake disk full");
new Throwable().printStackTrace(System.out);
}
throw new IOException(message);
} else {
if (dir.randomState.nextInt(200) == 0) {
final int half = len/2;
delegate.writeBytes(b, offset, half);
Thread.yield();
delegate.writeBytes(b, offset+half, len-half);
} else {
delegate.writeBytes(b, offset, len);
}
}
dir.maybeThrowDeterministicException();
if (first) {
// Maybe throw random exception; only do this on first
// write to a new file:
first = false;
dir.maybeThrowIOException(name);
}
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/LibraryTabActivity.java b/MPDroid/src/com/namelessdev/mpdroid/LibraryTabActivity.java
index 0cd3f4be..fefc60e2 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/LibraryTabActivity.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/LibraryTabActivity.java
@@ -1,176 +1,180 @@
package com.namelessdev.mpdroid;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.ArrayAdapter;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.namelessdev.mpdroid.fragments.AlbumsFragment;
import com.namelessdev.mpdroid.fragments.ArtistsFragment;
import com.namelessdev.mpdroid.fragments.FSFragment;
import com.namelessdev.mpdroid.fragments.PlaylistsFragment;
import com.namelessdev.mpdroid.fragments.StreamsFragment;
public class LibraryTabActivity extends SherlockFragmentActivity implements OnNavigationListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@TargetApi(11)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_tabs);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(this, R.layout.sherlock_spinner_item);
actionBarAdapter.add(getString(R.string.artists));
actionBarAdapter.add(getString(R.string.albums));
actionBarAdapter.add(getString(R.string.playlists));
actionBarAdapter.add(getString(R.string.streams));
actionBarAdapter.add(getString(R.string.files));
if(Build.VERSION.SDK_INT >= 14) {
//Bug on ICS with sherlock's layout
actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} else {
actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
}
actionBar.setListNavigationCallbacks(actionBarAdapter, this);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
- int defaultTab = settings.getInt("defaultLibraryScreen", 0);
+ int defaultTab = 0;
+ try {
+ defaultTab = Integer.parseInt(settings.getString("defaultLibraryScreen", "0"));
+ } catch (NumberFormatException e) {
+ }
if (defaultTab > actionBarAdapter.getCount() - 1) {
defaultTab = 0;
settings.edit().putString("defaultLibraryScreen", "0");
}
mViewPager.setCurrentItem(defaultTab, true);
}
@Override
public void onStart() {
super.onStart();
MPDApplication app = (MPDApplication) getApplicationContext();
app.setActivity(this);
}
@Override
public void onStop() {
super.onStop();
MPDApplication app = (MPDApplication) getApplicationContext();
app.unsetActivity(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.mpd_browsermenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
this.onSearchRequested();
return true;
case android.R.id.home:
finish();
return true;
}
return false;
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
mViewPager.setCurrentItem(itemPosition, true);
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = null;
switch (i) {
case 0: fragment = new ArtistsFragment(); break;
case 1: fragment = new AlbumsFragment(); break;
case 2: fragment = new PlaylistsFragment(); break;
case 3: fragment = new StreamsFragment(); break;
case 4: fragment = new FSFragment(); break;
}
return fragment;
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.artists);
case 1: return getString(R.string.albums);
case 2: return getString(R.string.playlists);
case 3: return getString(R.string.streams);
case 4: return getString(R.string.files);
}
return null;
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_tabs);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(this, R.layout.sherlock_spinner_item);
actionBarAdapter.add(getString(R.string.artists));
actionBarAdapter.add(getString(R.string.albums));
actionBarAdapter.add(getString(R.string.playlists));
actionBarAdapter.add(getString(R.string.streams));
actionBarAdapter.add(getString(R.string.files));
if(Build.VERSION.SDK_INT >= 14) {
//Bug on ICS with sherlock's layout
actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} else {
actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
}
actionBar.setListNavigationCallbacks(actionBarAdapter, this);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
int defaultTab = settings.getInt("defaultLibraryScreen", 0);
if (defaultTab > actionBarAdapter.getCount() - 1) {
defaultTab = 0;
settings.edit().putString("defaultLibraryScreen", "0");
}
mViewPager.setCurrentItem(defaultTab, true);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_tabs);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(this, R.layout.sherlock_spinner_item);
actionBarAdapter.add(getString(R.string.artists));
actionBarAdapter.add(getString(R.string.albums));
actionBarAdapter.add(getString(R.string.playlists));
actionBarAdapter.add(getString(R.string.streams));
actionBarAdapter.add(getString(R.string.files));
if(Build.VERSION.SDK_INT >= 14) {
//Bug on ICS with sherlock's layout
actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} else {
actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
}
actionBar.setListNavigationCallbacks(actionBarAdapter, this);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
int defaultTab = 0;
try {
defaultTab = Integer.parseInt(settings.getString("defaultLibraryScreen", "0"));
} catch (NumberFormatException e) {
}
if (defaultTab > actionBarAdapter.getCount() - 1) {
defaultTab = 0;
settings.edit().putString("defaultLibraryScreen", "0");
}
mViewPager.setCurrentItem(defaultTab, true);
}
|
diff --git a/src/org/proofpad/Acl2Parser.java b/src/org/proofpad/Acl2Parser.java
index e89e096..81517d4 100755
--- a/src/org/proofpad/Acl2Parser.java
+++ b/src/org/proofpad/Acl2Parser.java
@@ -1,728 +1,747 @@
package org.proofpad;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.parser.AbstractParser;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice;
import org.fife.ui.rsyntaxtextarea.parser.ParseResult;
import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
public class Acl2Parser extends AbstractParser {
public interface ParseListener {
void wasParsed();
}
private static Logger logger = Logger.getLogger(Acl2Parser.class.toString());
public static class CacheKey implements Serializable {
private static final long serialVersionUID = -4201796432147755450L;
private final File book;
private final long mtime;
public CacheKey(File book, long mtime) {
this.book = book;
this.mtime = mtime;
}
@Override
public int hashCode() {
return book.hashCode() ^ Long.valueOf(mtime).hashCode();
}
@Override
public boolean equals(Object other) {
return (other instanceof CacheKey &&
((CacheKey) other).book.equals(this.book) &&
((CacheKey) other).mtime == this.mtime);
}
}
private static class Range implements Serializable {
private static final long serialVersionUID = 3510110011135344206L;
public final int lower;
public final int upper;
Range(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
}
static class CacheSets implements Serializable {
private static final long serialVersionUID = -2233827686979689741L;
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
}
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
public File workingDir;
private Map<CacheKey, CacheSets> cache = Main.cache.getBookCache();
private File acl2Dir;
private final List<ParseListener> parseListeners = new LinkedList<Acl2Parser.ParseListener>();
public Acl2Parser(File workingDir, File acl2Dir) {
this.workingDir = workingDir;
this.setAcl2Dir(acl2Dir);
}
private static Map<String, Range> paramCounts = new HashMap<String, Range>();
static {
paramCounts.put("-", new Range(1, 2));
paramCounts.put("/", new Range(1, 2));
paramCounts.put("/=", new Range(2, 2));
paramCounts.put("1+", new Range(1, 1));
paramCounts.put("1-", new Range(1, 1));
paramCounts.put("<=", new Range(2, 2));
paramCounts.put(">", new Range(2, 2));
paramCounts.put(">=", new Range(2, 2));
paramCounts.put("abs", new Range(1, 1));
paramCounts.put("acl2-numberp", new Range(1, 1));
paramCounts.put("acons", new Range(3, 3));
paramCounts.put("add-to-set-eq", new Range(2, 2));
paramCounts.put("add-to-set-eql", new Range(2, 2));
paramCounts.put("add-to-set-equal", new Range(2, 2));
paramCounts.put("alistp", new Range(1, 1));
paramCounts.put("alpha-char-p", new Range(1, 1));
paramCounts.put("alphorder", new Range(2, 2));
paramCounts.put("ash", new Range(2, 2));
paramCounts.put("assert$", new Range(2, 2));
paramCounts.put("assoc-eq", new Range(2, 2));
paramCounts.put("assoc-equal", new Range(2, 2));
paramCounts.put("assoc-keyword", new Range(2, 2));
paramCounts.put("atom", new Range(1, 1));
paramCounts.put("atom-listp", new Range(1, 1));
paramCounts.put("binary-*", new Range(2, 2));
paramCounts.put("binary-+", new Range(2, 2));
paramCounts.put("binary-append", new Range(2, 2));
paramCounts.put("boole$", new Range(3, 3));
paramCounts.put("booleanp", new Range(1, 1));
paramCounts.put("butlast", new Range(2, 2));
paramCounts.put("caaaar", new Range(1, 1));
paramCounts.put("caaadr", new Range(1, 1));
paramCounts.put("caaar", new Range(1, 1));
paramCounts.put("caadar", new Range(1, 1));
paramCounts.put("caaddr", new Range(1, 1));
paramCounts.put("caadr", new Range(1, 1));
paramCounts.put("caar", new Range(1, 1));
paramCounts.put("cadaar", new Range(1, 1));
paramCounts.put("cadadr", new Range(1, 1));
paramCounts.put("cadar", new Range(1, 1));
paramCounts.put("caddar", new Range(1, 1));
paramCounts.put("cadddr", new Range(1, 1));
paramCounts.put("caddr", new Range(1, 1));
paramCounts.put("cadr", new Range(1, 1));
paramCounts.put("car", new Range(1, 1));
paramCounts.put("cdaaar", new Range(1, 1));
paramCounts.put("cdaadr", new Range(1, 1));
paramCounts.put("cdaar", new Range(1, 1));
paramCounts.put("cdadar", new Range(1, 1));
paramCounts.put("cdaddr", new Range(1, 1));
paramCounts.put("cdadr", new Range(1, 1));
paramCounts.put("cdar", new Range(1, 1));
paramCounts.put("cddaar", new Range(1, 1));
paramCounts.put("cddadr", new Range(1, 1));
paramCounts.put("cddar", new Range(1, 1));
paramCounts.put("cdddar", new Range(1, 1));
paramCounts.put("cddddr", new Range(1, 1));
paramCounts.put("cdddr", new Range(1, 1));
paramCounts.put("cddr", new Range(1, 1));
paramCounts.put("cdr", new Range(1, 1));
paramCounts.put("ceiling", new Range(2, 2));
paramCounts.put("char", new Range(2, 2));
paramCounts.put("char-code", new Range(1, 1));
paramCounts.put("char-downcase", new Range(1, 1));
paramCounts.put("char-equal", new Range(2, 2));
paramCounts.put("char-upcase", new Range(1, 1));
paramCounts.put("char<", new Range(2, 2));
paramCounts.put("char<=", new Range(2, 2));
paramCounts.put("char>", new Range(2, 2));
paramCounts.put("char>=", new Range(2, 2));
paramCounts.put("character-alistp", new Range(1, 1));
paramCounts.put("character-listp", new Range(1, 1));
paramCounts.put("characterp", new Range(1, 1));
paramCounts.put("code-char", new Range(1, 1));
paramCounts.put("coerce", new Range(2, 2));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("comp-gcl", new Range(1, 1));
paramCounts.put("complex", new Range(2, 2));
paramCounts.put("complex-rationalp", new Range(1, 1));
paramCounts.put("complex/complex-rationalp", new Range(1, 1));
paramCounts.put("conjugate", new Range(1, 1));
paramCounts.put("cons", new Range(2, 2));
paramCounts.put("consp", new Range(1, 1));
paramCounts.put("cpu-core-count", new Range(1, 1));
paramCounts.put("delete-assoc-eq", new Range(2, 2));
paramCounts.put("denominator", new Range(1, 1));
paramCounts.put("digit-char-p", new Range(1, 2));
paramCounts.put("digit-to-char", new Range(1, 1));
paramCounts.put("ec-call", new Range(1, 1));
paramCounts.put("eighth", new Range(1, 1));
paramCounts.put("endp", new Range(1, 1));
paramCounts.put("eq", new Range(2, 2));
paramCounts.put("eql", new Range(2, 2));
paramCounts.put("eqlable-alistp", new Range(1, 1));
paramCounts.put("eqlable-listp", new Range(1, 1));
paramCounts.put("eqlablep", new Range(1, 1));
paramCounts.put("equal", new Range(2, 2));
paramCounts.put("error1", new Range(4, 4));
paramCounts.put("evenp", new Range(1, 1));
paramCounts.put("explode-nonnegative-integer", new Range(3, 5));
paramCounts.put("expt", new Range(2, 2));
paramCounts.put("fifth", new Range(1, 1));
paramCounts.put("first", new Range(1, 1));
paramCounts.put("fix", new Range(1, 1));
paramCounts.put("fix-true-list", new Range(1, 1));
paramCounts.put("floor", new Range(2, 2));
paramCounts.put("fms", new Range(5, 5));
paramCounts.put("fms!", new Range(5, 5));
paramCounts.put("fmt", new Range(5, 5));
paramCounts.put("fmt!", new Range(5, 5));
paramCounts.put("fmt1", new Range(6, 6));
paramCounts.put("fmt1!", new Range(6, 6));
paramCounts.put("fourth", new Range(1, 1));
paramCounts.put("get-output-stream-string$", new Range(2, 4));
paramCounts.put("getenv$", new Range(2, 2));
paramCounts.put("getprop", new Range(5, 5));
paramCounts.put("good-atom-listp", new Range(1, 1));
paramCounts.put("hard-error", new Range(3, 3));
paramCounts.put("identity", new Range(1, 1));
paramCounts.put("if", new Range(3, 3));
paramCounts.put("iff", new Range(2, 2));
paramCounts.put("ifix", new Range(1, 1));
paramCounts.put("illegal", new Range(3, 3));
paramCounts.put("imagpart", new Range(1, 1));
paramCounts.put("implies", new Range(2, 2));
paramCounts.put("improper-consp", new Range(1, 1));
paramCounts.put("int=", new Range(2, 2));
paramCounts.put("integer-length", new Range(1, 1));
paramCounts.put("integer-listp", new Range(1, 1));
paramCounts.put("integerp", new Range(1, 1));
paramCounts.put("intern", new Range(2, 2));
paramCounts.put("intern$", new Range(2, 2));
paramCounts.put("intern-in-package-of-symbol", new Range(2, 5));
paramCounts.put("intersectp-eq", new Range(2, 2));
paramCounts.put("intersectp-equal", new Range(2, 2));
paramCounts.put("keywordp", new Range(1, 1));
paramCounts.put("kwote", new Range(1, 1));
paramCounts.put("kwote-lst", new Range(1, 1));
paramCounts.put("last", new Range(1, 1));
paramCounts.put("len", new Range(1, 1));
paramCounts.put("length", new Range(1, 1));
paramCounts.put("lexorder", new Range(2, 2));
paramCounts.put("listp", new Range(1, 1));
paramCounts.put("logandc1", new Range(2, 2));
paramCounts.put("logandc2", new Range(2, 2));
paramCounts.put("logbitp", new Range(2, 2));
paramCounts.put("logcount", new Range(1, 1));
paramCounts.put("lognand", new Range(2, 2));
paramCounts.put("lognor", new Range(2, 2));
paramCounts.put("lognot", new Range(1, 1));
paramCounts.put("logorc1", new Range(2, 2));
paramCounts.put("logorc2", new Range(2, 2));
paramCounts.put("logtest", new Range(2, 2));
paramCounts.put("lower-case-p", new Range(1, 1));
paramCounts.put("make-ord", new Range(3, 3));
paramCounts.put("max", new Range(2, 2));
paramCounts.put("mbe1", new Range(2, 2));
paramCounts.put("mbt", new Range(1, 1));
paramCounts.put("member-eq", new Range(2, 2));
paramCounts.put("member-equal", new Range(2, 2));
paramCounts.put("min", new Range(2, 2));
paramCounts.put("minusp", new Range(1, 1));
paramCounts.put("mod", new Range(2, 2));
paramCounts.put("mod-expt", new Range(3, 3));
paramCounts.put("must-be-equal", new Range(2, 2));
paramCounts.put("mv-list", new Range(2, 2));
paramCounts.put("mv-nth", new Range(2, 2));
paramCounts.put("natp", new Range(1, 1));
paramCounts.put("nfix", new Range(1, 1));
paramCounts.put("ninth", new Range(1, 1));
paramCounts.put("no-duplicatesp-eq", new Range(1, 1));
paramCounts.put("nonnegative-integer-quotient", new Range(2, 4));
paramCounts.put("not", new Range(1, 1));
paramCounts.put("nth", new Range(2, 2));
paramCounts.put("nthcdr", new Range(2, 2));
paramCounts.put("null", new Range(1, 1));
paramCounts.put("numerator", new Range(1, 1));
paramCounts.put("o-finp", new Range(1, 1));
paramCounts.put("o-first-coeff", new Range(1, 1));
paramCounts.put("o-first-expt", new Range(1, 1));
paramCounts.put("o-infp", new Range(1, 1));
paramCounts.put("o-p", new Range(1, 1));
paramCounts.put("o-rst", new Range(1, 1));
paramCounts.put("o<", new Range(2, 2));
paramCounts.put("o<=", new Range(2, 2));
paramCounts.put("o>", new Range(2, 2));
paramCounts.put("o>=", new Range(2, 2));
paramCounts.put("oddp", new Range(1, 1));
paramCounts.put("pairlis$", new Range(2, 2));
paramCounts.put("peek-char$", new Range(2, 2));
paramCounts.put("pkg-imports", new Range(1, 1));
paramCounts.put("pkg-witness", new Range(1, 1));
paramCounts.put("plusp", new Range(1, 1));
paramCounts.put("position-eq", new Range(2, 2));
paramCounts.put("position-equal", new Range(2, 2));
paramCounts.put("posp", new Range(1, 1));
paramCounts.put("print-object$", new Range(3, 3));
paramCounts.put("prog2$", new Range(2, 2));
paramCounts.put("proofs-co", new Range(1, 1));
paramCounts.put("proper-consp", new Range(1, 1));
paramCounts.put("put-assoc-eq", new Range(3, 3));
paramCounts.put("put-assoc-eql", new Range(3, 3));
paramCounts.put("put-assoc-equal", new Range(3, 3));
paramCounts.put("putprop", new Range(4, 4));
paramCounts.put("r-eqlable-alistp", new Range(1, 1));
paramCounts.put("r-symbol-alistp", new Range(1, 1));
paramCounts.put("random$", new Range(2, 2));
paramCounts.put("rassoc-eq", new Range(2, 2));
paramCounts.put("rassoc-equal", new Range(2, 2));
paramCounts.put("rational-listp", new Range(1, 1));
paramCounts.put("rationalp", new Range(1, 1));
paramCounts.put("read-byte$", new Range(2, 2));
paramCounts.put("read-char$", new Range(2, 2));
paramCounts.put("read-object", new Range(2, 2));
paramCounts.put("real/rationalp", new Range(1, 1));
paramCounts.put("realfix", new Range(1, 1));
paramCounts.put("realpart", new Range(1, 1));
paramCounts.put("rem", new Range(2, 2));
paramCounts.put("remove-duplicates-eq", new Range(1, 1));
paramCounts.put("remove-duplicates-equal", new Range(1, 6));
paramCounts.put("remove-eq", new Range(2, 2));
paramCounts.put("remove-equal", new Range(2, 2));
paramCounts.put("remove1-eq", new Range(2, 2));
paramCounts.put("remove1-equal", new Range(2, 2));
paramCounts.put("rest", new Range(1, 1));
paramCounts.put("return-last", new Range(3, 3));
paramCounts.put("revappend", new Range(2, 2));
paramCounts.put("reverse", new Range(1, 1));
paramCounts.put("rfix", new Range(1, 1));
paramCounts.put("round", new Range(2, 2));
paramCounts.put("second", new Range(1, 1));
paramCounts.put("set-difference-eq", new Range(2, 2));
paramCounts.put("setenv$", new Range(2, 2));
paramCounts.put("seventh", new Range(1, 1));
paramCounts.put("signum", new Range(1, 1));
paramCounts.put("sixth", new Range(1, 1));
paramCounts.put("standard-char-p", new Range(1, 1));
paramCounts.put("string", new Range(1, 1));
paramCounts.put("string-append", new Range(2, 2));
paramCounts.put("string-downcase", new Range(1, 1));
paramCounts.put("string-equal", new Range(2, 2));
paramCounts.put("string-listp", new Range(1, 1));
paramCounts.put("string-upcase", new Range(1, 1));
paramCounts.put("string<", new Range(2, 2));
paramCounts.put("string<=", new Range(2, 2));
paramCounts.put("string>", new Range(2, 2));
paramCounts.put("string>=", new Range(2, 2));
paramCounts.put("stringp", new Range(1, 1));
paramCounts.put("strip-cars", new Range(1, 1));
paramCounts.put("strip-cdrs", new Range(1, 1));
paramCounts.put("sublis", new Range(2, 2));
paramCounts.put("subseq", new Range(3, 3));
paramCounts.put("subsetp-eq", new Range(2, 2));
paramCounts.put("subsetp-equal", new Range(2, 2));
paramCounts.put("subst", new Range(3, 3));
paramCounts.put("substitute", new Range(3, 3));
paramCounts.put("symbol-<", new Range(2, 2));
paramCounts.put("symbol-alistp", new Range(1, 1));
paramCounts.put("symbol-listp", new Range(1, 1));
paramCounts.put("symbol-name", new Range(1, 1));
paramCounts.put("symbolp", new Range(1, 1));
paramCounts.put("sys-call-status", new Range(1, 1));
paramCounts.put("take", new Range(2, 2));
paramCounts.put("tenth", new Range(1, 1));
paramCounts.put("the", new Range(2, 2));
paramCounts.put("third", new Range(1, 1));
paramCounts.put("true-list-listp", new Range(1, 1));
paramCounts.put("true-listp", new Range(1, 1));
paramCounts.put("truncate", new Range(2, 2));
paramCounts.put("unary--", new Range(1, 1));
paramCounts.put("unary-/", new Range(1, 1));
paramCounts.put("union-equal", new Range(2, 2));
paramCounts.put("update-nth", new Range(3, 3));
paramCounts.put("upper-case-p", new Range(1, 1));
paramCounts.put("with-live-state", new Range(1, 1));
paramCounts.put("write-byte$", new Range(3, 3));
paramCounts.put("xor", new Range(2, 2));
paramCounts.put("zerop", new Range(1, 1));
paramCounts.put("zip", new Range(1, 1));
paramCounts.put("zp", new Range(1, 1));
paramCounts.put("zpf", new Range(1, 1));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("defconst", new Range(2, 3));
paramCounts.put("defdoc", new Range(2, 2));
paramCounts.put("defpkg", new Range(2, 5));
paramCounts.put("defproxy", new Range(4, 4));
paramCounts.put("local", new Range(1, 1));
paramCounts.put("remove-custom-keyword-hint", new Range(1, 1));
paramCounts.put("set-body", new Range(2, 2));
paramCounts.put("show-custom-keyword-hint-expansion", new Range(1, 1));
paramCounts.put("table", new Range(1, 5));
paramCounts.put("unmemoize", new Range(1, 1));
paramCounts.put("add-binop", new Range(2, 2));
paramCounts.put("add-dive-into-macro", new Range(2, 2));
paramCounts.put("add-include-book-dir", new Range(2, 2));
paramCounts.put("add-macro-alias", new Range(2, 2));
paramCounts.put("add-nth-alias", new Range(2, 2));
paramCounts.put("binop-table", new Range(1, 1));
paramCounts.put("delete-include-book-dir", new Range(1, 1));
paramCounts.put("remove-binop", new Range(1, 1));
paramCounts.put("remove-default-hints", new Range(1, 1));
paramCounts.put("remove-default-hints!", new Range(1, 1));
paramCounts.put("remove-dive-into-macro", new Range(1, 1));
paramCounts.put("remove-macro-alias", new Range(1, 1));
paramCounts.put("remove-nth-alias", new Range(1, 1));
paramCounts.put("remove-override-hints", new Range(1, 1));
paramCounts.put("remove-override-hints!", new Range(1, 1));
paramCounts.put("set-backchain-limit", new Range(1, 1));
paramCounts.put("set-bogus-defun-hints-ok", new Range(1, 1));
paramCounts.put("set-bogus-mutual-recursion-ok", new Range(1, 1));
paramCounts.put("set-case-split-limitations", new Range(1, 1));
paramCounts.put("set-checkpoint-summary-limit", new Range(1, 1));
paramCounts.put("set-compile-fns", new Range(1, 1));
paramCounts.put("set-debugger-enable", new Range(1, 1));
paramCounts.put("set-default-backchain-limit", new Range(1, 1));
paramCounts.put("set-default-hints", new Range(1, 1));
paramCounts.put("set-default-hints!", new Range(1, 1));
paramCounts.put("set-deferred-ttag-notes", new Range(2, 6));
paramCounts.put("set-enforce-redundancy", new Range(1, 1));
paramCounts.put("set-gag-mode", new Range(1, 1));
paramCounts.put("set-guard-checking", new Range(1, 1));
paramCounts.put("set-ignore-doc-string-error", new Range(1, 1));
paramCounts.put("set-ignore-ok", new Range(1, 1));
paramCounts.put("set-inhibit-output-lst", new Range(1, 1));
paramCounts.put("set-inhibited-summary-types", new Range(1, 1));
paramCounts.put("set-invisible-fns-table", new Range(1, 1));
paramCounts.put("set-irrelevant-formals-ok", new Range(1, 1));
paramCounts.put("set-ld-keyword-aliases", new Range(2, 6));
paramCounts.put("set-ld-redefinition-action", new Range(2, 5));
paramCounts.put("set-ld-skip-proofs", new Range(2, 2));
paramCounts.put("set-let*-abstraction", new Range(1, 1));
paramCounts.put("set-let*-abstractionp", new Range(1, 1));
paramCounts.put("set-match-free-default", new Range(1, 1));
paramCounts.put("set-match-free-error", new Range(1, 1));
paramCounts.put("set-measure-function", new Range(1, 1));
paramCounts.put("set-non-linear", new Range(1, 1));
paramCounts.put("set-non-linearp", new Range(1, 1));
paramCounts.put("set-nu-rewriter-mode", new Range(1, 1));
paramCounts.put("set-override-hints", new Range(1, 1));
paramCounts.put("set-override-hints!", new Range(1, 1));
paramCounts.put("set-print-clause-ids", new Range(1, 1));
paramCounts.put("set-prover-step-limit", new Range(1, 1));
paramCounts.put("set-raw-mode", new Range(1, 1));
paramCounts.put("set-raw-proof-format", new Range(1, 1));
paramCounts.put("set-rewrite-stack-limit", new Range(1, 1));
paramCounts.put("set-ruler-extenders", new Range(1, 1));
paramCounts.put("set-rw-cache-state", new Range(1, 1));
paramCounts.put("set-rw-cache-state!", new Range(1, 1));
paramCounts.put("set-saved-output", new Range(2, 2));
paramCounts.put("set-state-ok", new Range(1, 1));
paramCounts.put("set-tainted-ok", new Range(1, 1));
paramCounts.put("set-tainted-okp", new Range(1, 1));
paramCounts.put("set-verify-guards-eagerness", new Range(1, 1));
paramCounts.put("set-waterfall-parallelism", new Range(1, 2));
paramCounts.put("set-waterfall-printing", new Range(1, 1));
paramCounts.put("set-well-founded-relation", new Range(1, 1));
paramCounts.put("set-write-acl2x", new Range(2, 2));
paramCounts.put("with-guard-checking", new Range(2, 2));
}
public class ParseToken {
public int offset;
public int line;
public String name;
public List<String> params = new ArrayList<String>();
public Set<String> vars = new HashSet<String>();
}
public class Acl2ParserNotice extends DefaultParserNotice {
public Acl2ParserNotice(Acl2Parser parser, String msg, int line, int offs, int len, int level) {
super(parser, msg, line, offs, len);
//System.out.println("ERROR on line " + line + ": " + msg);
setLevel(level);
}
public Acl2ParserNotice(Acl2Parser parser, String msg,
ParseToken top, int end) {
this(parser, msg, top.line, top.offset, end - top.offset, ERROR);
}
public Acl2ParserNotice(Acl2Parser parser, String msg, int line,
Token token, int level) {
this(parser, msg, line, token.offset, token.textCount, level);
}
@Override
public boolean getShowInEditor() {
return getLevel() != INFO;
}
}
@Override
public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defproperty", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
+ String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
- functions.add(token.getLexeme().toLowerCase());
+ if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
+ functions.add(tokenName);
+ } else {
+ result.addNotice(new Acl2ParserNotice(this,
+ "A function with this name is already defined", line, token,
+ ParserNotice.ERROR));
+ }
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
- macros.add(token.getLexeme());
+ if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
+ macros.add(tokenName);
+ } else {
+ result.addNotice(new Acl2ParserNotice(this,
+ "A function with this name is already defined", line, token,
+ ParserNotice.ERROR));
+ }
} else if (top.name.equals("defconst") && top.params.size() == 1) {
- constants.add(token.getLexeme());
- String constName = token.getLexeme();
- if (!constName.startsWith("*") || !constName.endsWith("*")) {
+ if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
+ } else {
+ if (!constants.contains(tokenName)) {
+ constants.add(tokenName);
+ } else {
+ result.addNotice(new Acl2ParserNotice(this,
+ "A constant with this name is already defined", line, token,
+ ParserNotice.ERROR));
+ }
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book.exists());
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
result.addNotice(new Acl2ParserNotice(this, "<html><b>" +
htmlEncode(top.name) + "</b> is undefined.</html>",
line, token, ParserNotice.ERROR));
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
public static CacheSets parseBook(File book, File acl2Dir, Map<CacheKey, CacheSets> cache)
throws FileNotFoundException, BadLocationException {
CacheSets bookCache;
Scanner bookScanner = new Scanner(book);
bookScanner.useDelimiter("\\Z");
String bookContents = bookScanner.next();
bookScanner.close();
logger.info("PARSING: " + book);
book.lastModified();
Acl2Parser bookParser = new Acl2Parser(book.getParentFile(), acl2Dir);
bookParser.cache = cache;
RSyntaxDocument bookDoc = new IdeDocument(null);
bookDoc.insertString(0, bookContents, null);
bookParser.parse(bookDoc, null);
bookCache = new CacheSets();
bookCache.functions = bookParser.functions;
bookCache.constants = bookParser.constants;
bookCache.macros = bookParser.macros;
return bookCache;
}
private static String htmlEncode(String name) {
return name.replace("&", "&").replace("<", "<").replace(">", ">");
}
public void addParseListener(ParseListener parseListener) {
parseListeners.add(parseListener);
}
public File getAcl2Dir() {
return acl2Dir;
}
public void setAcl2Dir(File acl2Dir) {
this.acl2Dir = acl2Dir;
}
}
| false | true | public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defproperty", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
functions.add(token.getLexeme().toLowerCase());
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
macros.add(token.getLexeme());
} else if (top.name.equals("defconst") && top.params.size() == 1) {
constants.add(token.getLexeme());
String constName = token.getLexeme();
if (!constName.startsWith("*") || !constName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book.exists());
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
result.addNotice(new Acl2ParserNotice(this, "<html><b>" +
htmlEncode(top.name) + "</b> is undefined.</html>",
line, token, ParserNotice.ERROR));
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
| public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defproperty", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book.exists());
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
result.addNotice(new Acl2ParserNotice(this, "<html><b>" +
htmlEncode(top.name) + "</b> is undefined.</html>",
line, token, ParserNotice.ERROR));
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
|
diff --git a/org.amanzi.neo.loader/src/org/amanzi/neo/loader/AbstractLoader.java b/org.amanzi.neo.loader/src/org/amanzi/neo/loader/AbstractLoader.java
index 2c21ea2ea..0dd208c6b 100644
--- a/org.amanzi.neo.loader/src/org/amanzi/neo/loader/AbstractLoader.java
+++ b/org.amanzi.neo.loader/src/org/amanzi/neo/loader/AbstractLoader.java
@@ -1,2101 +1,2101 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.neo.loader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeSet;
import java.util.regex.Pattern;
import net.refractions.udig.catalog.CatalogPlugin;
import net.refractions.udig.catalog.ICatalog;
import net.refractions.udig.catalog.IService;
import org.amanzi.neo.core.INeoConstants;
import org.amanzi.neo.core.NeoCorePlugin;
import org.amanzi.neo.core.database.services.events.UpdateDatabaseEvent;
import org.amanzi.neo.core.database.services.events.UpdateViewEventType;
import org.amanzi.neo.core.enums.GeoNeoRelationshipTypes;
import org.amanzi.neo.core.enums.NetworkRelationshipTypes;
import org.amanzi.neo.core.enums.NetworkTypes;
import org.amanzi.neo.core.enums.NodeTypes;
import org.amanzi.neo.core.service.NeoServiceProvider;
import org.amanzi.neo.core.utils.ActionUtil;
import org.amanzi.neo.core.utils.ActionUtil.RunnableWithResult;
import org.amanzi.neo.core.utils.CSVParser;
import org.amanzi.neo.core.utils.NeoUtils;
import org.amanzi.neo.index.MultiPropertyIndex;
import org.amanzi.neo.loader.NetworkLoader.CRS;
import org.amanzi.neo.loader.internal.NeoLoaderPlugin;
import org.amanzi.neo.preferences.CommonCRSPreferencePage;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.preference.IPreferenceNode;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.preference.PreferenceNode;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.ReturnableEvaluator;
import org.neo4j.graphdb.StopEvaluator;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.Traverser.Order;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
public abstract class AbstractLoader {
private static final Logger LOGGER = Logger.getLogger(AbstractLoader.class);
// private static final Logger LOGGER = Logger.getLogger(AbstractLoader.class);
/** AbstractLoader DEFAULT_DIRRECTORY_LOADER field */
public static final String DEFAULT_DIRRECTORY_LOADER = "DEFAULT_DIRRECTORY_LOADER";
// protected HashMap<Integer, HeaderMaps> headersMap = new HashMap<Integer, HeaderMaps>();
// protected HashMap<Integer, Pair<Long, Long>> timeStamp = new HashMap<Integer, Pair<Long,
// Long>>();
protected HashMap<Integer, StoringProperty> storingProperties = new HashMap<Integer, StoringProperty>();
protected String typeName = "CSV";
protected GraphDatabaseService neo;
private NeoServiceProvider neoProvider;
protected HashMap<String, GisProperties> gisNodes = new HashMap<String, GisProperties>();
protected String filename = null;
protected String basename = null;
protected Display display;
private String fieldSepRegex;
protected String[] possibleFieldSepRegexes = new String[] {"\t", ",", ";"};
protected int lineNumber = 0;
private int limit = 0;
private long savedData = 0;
private long started = System.currentTimeMillis();
protected boolean headerWasParced;
// private ArrayList<MultiPropertyIndex<?>> indexes = new
// ArrayList<MultiPropertyIndex<?>>();
private final LinkedHashMap<String, ArrayList<MultiPropertyIndex< ? >>> indexes = new LinkedHashMap<String, ArrayList<MultiPropertyIndex< ? >>>();
private final LinkedHashMap<String, LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>>> mappedIndexes = new LinkedHashMap<String, LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>>>();
@SuppressWarnings("unchecked")
public static final Class[] NUMERIC_PROPERTY_TYPES = new Class[] {Integer.class, Long.class, Float.class, Double.class};
@SuppressWarnings("unchecked")
public static final Class[] KNOWN_PROPERTY_TYPES = new Class[] {Integer.class, Long.class, Float.class, Double.class, String.class};
private boolean indexesInitialized = false;
private boolean taskSetted;
protected CSVParser parser;
public class Header {
private static final int MAX_PROPERTY_VALUE_COUNT = 100; // discard
// calculate spread after this number of data points
int index;
String key;
String name;
HashMap<Class< ? extends Object>, Integer> parseTypes = new HashMap<Class< ? extends Object>, Integer>();
Double min = Double.POSITIVE_INFINITY;
Double max = Double.NEGATIVE_INFINITY;
HashMap<Object, Integer> values = new HashMap<Object, Integer>();
boolean isIdentityHeader=false;
int parseCount = 0;
int countALL = 0;
Header(String name, String key, int index) {
this.index = index;
this.name = name;
this.key = key;
for (Class< ? extends Object> klass : KNOWN_PROPERTY_TYPES) {
parseTypes.put(klass, 0);
}
}
Header(Header old) {
this(old.name, old.key, old.index);
this.parseCount = old.parseCount;
this.values = old.values;
this.min = old.min;
this.max = old.max;
this.countALL = old.countALL;
this.isIdentityHeader=old.isIdentityHeader;
}
protected boolean invalid(String field) {
return field == null || field.length() < 1 || field.equals("?");
}
Object parse(String field) {
if (invalid(field))
return null;
parseCount++;
try {
int value = Integer.parseInt(field);
incValue(value);
incType(Integer.class);
return value;
} catch (Exception e) {
try {
float value = Float.parseFloat(field);
incValue(value);
incType(Float.class);
return value;
} catch (Exception e2) {
incValue(field);
incType(String.class);
return field;
}
}
}
protected void incType(Class< ? extends Object> klass) {
parseTypes.put(klass, parseTypes.get(klass) + 1);
}
protected Object incValue(Object value) {
if (value != null) {
countALL++;
if (value instanceof Number) {
double doubleValue = ((Number)value).doubleValue();
min = Math.min(min, doubleValue);
max = Math.max(max, doubleValue);
}
}
if (values != null) {
Integer count = values.get(value);
if (count == null) {
count = 0;
}
boolean discard = false;
if (count == 0) {
// We have a new value, so adding it will increase the size
// of the map
// We should perform threshold tests to decide whether to
// drop the map or not
if (values.size() >= MAX_PROPERTY_VALUE_COUNT) {
// Exceeded absolute threashold, drop map
LOGGER.debug("Property values exceeded maximum count, no longer tracking value set: " + this.key);
discard = true;
}
// TODO if we do not use parse method this check will be
// wrong
// else if (values.size() >=
// MIN_PROPERTY_VALUE_SPREAD_COUNT) {
// // Exceeded minor threshold, test spread and then decide
// float spread = (float)values.size() / (float)parseCount;
// if (spread > MAX_PROPERTY_VALUE_SPREAD) {
// // Exceeded maximum spread, too much property variety,
// drop map
// LOGGER.debug("Property shows excessive variation, no longer tracking value set: "
// + this.key);
// discard = true;
// }
// }
}
//do not drop statistics for identity properties
if (discard && !isIdentityHeader) {
// Detected too much variety in property values, stop
// counting
dropStats();
} else {
values.put(value, count + 1);
}
}
return value;
}
boolean shouldConvert() {
return parseCount > 10;
}
Class< ? extends Object> knownType() {
Class< ? extends Object> best = String.class;
int maxCount = 0;
int countFound = 0;
for (Class< ? extends Object> klass : parseTypes.keySet()) {
int count = parseTypes.get(klass);
// Bias towards Strings
if (klass == String.class)
count *= 2;
if (maxCount < parseTypes.get(klass)) {
maxCount = count;
best = klass;
}
if (count > 0) {
countFound++;
}
}
if (countFound > 1) {
AbstractLoader.this.notify("Header " + key + " had multiple type matches: ");
for (Class< ? extends Object> klass : parseTypes.keySet()) {
int count = parseTypes.get(klass);
if (count > 0) {
AbstractLoader.this.notify("\t" + count + ": " + klass + " => " + key);
}
}
}
return best;
}
/**
* Disable statistics collection for this header. This is useful if the property is
* undesirable in some later statistical analysis, either because it is too diverse, or it
* is a property we can 'grouped by' during the load. Examples of excessive diversity would
* be element names, ids, timestamps, locations. Examples of grouping by would be site
* properties, timestamps and locations.
*/
public void dropStats() {
values = null;
}
}
protected class IntegerHeader extends Header {
IntegerHeader(Header old) {
super(old);
}
@Override
Integer parse(String field) {
if (invalid(field))
return null;
parseCount++;
return (Integer)incValue(Integer.parseInt(field));
}
@Override
boolean shouldConvert() {
return false;
}
@Override
Class<Integer> knownType() {
return Integer.class;
}
}
protected class LongHeader extends Header {
LongHeader(Header old) {
super(old);
}
@Override
Long parse(String field) {
if (invalid(field))
return null;
parseCount++;
return (Long)incValue(Long.parseLong(field));
}
@Override
boolean shouldConvert() {
return false;
}
@Override
Class<Long> knownType() {
return Long.class;
}
}
protected class FloatHeader extends Header {
FloatHeader(Header old) {
super(old);
}
@Override
Float parse(String field) {
if (invalid(field))
return null;
parseCount++;
return (Float)incValue(Float.parseFloat(field));
}
@Override
boolean shouldConvert() {
return false;
}
@Override
Class<Float> knownType() {
return Float.class;
}
}
protected class StringHeader extends Header {
StringHeader(Header old) {
super(old);
}
@Override
String parse(String field) {
if (invalid(field))
return null;
parseCount++;
return (String)incValue(field);
}
@Override
boolean shouldConvert() {
return false;
}
@Override
Class<String> knownType() {
return String.class;
}
}
protected interface PropertyMapper {
public Object mapValue(String originalValue);
}
protected class MappedHeaderRule {
private final String name;
protected String key;
private final PropertyMapper mapper;
MappedHeaderRule(String name, String key, PropertyMapper mapper) {
this.key = key;
this.name = name;
this.mapper = mapper;
}
}
/**
* This class allows for either replacing of duplicating properties. See addMappedHeader for
* details.
*
* @author craig
* @since 1.0.0
*/
protected class MappedHeader extends Header {
protected PropertyMapper mapper;
Class< ? extends Object> knownClass = null;
MappedHeader(Header old, MappedHeaderRule mapRule) {
super(old);
this.key = mapRule.key;
if (mapRule.name != null) {
// We only replace the name if the new one is valid, otherwise
// inherit from the old
// header
// This allows for support of header replacing rules, as well as
// duplicating rules
this.name = mapRule.name;
}
this.mapper = mapRule.mapper;
this.values = new HashMap<Object, Integer>(); // need to make a new
// values list,
// otherwise we share the same data as
// the original
}
@Override
Object parse(String field) {
if (invalid(field))
return null;
Object result = mapper.mapValue(field);
parseCount++;
if (knownClass == null && result != null) {
// Determine converted class from very first conversion
knownClass = result.getClass();
}
return incValue(result);
}
@Override
boolean shouldConvert() {
return false;
}
@Override
Class< ? extends Object> knownType() {
return knownClass;
}
}
/**
* Convenience implementation of a property mapper that understands date and time formats.
* Construct with a date-time pattern understood by java.text.SimpleDateFormat. If you pass null
* of an invalid format, then the default of "HH:mm:ss" will be used.
*
* @author craig
* @since 1.0.0
*/
protected class DateTimeMapper extends DateMapper {
/**
* @param format
*/
protected DateTimeMapper(String format) {
super(format);
}
@Override
public Object mapValue(String time) {
Date datetime = (Date)super.mapValue(time);
return datetime == null ? 0L : datetime.getTime();
}
}
/**
* Convenience implementation of a property mapper that understands date formats. Construct with
* a date-time pattern understood by java.text.SimpleDateFormat. If you pass null of an invalid
* format, then the default of "HH:mm:ss" will be used.
*/
protected class DateMapper implements PropertyMapper {
private SimpleDateFormat format;
protected DateMapper(String format) {
try {
this.format = new SimpleDateFormat(format);
} catch (Exception e) {
this.format = new SimpleDateFormat("HH:mm:ss");
}
}
@Override
public Object mapValue(String time) {
Date datetime;
try {
datetime = format.parse(time);
} catch (ParseException e) {
error(e.getLocalizedMessage());
return null;
}
return datetime;
}
}
/**
* Convenience implementation of a property mapper that assumes the object is a String. This is
* useful for overriding the default behavior of detecting field formats, and simply keeping the
* original strings. For example if the site name happens to contain only numbers, but we still
* want to see it as a string because it is the name.
*
* @author craig
* @since 1.0.0
*/
protected class StringMapper implements PropertyMapper {
@Override
public Object mapValue(String value) {
return value;
}
}
/**
* Initialize Loader with a specified set of parameters
*
* @param type defaults to 'CSV' if empty
* @param neoService defaults to looking up from Neoclipse if null
* @param fileName name of file to load
* @param display Display to use for scheduling plugin lookups and message boxes, or null
*/
protected void initialize(String typeString, GraphDatabaseService neoService, String filenameString, Display display) {
if (typeString != null && !typeString.isEmpty()) {
this.typeName = typeString;
}
initializeNeo(neoService, display);
this.display = display;
this.filename = filenameString;
this.basename = (new File(filename)).getName();
}
protected void initializeNeo(GraphDatabaseService neoService, Display display) {
if (neoService == null) {
// if Display is given than start Neo using syncExec
if (display != null) {
display.syncExec(new Runnable() {
public void run() {
initializeNeo();
}
});
}
// if Display is not given than initialize Neo as usual
else {
initializeNeo();
}
} else {
this.neo = neoService;
}
}
private void initializeNeo() {
if (this.neoProvider == null)
this.neoProvider = NeoServiceProvider.getProvider();
if (this.neo == null)
this.neo = this.neoProvider.getService();
}
protected void determineFieldSepRegex(String line) {
int maxMatch = 0;
for (String regex : possibleFieldSepRegexes) {
String[] fields = line.split(regex);
if (fields.length > maxMatch) {
maxMatch = fields.length;
fieldSepRegex = regex;
}
}
parser = new CSVParser(fieldSepRegex.charAt(0));
}
protected List<String> splitLine(String line) {
return parser.parse(line);
}
/**
* Converts to lower case and replaces all illegal characters with '_' and removes trailing '_'.
* This is useful for creating a version of a header or property name that can be used as a
* variable or method name in programming code, notably in Ruby DSL code.
*
* @param original header String
* @return edited String
*/
protected final static String cleanHeader(String header) {
return header.replaceAll("[\\s\\-\\[\\]\\(\\)\\/\\.\\\\\\:\\#]+", "_").replaceAll("[^\\w]+", "_").replaceAll("_+", "_").replaceAll("\\_$", "").toLowerCase();
}
/**
* Add a property name and regular expression for a known header. This is used if we want the
* property name in the database to be some specific text, not the header text in the file. The
* regular expression is used to find the header in the file to associate with the new property
* name. Note that the original property will not be saved using its original name. It will be
* saved with the specified name provided. For example, if you want the first field found that
* starts with 'lat' to be saved in a property called 'y', then you would call this using:
*
* <pre>
* addKnownHeader("y", "lat.*");
* </pre>
* @param key the name to use for the property
* @param regex a regular expression to use to find the property
* @param isIdentityHeader true if the property is an identity property
*/
protected void addKnownHeader(Integer headerId, String key, String regex, boolean isIdentityHeader) {
addKnownHeader(headerId, key, new String[] {regex}, isIdentityHeader);
}
/**
* Add a property name and list of regular expressions for a single known header. This is used
* if we want the property name in the database to be some specific text, not the header text in
* the file. The regular expressions are used to find the header in the file to associate with
* the new property name. Note that the original property will not be saved using its original
* name. It will be saved with the specified name provided. For example, if you want the first
* field found that starts with either 'lat' or 'y_wert' to be saved in a property called 'y',
* then you would call this using:
*
* <pre>
* addKnownHeader("y", new String[] {"lat.*", "y_wert.*"}, true);
* </pre>
* @param key the name to use for the property
* @param isIdentityHeader true if the property is an identity property
* @param array of regular expressions to use to find the single property
*/
protected void addKnownHeader(Integer headerId, String key, String[] regexes, boolean isIdentityHeader) {
HeaderMaps header = getHeaderMap(headerId);
if (header.knownHeaders.containsKey(key)) {
List<String> value = header.knownHeaders.get(key);
value.addAll(Arrays.asList(regexes));
header.knownHeaders.put(key, value);
} else {
header.knownHeaders.put(key, Arrays.asList(regexes));
}
if (isIdentityHeader) {
header.identityHeaders.add(key);
}
}
/**
* Add a number of regular expression strings to use as filters for deciding which properties to
* save. If this method is never used, and the filters are empty, then all properties are
* processed. Since the saving code is done in the specific loader, not using this method can
* cause a lot more parsing of data than is necessary, so it is advised to use this. Note also
* that the filter regular expressions are applied to the cleaned headers, not the original ones
* found in the file.
*
* @param filters
*/
protected void addHeaderFilters(Integer headerMapId, String[] filters) {
HeaderMaps header = getHeaderMap(headerMapId);
for (String filter : filters) {
header.headerFilters.add(Pattern.compile(filter));
}
}
/**
* gets header map
*
* @param headerId
* @return
*/
protected HeaderMaps getHeaderMap(Integer index) {
StoringProperty sProp = storingProperties.get(index);
if (sProp == null) {
sProp = new StoringProperty(getStoringNode(index));
storingProperties.put(index, sProp);
}
HeaderMaps header = sProp.getHeaders();
if (header == null) {
header = new HeaderMaps();
sProp.setHeaders(header);
}
return header;
}
/**
* Add a special header that creates a new property based on the existence of another property.
* This includes a mapper that modifies the contents of the value interpreted. For example, if
* you want to create a new property called 'active' that contains only 'yes/no' values and is
* based on finding the text 'on air' inside another property, use this:
*
* <pre>
* addMappedHeader("status", "Active", "active", new PropertyMapper() {
* public String mapValue(String originalValue) {
* return originalValue.toLowerCase().contains("on air") ? "yes" : "no";
* }
* });
* </pre>
*
* @param original header key to base new header on
* @param name of new header, or null to use the old header (and replace it)
* @param key of new header
* @param mapper the mapper required to convert values from the old to the new
*/
protected final void addMappedHeader(Integer headerMapId, String original, String name, String key, PropertyMapper mapper) {
HeaderMaps header = getHeaderMap(headerMapId);
header.mappedHeaders.put(original, new MappedHeaderRule(name, key, mapper));
}
/**
* This uses the same PropertyMapper mechanism as the addMappedHeader() method, but does not
* create a new property, instead it replaces the original property. Internally it uses the same
* key for original and new property and also sets the new name to null to signal the system to
* do replacement. This is especially useful if you want to override the default header parsing
* logic with your own custom logic. For example, to keep string values for a property:
*
* <pre>
* useMapper("site", new StringMapper());
* </pre>
*
* @param key of header/property
* @param mapper the mapper required to convert values
*/
protected final void useMapper(Integer headerMapId, String key, PropertyMapper mapper) {
HeaderMaps headerMap = getHeaderMap(headerMapId);
headerMap.mappedHeaders.put(key, new MappedHeaderRule(null, key, mapper));
}
protected final void dropHeaderStats(Integer headerMapId, String[] keys) {
HeaderMaps headerMap = getHeaderMap(headerMapId);
headerMap.dropStatsHeaders.addAll(Arrays.asList(keys));
}
protected final void addNonDataHeaders(Integer headerMapId, Collection<String> keys) {
HeaderMaps headerMap = getHeaderMap(headerMapId);
headerMap.dropStatsHeaders.addAll(keys);
headerMap.nonDataHeaders.addAll(keys);
}
protected final void addIdentityHeaders(Integer headerMapId, Collection<String> keys) {
HeaderMaps headerMap = getHeaderMap(headerMapId);
headerMap.dropStatsHeaders.addAll(keys);
headerMap.nonDataHeaders.addAll(keys);
headerMap.identityHeaders.addAll(keys);
}
/**
* Parse possible header lines and build a set of header objects to be used to parse all data
* lines later. This allows us to deal with several requirements:
* <ul>
* <li>Know when we have passed the header and are in the data body of the file</li>
* <li>Have objects that automatically learn the type of the data as the data is parsed</li>
* <li>Support mapping headers to known specific names</li>
* <li>Support mapping values to different values using pre-defined mapper code</li>
* </ul>
*
* @param line to parse as the header line
*/
protected final void parseHeader(String line) {
debug(line);
determineFieldSepRegex(line);
List<String> fields = splitLine(line);
if (fields.size() < 2)
return;
int index = 0;
for (String headerName : fields) {
String header = cleanHeader(headerName);
for (StoringProperty sProp : storingProperties.values()) {
HeaderMaps headerMap = sProp.getHeaders();
if (headerMap.headerAllowed(header)) {
boolean added = false;
debug("Added header[" + index + "] = " + header);
KNOWN: for (String key : headerMap.knownHeaders.keySet()) {
if (!headerMap.headers.containsKey(key)) {
for (String regex : headerMap.knownHeaders.get(key)) {
for (String testString : new String[] {header, headerName}) {
if (testString.toLowerCase().matches(regex.toLowerCase())) {
debug("Added known header[" + index + "] = " + key);
if (!headerMap.identityHeaders.contains(key)){
headerMap.headers.put(key, new Header(headerName, key, index));
}else{
final Header identityHeader = new Header(headerName, key, index);
identityHeader.isIdentityHeader=true;
headerMap.headers.put(key, identityHeader);
}
added = true;
break KNOWN;
}
}
}
}
}
if (!added/* !headers.containsKey(header) */) {
if (!headerMap.identityHeaders.contains(header)){
headerMap.headers.put(header, new Header(headerName, header, index));
}else{
final Header identityHeader = new Header(headerName, header, index);
identityHeader.isIdentityHeader=true;
headerMap.headers.put(header, identityHeader);
}
}
}
headerWasParced = headerWasParced || !headerMap.headers.isEmpty();
}
index++;
}
// Now add any new properties created from other existing properties
// using mapping rules
for (StoringProperty sProp : storingProperties.values()) {
HeaderMaps headerMap = sProp.getHeaders();
for (String key : headerMap.mappedHeaders.keySet()) {
if (headerMap.headers.containsKey(key)) {
MappedHeaderRule mapRule = headerMap.mappedHeaders.get(key);
if (headerMap.headers.containsKey(mapRule.key)) {
// We only allow replacement if the user passed null for
// the name
if (mapRule.name == null) {
headerMap.headers.put(mapRule.key, new MappedHeader(headerMap.headers.get(key), mapRule));
} else {
notify("Cannot add mapped header with key '" + mapRule.key + "': header with that name already exists");
}
} else {
headerMap.headers.put(mapRule.key, new MappedHeader(headerMap.headers.get(key), mapRule));
}
} else {
notify("No original header found matching mapped header key: " + key);
}
}
for (String key : headerMap.dropStatsHeaders) {
Header header = headerMap.headers.get(key);
//do not drop stats for identity headers
if (header != null && !header.isIdentityHeader) {
header.dropStats();
}
}
}
}
protected Transaction mainTx;
protected int commitSize = 5000;
// protected List<String> getNumericProperties() {
// ArrayList<String> results = new ArrayList<String>();
// for (Class< ? extends Object> klass : NUMERIC_PROPERTY_TYPES) {
// results.addAll(getProperties(klass));
// }
// return results;
// }
// protected List<String> getDataProperties() {
// ArrayList<String> results = new ArrayList<String>();
// results.addAll(getNumericProperties());
// for (String key : getProperties(String.class)) {
// if (headers.get(key).parseCount > 0) {
// results.add(key);
// }
// }
// return results;
// }
protected final LinkedHashMap<String, Object> makeDataMap(List<String> fields) {
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
for (StoringProperty sProp : storingProperties.values()) {
HeaderMaps headerMap = sProp.getHeaders();
for (String key : headerMap.headers.keySet()) {
try {
Header header = headerMap.headers.get(key);
String field = fields.get(header.index);
if (field == null || field.length() < 1 || field.equals("?")) {
continue;
}
Object value = header.parse(field);
map.put(key, value);
// TODO: Decide if we should actually use the name here
// Now speed up parsing once we are certain of the column types
if (header.shouldConvert()) {
Class< ? extends Object> klass = header.knownType();
if (klass == Integer.class) {
headerMap.headers.put(key, new IntegerHeader(header));
} else if (klass == Float.class) {
headerMap.headers.put(key, new FloatHeader(header));
} else {
headerMap.headers.put(key, new StringHeader(header));
}
}
} catch (Exception e) {
// TODO Handle Exception
}
}
}
return map;
}
private Display currentDisplay = null;
protected final void debug(final String line) {
runInDisplay(new Runnable() {
public void run() {
NeoLoaderPlugin.debug(typeName + ":" + basename + ":" + status() + ": " + line);
}
});
}
protected final void info(final String line) {
runInDisplay(new Runnable() {
public void run() {
NeoLoaderPlugin.notify(typeName + ":" + basename + ":" + status() + ": " + line);
}
});
}
protected final void notify(final String line) {
runInDisplay(new Runnable() {
public void run() {
NeoLoaderPlugin.notify(typeName + ":" + basename + ":" + status() + ": " + line);
}
});
}
protected final void error(final String line) {
runInDisplay(new Runnable() {
public void run() {
NeoLoaderPlugin.notify(typeName + ":" + basename + ":" + status() + ": " + line);
}
});
}
private final void runInDisplay(Runnable runnable) {
if (display != null) {
if (currentDisplay == null) {
currentDisplay = PlatformUI.getWorkbench().getDisplay();
}
currentDisplay.asyncExec(runnable);
} else {
runnable.run();
}
}
protected final String status() {
if (started <= 0)
started = System.currentTimeMillis();
return (lineNumber > 0 ? "line:" + lineNumber : "" + ((System.currentTimeMillis() - started) / 1000.0) + "s");
}
public void setLimit(int value) {
this.limit = value;
}
protected boolean isOverLimit() {
return limit > 0 && savedData > limit;
}
protected boolean setNewIndexProperty(Map<String, Header> headers, Node eventNode, String key, Object parsedValue) {
if (eventNode.hasProperty(key)) {
return false;
}
setIndexProperty(headers, eventNode, key, parsedValue);
return true;
}
/**
* Sets index property
*
* @param headers index header
* @param eventNode node
* @param key property key
* @param parsedValue parsed value
*/
protected void setIndexProperty(Map<String, Header> headers, Node eventNode, String key, Object parsedValue) {
if (parsedValue == null) {
return;
}
eventNode.setProperty(key, parsedValue);
Header header = headers.get(key);
if (header == null) {
header = new Header(key, key, 1);
headers.put(key, header);
}
header.parseCount++;
header.incValue(parsedValue);
header.incType(parsedValue.getClass());
}
/**
* Sets index property
*
* @param headers index header
* @param eventNode node
* @param key property key
* @param nonParsedValue parsed value
*/
protected void setIndexPropertyNotParcedValue(LinkedHashMap<String, Header> headers, Node eventNode, String key, String nonParsedValue) {
if (StringUtils.isEmpty(nonParsedValue)) {
return;
}
Header header = headers.get(key);
if (header == null) {
header = new Header(key, key, 1);
headers.put(key, header);
}
Object value = header.parse(nonParsedValue);
eventNode.setProperty(key, value);
}
private void incSaved() {
savedData++;
}
/**
* This is the main method of the class. It opens the file, iterates over the contents and calls
* parseLine(String) on each line. The subclass needs to implement parseLine(String) to
* interpret the data and save it to the database.
*
* @param monitor
* @throws IOException
*/
public void run(IProgressMonitor monitor) throws IOException {
if (monitor != null && !taskSetted){
monitor.beginTask(basename, 100);
}
CountingFileInputStream is = new CountingFileInputStream(new File(filename));
String characterSet = NeoLoaderPlugin.getDefault().getCharacterSet();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, characterSet));
mainTx = neo.beginTx();
NeoUtils.addTransactionLog(mainTx, Thread.currentThread(), "AbstractLoader");
try {
initializeIndexes();
int perc = is.percentage();
int prevPerc = 0;
int prevLineNumber = 0;
String line;
headerWasParced = !needParceHeaders();
while ((line = reader.readLine()) != null) {
lineNumber++;
if (!headerWasParced) {
parseHeader(line);
} else {
parseLine(line);
}
if (monitor != null) {
if (monitor.isCanceled())
break;
perc = is.percentage();
if (perc > prevPerc) {
monitor.subTask(basename + ":" + lineNumber + " (" + perc + "%)");
monitor.worked(perc - prevPerc);
prevPerc = perc;
}
}
if (lineNumber > prevLineNumber + commitSize) {
commit(true);
prevLineNumber = lineNumber;
}
if (isOverLimit())
break;
}
commit(true);
reader.close();
saveProperties();
finishUpIndexes();
finishUp();
} finally {
commit(false);
}
}
/**
* check necessity of parsing headers
*
* @return
*/
protected abstract boolean needParceHeaders();
// TODO add thread safe???
protected void addIndex(String nodeType, MultiPropertyIndex< ? > index) {
ArrayList<MultiPropertyIndex< ? >> indList = indexes.get(nodeType);
if (indList == null) {
indList = new ArrayList<MultiPropertyIndex< ? >>();
indexes.put(nodeType, indList);
}
if (!indList.contains(index)) {
indList.add(index);
}
}
protected void addMappedIndex(String key, String nodeType, MultiPropertyIndex< ? > index) {
LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>> mappIndex = mappedIndexes.get(key);
if (mappIndex == null) {
mappIndex = new LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>>();
mappedIndexes.put(key, mappIndex);
}
HashSet<MultiPropertyIndex< ? >> indSet = mappIndex.get(nodeType);
if (indSet == null) {
indSet = new HashSet<MultiPropertyIndex< ? >>();
mappIndex.put(nodeType, indSet);
}
indSet.add(index);
}
protected void removeIndex(String nodeType, MultiPropertyIndex< ? > index) {
ArrayList<MultiPropertyIndex< ? >> indList = indexes.get(nodeType);
if (indList != null) {
indList.remove(index);
}
}
/**
*remove mapped index
*
* @param key map key
* @param nodeType - node type
* @param index - index
*/
private void removeMappedIndex(String key, String nodeType, MultiPropertyIndex< ? > index) {
LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>> mapIn = mappedIndexes.get(key);
if (mapIn != null) {
HashSet<MultiPropertyIndex< ? >> indList = mapIn.get(nodeType);
if (indList != null) {
indList.remove(index);
}
}
}
protected void index(Node node) {
String nodeType = NeoUtils.getNodeType(node, "");
ArrayList<MultiPropertyIndex< ? >> indList = indexes.get(nodeType);
if (indList == null) {
return;
}
for (MultiPropertyIndex< ? > index : indList) {
try {
index.add(node);
} catch (IOException e) {
// TODO:Log error
removeIndex(nodeType, index);
}
}
}
/**
* Indexes mapped
*
* @param key - index key
* @param node - node
*/
protected void index(String key, Node node) {
String nodeType = NeoUtils.getNodeType(node, "");
LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>> indMap = mappedIndexes.get(key);
if (indMap == null) {
return;
}
HashSet<MultiPropertyIndex< ? >> indList = indMap.get(nodeType);
if (indList == null) {
return;
}
for (MultiPropertyIndex< ? > index : indList) {
try {
index.add(node);
} catch (IOException e) {
NeoLoaderPlugin.error(e.getLocalizedMessage());
removeMappedIndex(key, nodeType, index);
}
}
}
protected void flushIndexes() {
for (Entry<String, ArrayList<MultiPropertyIndex< ? >>> entry : indexes.entrySet()) {
for (MultiPropertyIndex< ? > index : entry.getValue()) {
try {
index.flush();
} catch (IOException e) {
// TODO:Log error
removeIndex(entry.getKey(), index);
}
}
}
for (Entry<String, LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>>> entryInd : mappedIndexes.entrySet()) {
if (entryInd.getValue() != null) {
for (Entry<String, HashSet<MultiPropertyIndex< ? >>> entry : entryInd.getValue().entrySet()) {
for (MultiPropertyIndex< ? > index : entry.getValue()) {
try {
index.flush();
} catch (IOException e) {
// TODO:Log error
removeMappedIndex(entryInd.getKey(), entry.getKey(), index);
}
}
}
}
}
}
protected void initializeIndexes() {
if (indexesInitialized) {
return;
}
for (Entry<String, ArrayList<MultiPropertyIndex< ? >>> entry : indexes.entrySet()) {
for (MultiPropertyIndex< ? > index : entry.getValue()) {
try {
index.initialize(this.neo, null);
} catch (IOException e) {
// TODO:Log error
removeIndex(entry.getKey(), index);
}
}
}
for (Entry<String, LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>>> entryInd : mappedIndexes.entrySet()) {
if (entryInd.getValue() != null) {
for (Entry<String, HashSet<MultiPropertyIndex< ? >>> entry : entryInd.getValue().entrySet()) {
for (MultiPropertyIndex< ? > index : entry.getValue()) {
try {
index.initialize(this.neo, null);
} catch (IOException e) {
NeoLoaderPlugin.error(e.getLocalizedMessage());
removeMappedIndex(entryInd.getKey(), entry.getKey(), index);
}
}
}
}
}
indexesInitialized = true;
}
protected void finishUpIndexes() {
for (Entry<String, ArrayList<MultiPropertyIndex< ? >>> entry : indexes.entrySet()) {
for (MultiPropertyIndex< ? > index : entry.getValue()) {
index.finishUp();
}
}
for (Entry<String, LinkedHashMap<String, HashSet<MultiPropertyIndex< ? >>>> entryInd : mappedIndexes.entrySet()) {
if (entryInd.getValue() != null) {
for (Entry<String, HashSet<MultiPropertyIndex< ? >>> entry : entryInd.getValue().entrySet()) {
for (MultiPropertyIndex< ? > index : entry.getValue()) {
index.finishUp();
}
}
}
}
}
protected void commit(boolean restart) {
if (mainTx != null) {
flushIndexes();
mainTx.success();
mainTx.finish();
// LOGGER.debug("Commit: Memory: "+(Runtime.getRuntime().totalMemory()
// -
// Runtime.getRuntime().freeMemory()));
if (restart) {
mainTx = neo.beginTx();
} else {
mainTx = null;
}
}
}
/**
* This method must be implemented by all readers to parse the data lines. It might save data
* directly to the database, or it might keep it in a cache for saving later, in the finishUp
* method. A common pattern is to block data into chunks, saving these to the database at
* reasonable points, and then using finishUp() to save any remaining data.
*
* @param line
*/
protected abstract void parseLine(String line);
/**
* After all lines have been parsed, this method is called, allowing the implementing class the
* opportunity to save any cached information, or write any final statistics. It is not abstract
* because it is possible, or even probable, to write an importer that does not need it.
*/
protected void finishUp() {
if (!isTest()) {
addRootToProject();
}
commit(true);
for (Map.Entry<Integer, StoringProperty> entry : storingProperties.entrySet()) {
Node storeNode = getStoringNode(entry.getKey());
entry.getValue().storeTimeStamp(storeNode);
if (storeNode != null)
storeNode.setProperty(INeoConstants.COUNT_TYPE_NAME, entry.getValue().getDataCounter());
}
}
/**
* Adds the root to project.
*/
protected void addRootToProject() {
for (Node root : getRootNodes()) {
String aweProjectName = LoaderUtils.getAweProjectName();
if (root != null) {
NeoCorePlugin.getDefault().getProjectService().addDataNodeToProject(aweProjectName, root);
}
}
}
/**
* Search the database for the 'gis' node for this dataset. If none found it created an
* appropriate node. The search is done for 'gis' nodes that reference the specified main node.
* If a node needs to be created it is linked to the main node so future searches will return
* it.
*
* @param mainNode main network or drive data node
* @return gis node for mainNode
*/
protected final Node findOrCreateGISNode(String gisName, String gisType, NetworkTypes fileType) {
GisProperties gisProperties = gisNodes.get(gisName);
if (gisProperties == null) {
Transaction transaction = neo.beginTx();
try {
Node reference = neo.getReferenceNode();
Node gis = NeoUtils.findGisNode(gisName, neo);
if (gis == null) {
gis = NeoUtils.createGISNode(reference, gisName, gisType, neo);
fileType.setTypeToNode(gis, neo);
}
gisProperties = new GisProperties(gis);
gisNodes.put(gisName, gisProperties);
transaction.success();
} finally {
transaction.finish();
}
}
// TODO add check on correct type!
return gisProperties.getGis();
}
protected void deleteTree(Node root) {
if (root != null) {
for (Relationship relationship : root.getRelationships(NetworkRelationshipTypes.CHILD, Direction.OUTGOING)) {
Node node = relationship.getEndNode();
deleteTree(node);
debug("Deleting node " + node + ": " + (node.hasProperty("name") ? node.getProperty("name") : ""));
deleteNode(node);
}
}
}
protected void deleteNode(Node node) {
if (node != null) {
for (Relationship relationship : node.getRelationships()) {
relationship.delete();
}
node.delete();
}
}
protected abstract String getPrymaryType(Integer key);
protected void saveProperties() {
for (Map.Entry<Integer, StoringProperty> spEntry : storingProperties.entrySet()) {
HeaderMaps headers = spEntry.getValue().getHeaders();
Node storingRootNode = getStoringNode(spEntry.getKey());
if (storingRootNode != null && headers != null) {
Transaction transaction = neo.beginTx();
try {
String primaryType = getPrymaryType(spEntry.getKey());
if (StringUtils.isNotEmpty(primaryType)) {
NeoUtils.setPrimaryType(storingRootNode, primaryType, neo);
}
Node propNode;
Relationship propRel = storingRootNode.getSingleRelationship(GeoNeoRelationshipTypes.PROPERTIES, Direction.OUTGOING);
if (propRel == null) {
propNode = neo.createNode();
propNode.setProperty(INeoConstants.PROPERTY_NAME_NAME, NeoUtils.getNodeName(storingRootNode, neo));
propNode.setProperty(INeoConstants.PROPERTY_TYPE_NAME, NodeTypes.GIS_PROPERTIES.getId());
storingRootNode.createRelationshipTo(propNode, GeoNeoRelationshipTypes.PROPERTIES);
} else {
propNode = propRel.getEndNode();
}
HashMap<String, Node> propTypeNodes = new HashMap<String, Node>();
for (Node node : propNode.traverse(Order.BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL_BUT_START_NODE,
GeoNeoRelationshipTypes.CHILD, Direction.OUTGOING)) {
propTypeNodes.put(node.getProperty("name").toString(), node);
}
for (Class< ? extends Object> klass : KNOWN_PROPERTY_TYPES) {
String typeName = makePropertyTypeName(klass);
List<String> properties = headers.getProperties(klass);
if (properties != null && properties.size() > 0) {
Node propTypeNode = propTypeNodes.get(typeName);
if (propTypeNode == null) {
propTypeNode = neo.createNode();
propTypeNode.setProperty(INeoConstants.PROPERTY_NAME_NAME, typeName);
propTypeNode.setProperty(INeoConstants.PROPERTY_TYPE_NAME, NodeTypes.GIS_PROPERTY.getId());
savePropertiesToNode(headers, propTypeNode, properties);
propNode.createRelationshipTo(propTypeNode, GeoNeoRelationshipTypes.CHILD);
} else {
TreeSet<String> combinedProperties = new TreeSet<String>();
String[] previousProperties = (String[])propTypeNode.getProperty(INeoConstants.NODE_TYPE_PROPERTIES, null);
if (previousProperties != null)
combinedProperties.addAll(Arrays.asList(previousProperties));
combinedProperties.addAll(properties);
savePropertiesToNode(headers, propTypeNode, combinedProperties);
}
}
}
transaction.success();
} finally {
transaction.finish();
}
}
}
}
/**
* get root for statistic node
*
* @param key - statistic id
* @return Node or null
*/
protected abstract Node getStoringNode(Integer key);
private void savePropertiesToNode(HeaderMaps headerMaps, Node propTypeNode, Collection<String> properties) {
propTypeNode.setProperty("properties", properties.toArray(new String[properties.size()]));
HashMap<String, Node> valueNodes = new HashMap<String, Node>();
ArrayList<String> noStatsProperties = new ArrayList<String>();
ArrayList<String> dataProperties = new ArrayList<String>();
ArrayList<String> identityProperties= new ArrayList<String>();
for (Relationship relation : propTypeNode.getRelationships(GeoNeoRelationshipTypes.PROPERTIES,GeoNeoRelationshipTypes.IDENTITY_PROPERTIES)) {
Node valueNode = relation.getEndNode();
String property = relation.getProperty("property", "").toString();
valueNodes.put(property, valueNode);
}
for (String property : properties) {
if (!headerMaps.nonDataHeaders.contains(property)) {
dataProperties.add(property);
}
Node valueNode = valueNodes.get(property);
Header header = headerMaps.headers.get(property);
- GeoNeoRelationshipTypes relType = !header.isIdentityHeader ? GeoNeoRelationshipTypes.PROPERTIES
- : GeoNeoRelationshipTypes.IDENTITY_PROPERTIES;
// if current headers do not contain information about property - we
// do not handling
// this property
if (header == null) {
continue;
}
+ GeoNeoRelationshipTypes relType = !header.isIdentityHeader ? GeoNeoRelationshipTypes.PROPERTIES
+ : GeoNeoRelationshipTypes.IDENTITY_PROPERTIES;
HashMap<Object, Integer> values = header.values;
Relationship valueRelation = null;
if (values == null) {
if (valueNode != null) {
for (Relationship relation : valueNode.getRelationships()) {
relation.delete();
}
valueNode.delete();
valueNode = null;
}
noStatsProperties.add(property);
} else {
if (header.isIdentityHeader){
noStatsProperties.add(property);
identityProperties.add(property);
}
if (valueNode == null) {
valueNode = neo.createNode();
valueRelation = propTypeNode.createRelationshipTo(valueNode, relType);
valueRelation.setProperty("property", property);
} else {
valueRelation = valueNode.getSingleRelationship(relType, Direction.INCOMING);
for (Object key : valueNode.getPropertyKeys()) {
Integer oldCount = (Integer)valueNode.getProperty(key.toString(), null);
if (oldCount == null) {
oldCount = 0;
}
Integer newCount = values.get(key);
if (newCount == null) {
newCount = 0;
}
values.put(key, oldCount + newCount);
}
}
int total = 0;
for (Object key : values.keySet()) {
valueNode.setProperty(key.toString(), values.get(key));
total += values.get(key);
}
if (valueRelation != null) {
valueRelation.setProperty("count", total);
}
}
if (valueNode == null) {
valueNode = neo.createNode();
valueRelation = propTypeNode.createRelationshipTo(valueNode, relType);
valueRelation.setProperty("property", property);
valueRelation.setProperty(INeoConstants.COUNT_TYPE_NAME, header.countALL);
}
if (!header.min.equals(Double.POSITIVE_INFINITY)) {
valueRelation.setProperty(INeoConstants.MIN_VALUE, header.min);
valueRelation.setProperty(INeoConstants.MAX_VALUE, header.max);
}
}
ArrayList<String> statsProperties = new ArrayList<String>(properties);
for (String noStat : noStatsProperties) {
statsProperties.remove(noStat);
}
propTypeNode.setProperty("data_properties", dataProperties.toArray(new String[0]));
propTypeNode.setProperty("stats_properties", statsProperties.toArray(new String[0]));
propTypeNode.setProperty("no_stats_properties", noStatsProperties.toArray(new String[0]));
propTypeNode.setProperty("identity_properties", identityProperties.toArray(new String[0]));
}
public static String makePropertyTypeName(Class< ? extends Object> klass) {
return klass.getName().replaceAll("java.lang.", "").toLowerCase();
}
/**
* This method adds the loaded data to the GIS catalog. This is achieved by
* <ul>
* <li>Cleaning the gis node of any old statistics, and then updating the basic statistics</li>
* <li>Then the data is added to the current AWE project</li>
* <li>The catalog for Neo data is created or updated</li>
* </ul>
*
* @throws MalformedURLException
*/
public static final void finishUpGis() throws MalformedURLException {
NeoServiceProvider neoProvider = NeoServiceProvider.getProvider();
if (neoProvider != null) {
addDataToCatalog();
}
}
public abstract Node[] getRootNodes();
/**
* Is this a test case running outside AWE application
*
* @return true if we have no NeoProvider and so are not running inside AWE
*/
protected final boolean isTest() {
return neoProvider == null;
}
public void clearCaches() {
for (StoringProperty sProp : storingProperties.values()) {
sProp.getHeaders().clearCaches();
}
}
/**
* This method adds the loaded data to the GIS catalog. The neo-catalog entry is created or
* updated.
*
* @throws MalformedURLException
*/
public static void addDataToCatalog() throws MalformedURLException {
// TODO: Lagutko, 17.12.2009, can be run as a Job
NeoServiceProvider neoProvider = NeoServiceProvider.getProvider();
if (neoProvider != null) {
String databaseLocation = neoProvider.getDefaultDatabaseLocation();
sendUpdateEvent(UpdateViewEventType.GIS);
ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
URL url = new URL("file://" + databaseLocation);
List<IService> services = CatalogPlugin.getDefault().getServiceFactory().createService(url);
for (IService service : services) {
if (catalog.getById(IService.class, service.getIdentifier(), new NullProgressMonitor()) != null) {
catalog.replace(service.getIdentifier(), service);
} else {
catalog.add(service);
}
}
neoProvider.commit();
}
}
public static void sendUpdateEvent(UpdateViewEventType aType) {
NeoCorePlugin.getDefault().getUpdateViewManager().fireUpdateView(new UpdateDatabaseEvent(aType));
}
/**
* Clean all gis nodes of any old statistics, and then update the basic statistics
*/
protected final void cleanupGisNode() {
for (GisProperties gisProperties : gisNodes.values()) {
cleanupGisNode(gisProperties);
}
}
/**
* Clean the gis node of any old statistics, and then update the basic statistics
*
* @param mainNode to use to connect to the AWE project
* @throws MalformedURLException
*/
private final void cleanupGisNode(GisProperties gisProperties) {
if (gisProperties != null) {
Transaction transaction = neo.beginTx();
try {
Node gis = gisProperties.getGis();
if (gisProperties.getBbox() != null) {
gis.setProperty(INeoConstants.PROPERTY_BBOX_NAME, gisProperties.getBbox());
}
gis.setProperty(INeoConstants.COUNT_TYPE_NAME, gisProperties.savedData);
HashSet<Node> nodeToDelete = new HashSet<Node>();
for (Relationship relation : gis.getRelationships(NetworkRelationshipTypes.AGGREGATION, Direction.OUTGOING)) {
nodeToDelete.add(relation.getEndNode());
}
for (Node node : nodeToDelete) {
NeoCorePlugin.getDefault().getProjectService().deleteNode(node);
}
transaction.success();
} finally {
transaction.finish();
}
}
}
/**
* Collects a list of GIS nodes that should be added to map
*
* @return list of GIS nodes
*/
protected ArrayList<Node> getGisNodes() {
ArrayList<Node> result = new ArrayList<Node>();
for (GisProperties gisPr : gisNodes.values()) {
result.add(gisPr.getGis());
}
return result;
}
/**
* adds gis to active map
*
* @param gis node
*/
public void addLayersToMap() {
LoaderUtils.addGisNodeToMap(getDataName(), getGisNodes().toArray(new Node[0]));
}
protected String getDataName(){
return filename;
}
/**
* @return Time in milliseconds since this loader started running
*/
protected long timeTaken() {
return System.currentTimeMillis() - started;
}
private void printHeaderStats() {
notify("Determined Columns:");
for (StoringProperty sProp : storingProperties.values()) {
HeaderMaps hm = sProp.getHeaders();
for (String key : hm.headers.keySet()) {
Header header = hm.headers.get(key);
if (header.parseCount > 0) {
notify("\t" + header.knownType() + " loaded: " + header.parseCount + " => " + key);
}
}
}
}
public void printStats(boolean verbose) {
printHeaderStats();
long taken = timeTaken();
notify("Finished loading " + basename + " data in " + (taken / 1000.0) + " seconds");
}
public void setCommitSize(int commitSize) {
this.commitSize = commitSize;
}
/**
* @return Returns the commitSize.
*/
public int getCommitSize() {
return commitSize;
}
/**
* This code finds the specified network node in the database, creating its own transaction for
* that.
*
* @param gis gis node
*/
protected Node findOrCreateNetworkNode(Node gisNode) {
return NeoUtils.findOrCreateNetworkNode(gisNode, basename, filename, neo);
}
/**
* get gisProperties by gis name
*
* @param name gis name
* @return GisProperties
*/
protected GisProperties getGisProperties(String name) {
return gisNodes.get(name);
}
public class HeaderMaps {
protected HashMap<Class< ? extends Object>, List<String>> typedProperties = null;
protected ArrayList<Pattern> headerFilters = new ArrayList<Pattern>();
protected LinkedHashMap<String, List<String>> knownHeaders = new LinkedHashMap<String, List<String>>();
protected LinkedHashMap<String, MappedHeaderRule> mappedHeaders = new LinkedHashMap<String, MappedHeaderRule>();
public LinkedHashMap<String, Header> headers = new LinkedHashMap<String, Header>();
protected TreeSet<String> dropStatsHeaders = new TreeSet<String>();
protected TreeSet<String> nonDataHeaders = new TreeSet<String>();
protected TreeSet<String> identityHeaders = new TreeSet<String>();
/**
* @return true if we have parsed the header line and know the properties to load
*/
protected boolean haveHeaders() {
return headers.size() > 0;
}
/**
* Get the header name for the specified key, if it exists
*
* @param key
* @return
*/
protected String headerName(String key) {
Header header = headers.get(key);
return header == null ? null : header.name;
}
public void clearCaches() {
this.headers.clear();
this.knownHeaders.clear();
}
protected boolean headerAllowed(String header) {
if (headerFilters == null || headerFilters.size() < 1) {
return true;
}
for (Pattern filter : headerFilters) {
if (filter.matcher(header).matches()) {
return true;
}
}
return false;
}
protected List<String> getProperties(Class< ? extends Object> klass) {
if (typedProperties == null) {
makeTypedProperties();
}
return typedProperties.get(klass);
}
private void makeTypedProperties() {
this.typedProperties = new HashMap<Class< ? extends Object>, List<String>>();
for (Class< ? extends Object> klass : KNOWN_PROPERTY_TYPES) {
this.typedProperties.put(klass, new ArrayList<String>());
}
for (String key : headers.keySet()) {
Header header = headers.get(key);
if (header.parseCount > 0) {
for (Class< ? extends Object> klass : KNOWN_PROPERTY_TYPES) {
if (header.knownType() == klass) {
this.typedProperties.get(klass).add(header.key);
}
}
}
}
}
}
public class StoringProperty {
// private Node storingNode;
private long dataCounter;
private Long timeStampMin;
private Long timeStampMax;
private HeaderMaps headers;
public StoringProperty(Node storingNode) {
// this.storingNode = storingNode;
if (storingNode != null)
dataCounter = (Long)storingNode.getProperty(INeoConstants.COUNT_TYPE_NAME, 0L);
}
/**
* @param storeNode node for store
*/
public void storeTimeStamp(Node storeNode) {
if (storeNode != null) {
if (timeStampMin != null) {
storeNode.setProperty(INeoConstants.MIN_TIMESTAMP, timeStampMin);
}
if (timeStampMax != null) {
storeNode.setProperty(INeoConstants.MAX_TIMESTAMP, timeStampMax);
}
}
}
/**
*inc saved;
*/
public void incSaved() {
dataCounter++;
}
/**
* @return Returns the dataCountre.
*/
public long getDataCounter() {
return dataCounter;
}
/**
* @return Returns the timeStampMin.
*/
public Long getTimeStampMin() {
return timeStampMin;
}
/**
* @param timeStampMin The timeStampMin to set.
*/
public void setTimeStampMin(Long timeStampMin) {
this.timeStampMin = timeStampMin;
}
/**
* @return Returns the timeStampMax.
*/
public Long getTimeStampMax() {
return timeStampMax;
}
/**
* @param timeStampMax The timeStampMax to set.
*/
public void setTimeStampMax(Long timeStampMax) {
this.timeStampMax = timeStampMax;
}
/**
* @return Returns the headers.
*/
public HeaderMaps getHeaders() {
return headers;
}
/**
* @param headers The headers to set.
*/
public void setHeaders(HeaderMaps headers) {
this.headers = headers;
}
/**
* @param dataCounter The dataCounter to set.
*/
public void setDataCounter(long dataCounter) {
this.dataCounter = dataCounter;
}
}
public static class GisProperties {
private final Node gis;
private CRS crs;
private double[] bbox;
private long savedData;
public GisProperties(Node gis) {
this.gis = gis;
bbox = (double[])gis.getProperty(INeoConstants.PROPERTY_BBOX_NAME, null);
savedData = (Long)gis.getProperty(INeoConstants.COUNT_TYPE_NAME, 0L);
}
/**
*inc saved;
*/
public void incSaved() {
savedData++;
}
protected final void checkCRS(float lat, float lon, String hint) {
if (crs == null) {
// TODO move CRS class and update CRS in amanzi.neo.core
crs = CRS.fromLocation(lat, lon, hint);
saveCRS();
}
}
/**
* initCRS
*/
public void initCRS() {
if (gis.hasProperty(INeoConstants.PROPERTY_CRS_TYPE_NAME) && gis.hasProperty(INeoConstants.PROPERTY_CRS_NAME)) {
crs = CRS.fromCRS((String)gis.getProperty(INeoConstants.PROPERTY_CRS_TYPE_NAME), (String)gis.getProperty(INeoConstants.PROPERTY_CRS_NAME));
}
}
/**
* ubdate bbox
*
* @param lat - latitude
* @param lon - longitude
*/
public final void updateBBox(double lat, double lon) {
if (bbox == null) {
bbox = new double[] {lon, lon, lat, lat};
} else {
if (bbox[0] > lon)
bbox[0] = lon;
if (bbox[1] < lon)
bbox[1] = lon;
if (bbox[2] > lat)
bbox[2] = lat;
if (bbox[3] < lat)
bbox[3] = lat;
}
}
/**
* @return Returns the gis.
*/
public Node getGis() {
return gis;
}
/**
* @return Returns the bbox.
*/
public double[] getBbox() {
return bbox;
}
/**
* @param crs The crs to set.
*/
public void setCrs(CRS crs) {
this.crs = crs;
}
/**
* @return
*/
public CRS getCrs() {
return crs;
}
/**
*save bbox to gis node
*/
public void saveBBox() {
if (getBbox() != null) {
gis.setProperty(INeoConstants.PROPERTY_BBOX_NAME, getBbox());
}
}
/**
*save CRS to gis node
*/
public void saveCRS() {
if (getCrs() != null) {
if (crs.getWkt() != null) {
gis.setProperty(INeoConstants.PROPERTY_WKT_CRS, crs.getWkt());
}
gis.setProperty(INeoConstants.PROPERTY_CRS_TYPE_NAME, crs.getType());// TODO remove?
// - not used
// in GeoNeo
gis.setProperty(INeoConstants.PROPERTY_CRS_NAME, crs.toString());
}
}
/**
*save CRS
*
* @param crs -CoordinateReferenceSystem
*/
public void setCrs(CoordinateReferenceSystem crs) {
setCrs(CRS.fromCRS(crs));
}
/**
* @param bbox The bbox to set.
*/
public void setBbox(double[] bbox) {
this.bbox = bbox;
}
}
/**
* @param key -key of value from preference store
* @return array of possible headers
*/
protected String[] getPossibleHeaders(String key) {
String text = NeoLoaderPlugin.getDefault().getPreferenceStore().getString(key);
String[] array = text.split(",");
List<String> result = new ArrayList<String>();
for (String string : array) {
String value = string.trim();
if (!value.isEmpty()) {
result.add(value);
}
}
return result.toArray(new String[0]);
}
/**
* Updates Min and Max timestamp values for this gis
*
* @param timestamp
*/
protected void updateTimestampMinMax(Integer key, final long timestamp) {
StoringProperty sProp = storingProperties.get(key);
if (sProp == null) {
sProp = new StoringProperty(getStoringNode(key));
storingProperties.put(key, sProp);
}
Long minTimeStamp = sProp.getTimeStampMin() == null ? timestamp : Math.min(sProp.getTimeStampMin(), timestamp);
Long maxTimeStamp = sProp.getTimeStampMax() == null ? timestamp : Math.max(sProp.getTimeStampMax(), timestamp);
sProp.setTimeStampMin(minTimeStamp);
sProp.setTimeStampMax(maxTimeStamp);
}
/**
* Sets property to node (if value!=null)
*
* @param node - node
* @param key - property key
* @param value - value
*/
protected void setProperty(PropertyContainer node, String key, Object value) {
if (value != null) {
node.setProperty(key, value);
}
}
/**
* @param gisProperties
* @return
*/
public static CoordinateReferenceSystem askCRSChoise(final GisProperties gisProperties) {
CoordinateReferenceSystem result = ActionUtil.getInstance().runTaskWithResult(new RunnableWithResult<CoordinateReferenceSystem>() {
private CoordinateReferenceSystem result;
@Override
public CoordinateReferenceSystem getValue() {
return result;
}
@Override
public void run() {
result = null;
CommonCRSPreferencePage page = new CommonCRSPreferencePage();
try {
LOGGER.debug(gisProperties.getCrs().epsg);
page.setSelectedCRS(org.geotools.referencing.CRS.decode(gisProperties.getCrs().epsg));
} catch (NoSuchAuthorityCodeException e) {
NeoLoaderPlugin.exception(e);
result = null;
return;
}
page.setTitle("Select Coordinate Reference System");
page.setSubTitle("Select the coordinate reference system from the list of commonly used CRS's, or add a new one with the Add button");
page.init(PlatformUI.getWorkbench());
PreferenceManager mgr = new PreferenceManager();
IPreferenceNode node = new PreferenceNode("1", page); //$NON-NLS-1$
mgr.addToRoot(node);
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
PreferenceDialog pdialog = new PreferenceDialog(shell, mgr);;
if (pdialog.open() == PreferenceDialog.OK) {
page.performOk();
result = page.getCRS();
}
}
});
return result;
}
/**
* Calculates list of files to import
*
* @param directoryName directory to import
* @param extension extension of File (can be null)
* @return list of files to import
*/
protected ArrayList<File> getAllLogFilePathes(String directoryName, String extension) {
File directory = new File(directoryName);
ArrayList<File> result = new ArrayList<File>();
for (File childFile : directory.listFiles()) {
if (childFile.isDirectory()) {
result.addAll(getAllLogFilePathes(childFile.getAbsolutePath(), extension));
} else if (childFile.isFile() && ((extension == null) || childFile.getName().endsWith(extension))) {
result.add(childFile);
}
}
return result;
}
/**
* @param taskSetted The taskSetted to set.
*/
public void setTaskSetted(boolean taskSetted) {
this.taskSetted = taskSetted;
}
}
| false | true | private void savePropertiesToNode(HeaderMaps headerMaps, Node propTypeNode, Collection<String> properties) {
propTypeNode.setProperty("properties", properties.toArray(new String[properties.size()]));
HashMap<String, Node> valueNodes = new HashMap<String, Node>();
ArrayList<String> noStatsProperties = new ArrayList<String>();
ArrayList<String> dataProperties = new ArrayList<String>();
ArrayList<String> identityProperties= new ArrayList<String>();
for (Relationship relation : propTypeNode.getRelationships(GeoNeoRelationshipTypes.PROPERTIES,GeoNeoRelationshipTypes.IDENTITY_PROPERTIES)) {
Node valueNode = relation.getEndNode();
String property = relation.getProperty("property", "").toString();
valueNodes.put(property, valueNode);
}
for (String property : properties) {
if (!headerMaps.nonDataHeaders.contains(property)) {
dataProperties.add(property);
}
Node valueNode = valueNodes.get(property);
Header header = headerMaps.headers.get(property);
GeoNeoRelationshipTypes relType = !header.isIdentityHeader ? GeoNeoRelationshipTypes.PROPERTIES
: GeoNeoRelationshipTypes.IDENTITY_PROPERTIES;
// if current headers do not contain information about property - we
// do not handling
// this property
if (header == null) {
continue;
}
HashMap<Object, Integer> values = header.values;
Relationship valueRelation = null;
if (values == null) {
if (valueNode != null) {
for (Relationship relation : valueNode.getRelationships()) {
relation.delete();
}
valueNode.delete();
valueNode = null;
}
noStatsProperties.add(property);
} else {
if (header.isIdentityHeader){
noStatsProperties.add(property);
identityProperties.add(property);
}
if (valueNode == null) {
valueNode = neo.createNode();
valueRelation = propTypeNode.createRelationshipTo(valueNode, relType);
valueRelation.setProperty("property", property);
} else {
valueRelation = valueNode.getSingleRelationship(relType, Direction.INCOMING);
for (Object key : valueNode.getPropertyKeys()) {
Integer oldCount = (Integer)valueNode.getProperty(key.toString(), null);
if (oldCount == null) {
oldCount = 0;
}
Integer newCount = values.get(key);
if (newCount == null) {
newCount = 0;
}
values.put(key, oldCount + newCount);
}
}
int total = 0;
for (Object key : values.keySet()) {
valueNode.setProperty(key.toString(), values.get(key));
total += values.get(key);
}
if (valueRelation != null) {
valueRelation.setProperty("count", total);
}
}
if (valueNode == null) {
valueNode = neo.createNode();
valueRelation = propTypeNode.createRelationshipTo(valueNode, relType);
valueRelation.setProperty("property", property);
valueRelation.setProperty(INeoConstants.COUNT_TYPE_NAME, header.countALL);
}
if (!header.min.equals(Double.POSITIVE_INFINITY)) {
valueRelation.setProperty(INeoConstants.MIN_VALUE, header.min);
valueRelation.setProperty(INeoConstants.MAX_VALUE, header.max);
}
}
ArrayList<String> statsProperties = new ArrayList<String>(properties);
for (String noStat : noStatsProperties) {
statsProperties.remove(noStat);
}
propTypeNode.setProperty("data_properties", dataProperties.toArray(new String[0]));
propTypeNode.setProperty("stats_properties", statsProperties.toArray(new String[0]));
propTypeNode.setProperty("no_stats_properties", noStatsProperties.toArray(new String[0]));
propTypeNode.setProperty("identity_properties", identityProperties.toArray(new String[0]));
}
| private void savePropertiesToNode(HeaderMaps headerMaps, Node propTypeNode, Collection<String> properties) {
propTypeNode.setProperty("properties", properties.toArray(new String[properties.size()]));
HashMap<String, Node> valueNodes = new HashMap<String, Node>();
ArrayList<String> noStatsProperties = new ArrayList<String>();
ArrayList<String> dataProperties = new ArrayList<String>();
ArrayList<String> identityProperties= new ArrayList<String>();
for (Relationship relation : propTypeNode.getRelationships(GeoNeoRelationshipTypes.PROPERTIES,GeoNeoRelationshipTypes.IDENTITY_PROPERTIES)) {
Node valueNode = relation.getEndNode();
String property = relation.getProperty("property", "").toString();
valueNodes.put(property, valueNode);
}
for (String property : properties) {
if (!headerMaps.nonDataHeaders.contains(property)) {
dataProperties.add(property);
}
Node valueNode = valueNodes.get(property);
Header header = headerMaps.headers.get(property);
// if current headers do not contain information about property - we
// do not handling
// this property
if (header == null) {
continue;
}
GeoNeoRelationshipTypes relType = !header.isIdentityHeader ? GeoNeoRelationshipTypes.PROPERTIES
: GeoNeoRelationshipTypes.IDENTITY_PROPERTIES;
HashMap<Object, Integer> values = header.values;
Relationship valueRelation = null;
if (values == null) {
if (valueNode != null) {
for (Relationship relation : valueNode.getRelationships()) {
relation.delete();
}
valueNode.delete();
valueNode = null;
}
noStatsProperties.add(property);
} else {
if (header.isIdentityHeader){
noStatsProperties.add(property);
identityProperties.add(property);
}
if (valueNode == null) {
valueNode = neo.createNode();
valueRelation = propTypeNode.createRelationshipTo(valueNode, relType);
valueRelation.setProperty("property", property);
} else {
valueRelation = valueNode.getSingleRelationship(relType, Direction.INCOMING);
for (Object key : valueNode.getPropertyKeys()) {
Integer oldCount = (Integer)valueNode.getProperty(key.toString(), null);
if (oldCount == null) {
oldCount = 0;
}
Integer newCount = values.get(key);
if (newCount == null) {
newCount = 0;
}
values.put(key, oldCount + newCount);
}
}
int total = 0;
for (Object key : values.keySet()) {
valueNode.setProperty(key.toString(), values.get(key));
total += values.get(key);
}
if (valueRelation != null) {
valueRelation.setProperty("count", total);
}
}
if (valueNode == null) {
valueNode = neo.createNode();
valueRelation = propTypeNode.createRelationshipTo(valueNode, relType);
valueRelation.setProperty("property", property);
valueRelation.setProperty(INeoConstants.COUNT_TYPE_NAME, header.countALL);
}
if (!header.min.equals(Double.POSITIVE_INFINITY)) {
valueRelation.setProperty(INeoConstants.MIN_VALUE, header.min);
valueRelation.setProperty(INeoConstants.MAX_VALUE, header.max);
}
}
ArrayList<String> statsProperties = new ArrayList<String>(properties);
for (String noStat : noStatsProperties) {
statsProperties.remove(noStat);
}
propTypeNode.setProperty("data_properties", dataProperties.toArray(new String[0]));
propTypeNode.setProperty("stats_properties", statsProperties.toArray(new String[0]));
propTypeNode.setProperty("no_stats_properties", noStatsProperties.toArray(new String[0]));
propTypeNode.setProperty("identity_properties", identityProperties.toArray(new String[0]));
}
|
diff --git a/src/main/java/org/elasticsearch/node/settings/NodeSettingsService.java b/src/main/java/org/elasticsearch/node/settings/NodeSettingsService.java
index 994c15424e2..a88863ff596 100644
--- a/src/main/java/org/elasticsearch/node/settings/NodeSettingsService.java
+++ b/src/main/java/org/elasticsearch/node/settings/NodeSettingsService.java
@@ -1,103 +1,103 @@
/*
* Licensed to ElasticSearch and Shay Banon 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.node.settings;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.Settings;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A service that allows to register for node settings change that can come from cluster
* events holding new settings.
*/
public class NodeSettingsService extends AbstractComponent implements ClusterStateListener {
private volatile Settings lastSettingsApplied;
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();
@Inject
public NodeSettingsService(Settings settings) {
super(settings);
}
// inject it as a member, so we won't get into possible cyclic problems
public void setClusterService(ClusterService clusterService) {
clusterService.add(this);
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
// nothing to do until we actually recover from the gateway or any other block indicates we need to disable persistency
if (event.state().blocks().disableStatePersistence()) {
return;
}
if (!event.metaDataChanged()) {
// nothing changed in the metadata, no need to check
return;
}
if (lastSettingsApplied != null && event.state().metaData().settings().equals(lastSettingsApplied)) {
// nothing changed in the settings, ignore
return;
}
for (Listener listener : listeners) {
try {
listener.onRefreshSettings(event.state().metaData().settings());
} catch (Exception e) {
logger.warn("failed to refresh settings for [{}]", e, listener);
}
}
try {
for (Map.Entry<String, String> entry : event.state().metaData().settings().getAsMap().entrySet()) {
if (entry.getKey().startsWith("logger.")) {
String component = entry.getKey().substring("logger.".length());
- ESLoggerFactory.getLogger(component, entry.getValue()).setLevel(entry.getValue());
+ ESLoggerFactory.getLogger(component).setLevel(entry.getValue());
}
}
} catch (Exception e) {
logger.warn("failed to refresh settings for [{}]", e, "logger");
}
lastSettingsApplied = event.state().metaData().settings();
}
public void addListener(Listener listener) {
this.listeners.add(listener);
}
public void removeListener(Listener listener) {
this.listeners.remove(listener);
}
public static interface Listener {
void onRefreshSettings(Settings settings);
}
}
| true | true | public void clusterChanged(ClusterChangedEvent event) {
// nothing to do until we actually recover from the gateway or any other block indicates we need to disable persistency
if (event.state().blocks().disableStatePersistence()) {
return;
}
if (!event.metaDataChanged()) {
// nothing changed in the metadata, no need to check
return;
}
if (lastSettingsApplied != null && event.state().metaData().settings().equals(lastSettingsApplied)) {
// nothing changed in the settings, ignore
return;
}
for (Listener listener : listeners) {
try {
listener.onRefreshSettings(event.state().metaData().settings());
} catch (Exception e) {
logger.warn("failed to refresh settings for [{}]", e, listener);
}
}
try {
for (Map.Entry<String, String> entry : event.state().metaData().settings().getAsMap().entrySet()) {
if (entry.getKey().startsWith("logger.")) {
String component = entry.getKey().substring("logger.".length());
ESLoggerFactory.getLogger(component, entry.getValue()).setLevel(entry.getValue());
}
}
} catch (Exception e) {
logger.warn("failed to refresh settings for [{}]", e, "logger");
}
lastSettingsApplied = event.state().metaData().settings();
}
| public void clusterChanged(ClusterChangedEvent event) {
// nothing to do until we actually recover from the gateway or any other block indicates we need to disable persistency
if (event.state().blocks().disableStatePersistence()) {
return;
}
if (!event.metaDataChanged()) {
// nothing changed in the metadata, no need to check
return;
}
if (lastSettingsApplied != null && event.state().metaData().settings().equals(lastSettingsApplied)) {
// nothing changed in the settings, ignore
return;
}
for (Listener listener : listeners) {
try {
listener.onRefreshSettings(event.state().metaData().settings());
} catch (Exception e) {
logger.warn("failed to refresh settings for [{}]", e, listener);
}
}
try {
for (Map.Entry<String, String> entry : event.state().metaData().settings().getAsMap().entrySet()) {
if (entry.getKey().startsWith("logger.")) {
String component = entry.getKey().substring("logger.".length());
ESLoggerFactory.getLogger(component).setLevel(entry.getValue());
}
}
} catch (Exception e) {
logger.warn("failed to refresh settings for [{}]", e, "logger");
}
lastSettingsApplied = event.state().metaData().settings();
}
|
diff --git a/src/com/android/providers/media/MediaProvider.java b/src/com/android/providers/media/MediaProvider.java
index 4ebad86..9206960 100644
--- a/src/com/android/providers/media/MediaProvider.java
+++ b/src/com/android/providers/media/MediaProvider.java
@@ -1,4028 +1,4028 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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.android.providers.media;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.OperationApplicationException;
import android.content.ServiceConnection;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaFile;
import android.media.MediaScanner;
import android.media.MiniThumbFile;
import android.media.MtpConstants;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Video;
import android.provider.MediaStore.Files.FileColumns;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Stack;
/**
* Media content provider. See {@link android.provider.MediaStore} for details.
* Separate databases are kept for each external storage card we see (using the
* card's ID as an index). The content visible at content://media/external/...
* changes with the card.
*/
public class MediaProvider extends ContentProvider {
private static final Uri MEDIA_URI = Uri.parse("content://media");
private static final Uri ALBUMART_URI = Uri.parse("content://media/external/audio/albumart");
private static final int ALBUM_THUMB = 1;
private static final int IMAGE_THUMB = 2;
private static final HashMap<String, String> sArtistAlbumsMap = new HashMap<String, String>();
private static final HashMap<String, String> sFolderArtMap = new HashMap<String, String>();
// A HashSet of paths that are pending creation of album art thumbnails.
private HashSet mPendingThumbs = new HashSet();
// A Stack of outstanding thumbnail requests.
private Stack mThumbRequestStack = new Stack();
// The lock of mMediaThumbQueue protects both mMediaThumbQueue and mCurrentThumbRequest.
private MediaThumbRequest mCurrentThumbRequest = null;
private PriorityQueue<MediaThumbRequest> mMediaThumbQueue =
new PriorityQueue<MediaThumbRequest>(MediaThumbRequest.PRIORITY_NORMAL,
MediaThumbRequest.getComparator());
// For compatibility with the approximately 0 apps that used mediaprovider search in
// releases 1.0, 1.1 or 1.5
private String[] mSearchColsLegacy = new String[] {
android.provider.BaseColumns._ID,
MediaStore.Audio.Media.MIME_TYPE,
"(CASE WHEN grouporder=1 THEN " + R.drawable.ic_search_category_music_artist +
" ELSE CASE WHEN grouporder=2 THEN " + R.drawable.ic_search_category_music_album +
" ELSE " + R.drawable.ic_search_category_music_song + " END END" +
") AS " + SearchManager.SUGGEST_COLUMN_ICON_1,
"0 AS " + SearchManager.SUGGEST_COLUMN_ICON_2,
"text1 AS " + SearchManager.SUGGEST_COLUMN_TEXT_1,
"text1 AS " + SearchManager.SUGGEST_COLUMN_QUERY,
"CASE when grouporder=1 THEN data1 ELSE artist END AS data1",
"CASE when grouporder=1 THEN data2 ELSE " +
"CASE WHEN grouporder=2 THEN NULL ELSE album END END AS data2",
"match as ar",
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
"grouporder",
"NULL AS itemorder" // We should be sorting by the artist/album/title keys, but that
// column is not available here, and the list is already sorted.
};
private String[] mSearchColsFancy = new String[] {
android.provider.BaseColumns._ID,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE,
"data1",
"data2",
};
// If this array gets changed, please update the constant below to point to the correct item.
private String[] mSearchColsBasic = new String[] {
android.provider.BaseColumns._ID,
MediaStore.Audio.Media.MIME_TYPE,
"(CASE WHEN grouporder=1 THEN " + R.drawable.ic_search_category_music_artist +
" ELSE CASE WHEN grouporder=2 THEN " + R.drawable.ic_search_category_music_album +
" ELSE " + R.drawable.ic_search_category_music_song + " END END" +
") AS " + SearchManager.SUGGEST_COLUMN_ICON_1,
"text1 AS " + SearchManager.SUGGEST_COLUMN_TEXT_1,
"text1 AS " + SearchManager.SUGGEST_COLUMN_QUERY,
"(CASE WHEN grouporder=1 THEN '%1'" + // %1 gets replaced with localized string.
" ELSE CASE WHEN grouporder=3 THEN artist || ' - ' || album" +
" ELSE CASE WHEN text2!='" + MediaStore.UNKNOWN_STRING + "' THEN text2" +
" ELSE NULL END END END) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_INTENT_DATA
};
// Position of the TEXT_2 item in the above array.
private final int SEARCH_COLUMN_BASIC_TEXT2 = 5;
private static final String[] mMediaTableColumns = new String[] {
FileColumns._ID,
FileColumns.MEDIA_TYPE,
};
private Uri mAlbumArtBaseUri = Uri.parse("content://media/external/audio/albumart");
private BroadcastReceiver mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_MEDIA_EJECT)) {
// Remove the external volume and then notify all cursors backed by
// data on that volume
detachVolume(Uri.parse("content://media/external"));
sFolderArtMap.clear();
MiniThumbFile.reset();
}
}
};
// set to disable sending events when the operation originates from MTP
private boolean mDisableMtpObjectCallbacks;
private final SQLiteDatabase.CustomFunction mObjectRemovedCallback =
new SQLiteDatabase.CustomFunction() {
public void callback(String[] args) {
// do nothing if the operation originated from MTP
if (mDisableMtpObjectCallbacks) return;
Log.d(TAG, "object removed " + args[0]);
IMtpService mtpService = mMtpService;
if (mtpService != null) {
try {
sendObjectRemoved(Integer.parseInt(args[0]));
} catch (NumberFormatException e) {
Log.e(TAG, "NumberFormatException in mObjectRemovedCallback", e);
}
}
}
};
// path to external storage, or media directory in internal storage
private static String mExternalStoragePath;
// legacy path, which needs to get remapped to mExternalStoragePath
private static String mLegacyExternalStoragePath;
private static String fixExternalStoragePath(String path) {
// replace legacy storage path with correct prefix
if (path != null && mLegacyExternalStoragePath != null
&& path.startsWith(mLegacyExternalStoragePath)) {
path = mExternalStoragePath + path.substring(mLegacyExternalStoragePath.length());
}
return path;
}
private static ContentValues fixExternalStoragePath(ContentValues values) {
String path = values.getAsString(MediaStore.MediaColumns.DATA);
if (path != null) {
String fixedPath = fixExternalStoragePath(path);
if (!path.equals(fixedPath)) {
values = new ContentValues(values);
values.put(MediaStore.MediaColumns.DATA, fixedPath);
}
}
return values;
}
/**
* Wrapper class for a specific database (associated with one particular
* external card, or with internal storage). Can open the actual database
* on demand, create and upgrade the schema, etc.
*/
private final class DatabaseHelper extends SQLiteOpenHelper {
final Context mContext;
final String mName;
final boolean mInternal; // True if this is the internal database
boolean mUpgradeAttempted; // Used for upgrade error handling
// In memory caches of artist and album data.
HashMap<String, Long> mArtistCache = new HashMap<String, Long>();
HashMap<String, Long> mAlbumCache = new HashMap<String, Long>();
public DatabaseHelper(Context context, String name, boolean internal) {
super(context, name, null, DATABASE_VERSION);
mContext = context;
mName = name;
mInternal = internal;
}
/**
* Creates database the first time we try to open it.
*/
@Override
public void onCreate(final SQLiteDatabase db) {
updateDatabase(db, mInternal, 0, DATABASE_VERSION);
}
/**
* Updates the database format when a new content provider is used
* with an older database format.
*/
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldV, final int newV) {
mUpgradeAttempted = true;
updateDatabase(db, mInternal, oldV, newV);
}
public synchronized SQLiteDatabase getWritableDatabase() {
SQLiteDatabase result = null;
mUpgradeAttempted = false;
try {
result = super.getWritableDatabase();
} catch (Exception e) {
if (!mUpgradeAttempted) {
Log.e(TAG, "failed to open database " + mName, e);
return null;
}
}
// If we failed to open the database during an upgrade, delete the file and try again.
// This will result in the creation of a fresh database, which will be repopulated
// when the media scanner runs.
if (result == null && mUpgradeAttempted) {
mContext.getDatabasePath(mName).delete();
result = super.getWritableDatabase();
}
return result;
}
/**
* Touch this particular database and garbage collect old databases.
* An LRU cache system is used to clean up databases for old external
* storage volumes.
*/
@Override
public void onOpen(SQLiteDatabase db) {
// Turn off WAL optimization as it appears to cause difficult to repoduce
// disk i/o errors.
db.disableWriteAheadLogging();
if (mInternal) return; // The internal database is kept separately.
db.addCustomFunction("_OBJECT_REMOVED", 1, mObjectRemovedCallback);
// touch the database file to show it is most recently used
File file = new File(db.getPath());
long now = System.currentTimeMillis();
file.setLastModified(now);
// delete least recently used databases if we are over the limit
String[] databases = mContext.databaseList();
int count = databases.length;
int limit = MAX_EXTERNAL_DATABASES;
// delete external databases that have not been used in the past two months
long twoMonthsAgo = now - OBSOLETE_DATABASE_DB;
for (int i = 0; i < databases.length; i++) {
File other = mContext.getDatabasePath(databases[i]);
if (INTERNAL_DATABASE_NAME.equals(databases[i]) || file.equals(other)) {
databases[i] = null;
count--;
if (file.equals(other)) {
// reduce limit to account for the existence of the database we
// are about to open, which we removed from the list.
limit--;
}
} else {
long time = other.lastModified();
if (time < twoMonthsAgo) {
if (LOCAL_LOGV) Log.v(TAG, "Deleting old database " + databases[i]);
mContext.deleteDatabase(databases[i]);
databases[i] = null;
count--;
}
}
}
// delete least recently used databases until
// we are no longer over the limit
while (count > limit) {
int lruIndex = -1;
long lruTime = 0;
for (int i = 0; i < databases.length; i++) {
if (databases[i] != null) {
long time = mContext.getDatabasePath(databases[i]).lastModified();
if (lruTime == 0 || time < lruTime) {
lruIndex = i;
lruTime = time;
}
}
}
// delete least recently used database
if (lruIndex != -1) {
if (LOCAL_LOGV) Log.v(TAG, "Deleting old database " + databases[lruIndex]);
mContext.deleteDatabase(databases[lruIndex]);
databases[lruIndex] = null;
count--;
}
}
}
}
private IMtpService mMtpService;
private final ServiceConnection mMtpServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, android.os.IBinder service) {
Log.d(TAG, "mMtpService connected");
mMtpService = IMtpService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
Log.d(TAG, "mMtpService disconnected");
mMtpService = null;
}
};
@Override
public boolean onCreate() {
final Context context = getContext();
sArtistAlbumsMap.put(MediaStore.Audio.Albums._ID, "audio.album_id AS " +
MediaStore.Audio.Albums._ID);
sArtistAlbumsMap.put(MediaStore.Audio.Albums.ALBUM, "album");
sArtistAlbumsMap.put(MediaStore.Audio.Albums.ALBUM_KEY, "album_key");
sArtistAlbumsMap.put(MediaStore.Audio.Albums.FIRST_YEAR, "MIN(year) AS " +
MediaStore.Audio.Albums.FIRST_YEAR);
sArtistAlbumsMap.put(MediaStore.Audio.Albums.LAST_YEAR, "MAX(year) AS " +
MediaStore.Audio.Albums.LAST_YEAR);
sArtistAlbumsMap.put(MediaStore.Audio.Media.ARTIST, "artist");
sArtistAlbumsMap.put(MediaStore.Audio.Media.ARTIST_ID, "artist");
sArtistAlbumsMap.put(MediaStore.Audio.Media.ARTIST_KEY, "artist_key");
sArtistAlbumsMap.put(MediaStore.Audio.Albums.NUMBER_OF_SONGS, "count(*) AS " +
MediaStore.Audio.Albums.NUMBER_OF_SONGS);
sArtistAlbumsMap.put(MediaStore.Audio.Albums.ALBUM_ART, "album_art._data AS " +
MediaStore.Audio.Albums.ALBUM_ART);
mSearchColsBasic[SEARCH_COLUMN_BASIC_TEXT2] =
mSearchColsBasic[SEARCH_COLUMN_BASIC_TEXT2].replaceAll(
"%1", context.getString(R.string.artist_label));
mDatabases = new HashMap<String, DatabaseHelper>();
attachVolume(INTERNAL_VOLUME);
IntentFilter iFilter = new IntentFilter(Intent.ACTION_MEDIA_EJECT);
iFilter.addDataScheme("file");
context.registerReceiver(mUnmountReceiver, iFilter);
// figure out correct path to use for external storage
mExternalStoragePath = SystemProperties.get("ro.media.storage");
if (mExternalStoragePath == null || mExternalStoragePath.length() == 0) {
mExternalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
// apps may use the legacy /mnt/sdcard path instead.
// if so, we need to transform the paths to use the mExternalStoragePath prefix
mLegacyExternalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
if (mExternalStoragePath.equals(mLegacyExternalStoragePath)) {
// paths are equal - no remapping necessary
mLegacyExternalStoragePath = null;
}
}
// open external database if external storage is mounted
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
attachVolume(EXTERNAL_VOLUME);
}
HandlerThread ht = new HandlerThread("thumbs thread", Process.THREAD_PRIORITY_BACKGROUND);
ht.start();
mThumbHandler = new Handler(ht.getLooper()) {
@Override
public void handleMessage(Message msg) {
if (msg.what == IMAGE_THUMB) {
synchronized (mMediaThumbQueue) {
mCurrentThumbRequest = mMediaThumbQueue.poll();
}
if (mCurrentThumbRequest == null) {
Log.w(TAG, "Have message but no request?");
} else {
try {
File origFile = new File(mCurrentThumbRequest.mPath);
if (origFile.exists() && origFile.length() > 0) {
mCurrentThumbRequest.execute();
} else {
// original file hasn't been stored yet
synchronized (mMediaThumbQueue) {
Log.w(TAG, "original file hasn't been stored yet: " + mCurrentThumbRequest.mPath);
}
}
} catch (IOException ex) {
Log.w(TAG, ex);
} catch (UnsupportedOperationException ex) {
// This could happen if we unplug the sd card during insert/update/delete
// See getDatabaseForUri.
Log.w(TAG, ex);
} finally {
synchronized (mCurrentThumbRequest) {
mCurrentThumbRequest.mState = MediaThumbRequest.State.DONE;
mCurrentThumbRequest.notifyAll();
}
}
}
} else if (msg.what == ALBUM_THUMB) {
ThumbData d;
synchronized (mThumbRequestStack) {
d = (ThumbData)mThumbRequestStack.pop();
}
makeThumbInternal(d);
synchronized (mPendingThumbs) {
mPendingThumbs.remove(d.path);
}
}
}
};
context.bindService(new Intent(context, MtpService.class),
mMtpServiceConnection, Context.BIND_AUTO_CREATE);
return true;
}
private static final String IMAGE_COLUMNS =
"_data,_size,_display_name,mime_type,title,date_added," +
"date_modified,description,picasa_id,isprivate,latitude,longitude," +
"datetaken,orientation,mini_thumb_magic,bucket_id,bucket_display_name";
private static final String AUDIO_COLUMNSv99 =
"_data,_display_name,_size,mime_type,date_added," +
"date_modified,title,title_key,duration,artist_id,composer,album_id," +
"track,year,is_ringtone,is_music,is_alarm,is_notification,is_podcast," +
"bookmark";
private static final String AUDIO_COLUMNSv100 =
"_data,_display_name,_size,mime_type,date_added," +
"date_modified,title,title_key,duration,artist_id,composer,album_id," +
"track,year,is_ringtone,is_music,is_alarm,is_notification,is_podcast," +
"bookmark,album_artist";
private static final String VIDEO_COLUMNS =
"_data,_display_name,_size,mime_type,date_added,date_modified," +
"title,duration,artist,album,resolution,description,isprivate,tags," +
"category,language,mini_thumb_data,latitude,longitude,datetaken," +
"mini_thumb_magic,bucket_id,bucket_display_name, bookmark";
private static final String PLAYLIST_COLUMNS = "_data,name,date_added,date_modified";
/**
* This method takes care of updating all the tables in the database to the
* current version, creating them if necessary.
* This method can only update databases at schema 63 or higher, which was
* created August 1, 2008. Older database will be cleared and recreated.
* @param db Database
* @param internal True if this is the internal media database
*/
private static void updateDatabase(SQLiteDatabase db, boolean internal,
int fromVersion, int toVersion) {
// sanity checks
if (toVersion != DATABASE_VERSION) {
Log.e(TAG, "Illegal update request. Got " + toVersion + ", expected " +
DATABASE_VERSION);
throw new IllegalArgumentException();
} else if (fromVersion > toVersion) {
Log.e(TAG, "Illegal update request: can't downgrade from " + fromVersion +
" to " + toVersion + ". Did you forget to wipe data?");
throw new IllegalArgumentException();
}
// Revisions 84-86 were a failed attempt at supporting the "album artist" id3 tag.
// We can't downgrade from those revisions, so start over.
// (the initial change to do this was wrong, so now we actually need to start over
// if the database version is 84-89)
// Post-gingerbread, revisions 91-94 were broken in a way that is not easy to repair.
// However version 91 was reused in a divergent development path for gingerbread,
// so we need to support upgrades from 91.
// Therefore we will only force a reset for versions 92 - 94.
if (fromVersion < 63 || (fromVersion >= 84 && fromVersion <= 89) ||
(fromVersion >= 92 && fromVersion <= 94)) {
fromVersion = 63;
// Drop everything and start over.
Log.i(TAG, "Upgrading media database from version " +
fromVersion + " to " + toVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS images");
db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
db.execSQL("DROP TABLE IF EXISTS thumbnails");
db.execSQL("DROP TRIGGER IF EXISTS thumbnails_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_meta");
db.execSQL("DROP TABLE IF EXISTS artists");
db.execSQL("DROP TABLE IF EXISTS albums");
db.execSQL("DROP TABLE IF EXISTS album_art");
db.execSQL("DROP VIEW IF EXISTS artist_info");
db.execSQL("DROP VIEW IF EXISTS album_info");
db.execSQL("DROP VIEW IF EXISTS artists_albums_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_genres");
db.execSQL("DROP TABLE IF EXISTS audio_genres_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_genres_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_playlists");
db.execSQL("DROP TABLE IF EXISTS audio_playlists_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup1");
db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup2");
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
db.execSQL("DROP TABLE IF EXISTS objects");
db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup");
db.execSQL("CREATE TABLE IF NOT EXISTS images (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"_size INTEGER," +
"_display_name TEXT," +
"mime_type TEXT," +
"title TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"description TEXT," +
"picasa_id TEXT," +
"isprivate INTEGER," +
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"orientation INTEGER," +
"mini_thumb_magic INTEGER," +
"bucket_id TEXT," +
"bucket_display_name TEXT" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS mini_thumb_magic_index on images(mini_thumb_magic);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON images " +
"BEGIN " +
"DELETE FROM thumbnails WHERE image_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
// create image thumbnail table
db.execSQL("CREATE TABLE IF NOT EXISTS thumbnails (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"image_id INTEGER," +
"kind INTEGER," +
"width INTEGER," +
"height INTEGER" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS image_id_index on thumbnails(image_id);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS thumbnails_cleanup DELETE ON thumbnails " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
// Contains meta data about audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_meta (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT UNIQUE NOT NULL," +
"_display_name TEXT," +
"_size INTEGER," +
"mime_type TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"title TEXT NOT NULL," +
"title_key TEXT NOT NULL," +
"duration INTEGER," +
"artist_id INTEGER," +
"composer TEXT," +
"album_id INTEGER," +
"track INTEGER," + // track is an integer to allow proper sorting
"year INTEGER CHECK(year!=0)," +
"is_ringtone INTEGER," +
"is_music INTEGER," +
"is_alarm INTEGER," +
"is_notification INTEGER" +
");");
// Contains a sort/group "key" and the preferred display name for artists
db.execSQL("CREATE TABLE IF NOT EXISTS artists (" +
"artist_id INTEGER PRIMARY KEY," +
"artist_key TEXT NOT NULL UNIQUE," +
"artist TEXT NOT NULL" +
");");
// Contains a sort/group "key" and the preferred display name for albums
db.execSQL("CREATE TABLE IF NOT EXISTS albums (" +
"album_id INTEGER PRIMARY KEY," +
"album_key TEXT NOT NULL UNIQUE," +
"album TEXT NOT NULL" +
");");
db.execSQL("CREATE TABLE IF NOT EXISTS album_art (" +
"album_id INTEGER PRIMARY KEY," +
"_data TEXT" +
");");
recreateAudioView(db);
// Provides some extra info about artists, like the number of tracks
// and albums for this artist
db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
"SELECT artist_id AS _id, artist, artist_key, " +
"COUNT(DISTINCT album) AS number_of_albums, " +
"COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
"GROUP BY artist_key;");
// Provides extra info albums, such as the number of tracks
db.execSQL("CREATE VIEW IF NOT EXISTS album_info AS " +
"SELECT audio.album_id AS _id, album, album_key, " +
"MIN(year) AS minyear, " +
"MAX(year) AS maxyear, artist, artist_id, artist_key, " +
"count(*) AS " + MediaStore.Audio.Albums.NUMBER_OF_SONGS +
",album_art._data AS album_art" +
" FROM audio LEFT OUTER JOIN album_art ON audio.album_id=album_art.album_id" +
" WHERE is_music=1 GROUP BY audio.album_id;");
// For a given artist_id, provides the album_id for albums on
// which the artist appears.
db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
"SELECT DISTINCT artist_id, album_id FROM audio_meta;");
/*
* Only external media volumes can handle genres, playlists, etc.
*/
if (!internal) {
// Cleans up when an audio file is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON audio_meta " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
"DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
"END");
// Contains audio genre definitions
db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres (" +
"_id INTEGER PRIMARY KEY," +
"name TEXT NOT NULL" +
");");
// Contiains mappings between audio genres and audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres_map (" +
"_id INTEGER PRIMARY KEY," +
"audio_id INTEGER NOT NULL," +
"genre_id INTEGER NOT NULL" +
");");
// Cleans up when an audio genre is delete
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_genres_cleanup DELETE ON audio_genres " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE genre_id = old._id;" +
"END");
// Contains audio playlist definitions
db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," + // _data is path for file based playlists, or null
"name TEXT NOT NULL," +
"date_added INTEGER," +
"date_modified INTEGER" +
");");
// Contains mappings between audio playlists and audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists_map (" +
"_id INTEGER PRIMARY KEY," +
"audio_id INTEGER NOT NULL," +
"playlist_id INTEGER NOT NULL," +
"play_order INTEGER NOT NULL" +
");");
// Cleans up when an audio playlist is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON audio_playlists " +
"BEGIN " +
"DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
// Cleans up album_art table entry when an album is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup1 DELETE ON albums " +
"BEGIN " +
"DELETE FROM album_art WHERE album_id = old.album_id;" +
"END");
// Cleans up album_art when an album is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup2 DELETE ON album_art " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
// Contains meta data about video files
db.execSQL("CREATE TABLE IF NOT EXISTS video (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT NOT NULL," +
"_display_name TEXT," +
"_size INTEGER," +
"mime_type TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"title TEXT," +
"duration INTEGER," +
"artist TEXT," +
"album TEXT," +
"resolution TEXT," +
"description TEXT," +
"isprivate INTEGER," + // for YouTube videos
"tags TEXT," + // for YouTube videos
"category TEXT," + // for YouTube videos
"language TEXT," + // for YouTube videos
"mini_thumb_data TEXT," +
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"mini_thumb_magic INTEGER" +
");");
db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON video " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
// At this point the database is at least at schema version 63 (it was
// either created at version 63 by the code above, or was already at
// version 63 or later)
if (fromVersion < 64) {
// create the index that updates the database to schema version 64
db.execSQL("CREATE INDEX IF NOT EXISTS sort_index on images(datetaken ASC, _id ASC);");
}
/*
* Android 1.0 shipped with database version 64
*/
if (fromVersion < 65) {
// create the index that updates the database to schema version 65
db.execSQL("CREATE INDEX IF NOT EXISTS titlekey_index on audio_meta(title_key);");
}
// In version 66, originally we updateBucketNames(db, "images"),
// but we need to do it in version 89 and therefore save the update here.
if (fromVersion < 67) {
// create the indices that update the database to schema version 67
db.execSQL("CREATE INDEX IF NOT EXISTS albumkey_index on albums(album_key);");
db.execSQL("CREATE INDEX IF NOT EXISTS artistkey_index on artists(artist_key);");
}
if (fromVersion < 68) {
// Create bucket_id and bucket_display_name columns for the video table.
db.execSQL("ALTER TABLE video ADD COLUMN bucket_id TEXT;");
db.execSQL("ALTER TABLE video ADD COLUMN bucket_display_name TEXT");
// In version 68, originally we updateBucketNames(db, "video"),
// but we need to do it in version 89 and therefore save the update here.
}
if (fromVersion < 69) {
updateDisplayName(db, "images");
}
if (fromVersion < 70) {
// Create bookmark column for the video table.
db.execSQL("ALTER TABLE video ADD COLUMN bookmark INTEGER;");
}
if (fromVersion < 71) {
// There is no change to the database schema, however a code change
// fixed parsing of metadata for certain files bought from the
// iTunes music store, so we want to rescan files that might need it.
// We do this by clearing the modification date in the database for
// those files, so that the media scanner will see them as updated
// and rescan them.
db.execSQL("UPDATE audio_meta SET date_modified=0 WHERE _id IN (" +
"SELECT _id FROM audio where mime_type='audio/mp4' AND " +
"artist='" + MediaStore.UNKNOWN_STRING + "' AND " +
"album='" + MediaStore.UNKNOWN_STRING + "'" +
");");
}
if (fromVersion < 72) {
// Create is_podcast and bookmark columns for the audio table.
db.execSQL("ALTER TABLE audio_meta ADD COLUMN is_podcast INTEGER;");
db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE _data LIKE '%/podcasts/%';");
db.execSQL("UPDATE audio_meta SET is_music=0 WHERE is_podcast=1" +
" AND _data NOT LIKE '%/music/%';");
db.execSQL("ALTER TABLE audio_meta ADD COLUMN bookmark INTEGER;");
// New columns added to tables aren't visible in views on those tables
// without opening and closing the database (or using the 'vacuum' command,
// which we can't do here because all this code runs inside a transaction).
// To work around this, we drop and recreate the affected view and trigger.
recreateAudioView(db);
}
/*
* Android 1.5 shipped with database version 72
*/
if (fromVersion < 73) {
// There is no change to the database schema, but we now do case insensitive
// matching of folder names when determining whether something is music, a
// ringtone, podcast, etc, so we might need to reclassify some files.
db.execSQL("UPDATE audio_meta SET is_music=1 WHERE is_music=0 AND " +
"_data LIKE '%/music/%';");
db.execSQL("UPDATE audio_meta SET is_ringtone=1 WHERE is_ringtone=0 AND " +
"_data LIKE '%/ringtones/%';");
db.execSQL("UPDATE audio_meta SET is_notification=1 WHERE is_notification=0 AND " +
"_data LIKE '%/notifications/%';");
db.execSQL("UPDATE audio_meta SET is_alarm=1 WHERE is_alarm=0 AND " +
"_data LIKE '%/alarms/%';");
db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE is_podcast=0 AND " +
"_data LIKE '%/podcasts/%';");
}
if (fromVersion < 74) {
// This view is used instead of the audio view by the union below, to force
// sqlite to use the title_key index. This greatly reduces memory usage
// (no separate copy pass needed for sorting, which could cause errors on
// large datasets) and improves speed (by about 35% on a large dataset)
db.execSQL("CREATE VIEW IF NOT EXISTS searchhelpertitle AS SELECT * FROM audio " +
"ORDER BY title_key;");
db.execSQL("CREATE VIEW IF NOT EXISTS search AS " +
"SELECT _id," +
"'artist' AS mime_type," +
"artist," +
"NULL AS album," +
"NULL AS title," +
"artist AS text1," +
"NULL AS text2," +
"number_of_albums AS data1," +
"number_of_tracks AS data2," +
"artist_key AS match," +
"'content://media/external/audio/artists/'||_id AS suggest_intent_data," +
"1 AS grouporder " +
"FROM artist_info WHERE (artist!='" + MediaStore.UNKNOWN_STRING + "') " +
"UNION ALL " +
"SELECT _id," +
"'album' AS mime_type," +
"artist," +
"album," +
"NULL AS title," +
"album AS text1," +
"artist AS text2," +
"NULL AS data1," +
"NULL AS data2," +
"artist_key||' '||album_key AS match," +
"'content://media/external/audio/albums/'||_id AS suggest_intent_data," +
"2 AS grouporder " +
"FROM album_info WHERE (album!='" + MediaStore.UNKNOWN_STRING + "') " +
"UNION ALL " +
"SELECT searchhelpertitle._id AS _id," +
"mime_type," +
"artist," +
"album," +
"title," +
"title AS text1," +
"artist AS text2," +
"NULL AS data1," +
"NULL AS data2," +
"artist_key||' '||album_key||' '||title_key AS match," +
"'content://media/external/audio/media/'||searchhelpertitle._id AS " +
"suggest_intent_data," +
"3 AS grouporder " +
"FROM searchhelpertitle WHERE (title != '') "
);
}
if (fromVersion < 75) {
// Force a rescan of the audio entries so we can apply the new logic to
// distinguish same-named albums.
db.execSQL("UPDATE audio_meta SET date_modified=0;");
db.execSQL("DELETE FROM albums");
}
if (fromVersion < 76) {
// We now ignore double quotes when building the key, so we have to remove all of them
// from existing keys.
db.execSQL("UPDATE audio_meta SET title_key=" +
"REPLACE(title_key,x'081D08C29F081D',x'081D') " +
"WHERE title_key LIKE '%'||x'081D08C29F081D'||'%';");
db.execSQL("UPDATE albums SET album_key=" +
"REPLACE(album_key,x'081D08C29F081D',x'081D') " +
"WHERE album_key LIKE '%'||x'081D08C29F081D'||'%';");
db.execSQL("UPDATE artists SET artist_key=" +
"REPLACE(artist_key,x'081D08C29F081D',x'081D') " +
"WHERE artist_key LIKE '%'||x'081D08C29F081D'||'%';");
}
/*
* Android 1.6 shipped with database version 76
*/
if (fromVersion < 77) {
// create video thumbnail table
db.execSQL("CREATE TABLE IF NOT EXISTS videothumbnails (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"video_id INTEGER," +
"kind INTEGER," +
"width INTEGER," +
"height INTEGER" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS video_id_index on videothumbnails(video_id);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS videothumbnails_cleanup DELETE ON videothumbnails " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
/*
* Android 2.0 and 2.0.1 shipped with database version 77
*/
if (fromVersion < 78) {
// Force a rescan of the video entries so we can update
// latest changed DATE_TAKEN units (in milliseconds).
db.execSQL("UPDATE video SET date_modified=0;");
}
/*
* Android 2.1 shipped with database version 78
*/
if (fromVersion < 79) {
// move /sdcard/albumthumbs to
// /sdcard/Android/data/com.android.providers.media/albumthumbs,
// and update the database accordingly
String oldthumbspath = mExternalStoragePath + "/albumthumbs";
String newthumbspath = mExternalStoragePath + "/" + ALBUM_THUMB_FOLDER;
File thumbsfolder = new File(oldthumbspath);
if (thumbsfolder.exists()) {
// move folder to its new location
File newthumbsfolder = new File(newthumbspath);
newthumbsfolder.getParentFile().mkdirs();
if(thumbsfolder.renameTo(newthumbsfolder)) {
// update the database
db.execSQL("UPDATE album_art SET _data=REPLACE(_data, '" +
oldthumbspath + "','" + newthumbspath + "');");
}
}
}
if (fromVersion < 80) {
// Force rescan of image entries to update DATE_TAKEN as UTC timestamp.
db.execSQL("UPDATE images SET date_modified=0;");
}
if (fromVersion < 81 && !internal) {
// Delete entries starting with /mnt/sdcard. This is for the benefit
// of users running builds between 2.0.1 and 2.1 final only, since
// users updating from 2.0 or earlier will not have such entries.
// First we need to update the _data fields in the affected tables, since
// otherwise deleting the entries will also delete the underlying files
// (via a trigger), and we want to keep them.
db.execSQL("UPDATE audio_playlists SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE images SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE video SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE videothumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE thumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE album_art SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE audio_meta SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
// Once the paths have been renamed, we can safely delete the entries
db.execSQL("DELETE FROM audio_playlists WHERE _data IS '////';");
db.execSQL("DELETE FROM images WHERE _data IS '////';");
db.execSQL("DELETE FROM video WHERE _data IS '////';");
db.execSQL("DELETE FROM videothumbnails WHERE _data IS '////';");
db.execSQL("DELETE FROM thumbnails WHERE _data IS '////';");
db.execSQL("DELETE FROM audio_meta WHERE _data IS '////';");
db.execSQL("DELETE FROM album_art WHERE _data IS '////';");
// rename existing entries starting with /sdcard to /mnt/sdcard
db.execSQL("UPDATE audio_meta" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE audio_playlists" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE images" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE video" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE videothumbnails" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE thumbnails" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE album_art" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
// Delete albums and artists, then clear the modification time on songs, which
// will cause the media scanner to rescan everything, rebuilding the artist and
// album tables along the way, while preserving playlists.
// We need this rescan because ICU also changed, and now generates different
// collation keys
db.execSQL("DELETE from albums");
db.execSQL("DELETE from artists");
db.execSQL("UPDATE audio_meta SET date_modified=0;");
}
if (fromVersion < 82) {
// recreate this view with the correct "group by" specifier
db.execSQL("DROP VIEW IF EXISTS artist_info");
db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
"SELECT artist_id AS _id, artist, artist_key, " +
"COUNT(DISTINCT album_key) AS number_of_albums, " +
"COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
"GROUP BY artist_key;");
}
/* we skipped over version 83, and reverted versions 84, 85 and 86 */
if (fromVersion < 87) {
// The fastscroll thumb needs an index on the strings being displayed,
// otherwise the queries it does to determine the correct position
// becomes really inefficient
db.execSQL("CREATE INDEX IF NOT EXISTS title_idx on audio_meta(title);");
db.execSQL("CREATE INDEX IF NOT EXISTS artist_idx on artists(artist);");
db.execSQL("CREATE INDEX IF NOT EXISTS album_idx on albums(album);");
}
if (fromVersion < 88) {
// Clean up a few more things from versions 84/85/86, and recreate
// the few things worth keeping from those changes.
db.execSQL("DROP TRIGGER IF EXISTS albums_update1;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update2;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update3;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update4;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update1;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update2;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update3;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update4;");
db.execSQL("DROP VIEW IF EXISTS album_artists;");
db.execSQL("CREATE INDEX IF NOT EXISTS album_id_idx on audio_meta(album_id);");
db.execSQL("CREATE INDEX IF NOT EXISTS artist_id_idx on audio_meta(artist_id);");
// For a given artist_id, provides the album_id for albums on
// which the artist appears.
db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
"SELECT DISTINCT artist_id, album_id FROM audio_meta;");
}
if (fromVersion < 89) {
updateBucketNames(db, "images");
updateBucketNames(db, "video");
}
if (fromVersion < 91) {
// Never query by mini_thumb_magic_index
db.execSQL("DROP INDEX IF EXISTS mini_thumb_magic_index");
// sort the items by taken date in each bucket
db.execSQL("CREATE INDEX IF NOT EXISTS image_bucket_index ON images(bucket_id, datetaken)");
db.execSQL("CREATE INDEX IF NOT EXISTS video_bucket_index ON video(bucket_id, datetaken)");
}
// versions 92 - 98 were work in progress on MTP obsoleted by version 99
if (fromVersion < 99) {
// Remove various stages of work in progress for MTP support
db.execSQL("DROP TABLE IF EXISTS objects");
db.execSQL("DROP TABLE IF EXISTS files");
db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_images;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_audio;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_video;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_playlists;");
db.execSQL("DROP TRIGGER IF EXISTS media_cleanup;");
// Create a new table to manage all files in our storage.
// This contains a union of all the columns from the old
// images, audio_meta, videos and audio_playlist tables.
db.execSQL("CREATE TABLE files (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," + // this can be null for playlists
"_size INTEGER," +
"format INTEGER," +
"parent INTEGER," +
"date_added INTEGER," +
"date_modified INTEGER," +
"mime_type TEXT," +
"title TEXT," +
"description TEXT," +
"_display_name TEXT," +
// for images
"picasa_id TEXT," +
"orientation INTEGER," +
// for images and video
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"mini_thumb_magic INTEGER," +
"bucket_id TEXT," +
"bucket_display_name TEXT," +
"isprivate INTEGER," +
// for audio
"title_key TEXT," +
"artist_id INTEGER," +
"album_id INTEGER," +
"composer TEXT," +
"track INTEGER," +
"year INTEGER CHECK(year!=0)," +
"is_ringtone INTEGER," +
"is_music INTEGER," +
"is_alarm INTEGER," +
"is_notification INTEGER," +
"is_podcast INTEGER," +
// for audio and video
"duration INTEGER," +
"bookmark INTEGER," +
// for video
"artist TEXT," +
"album TEXT," +
"resolution TEXT," +
"tags TEXT," +
"category TEXT," +
"language TEXT," +
"mini_thumb_data TEXT," +
// for playlists
"name TEXT," +
// media_type is used by the views to emulate the old
// images, audio_meta, videos and audio_playlist tables.
"media_type INTEGER," +
// Value of _id from the old media table.
// Used only for updating other tables during database upgrade.
"old_id INTEGER" +
");");
db.execSQL("CREATE INDEX path_index ON files(_data);");
db.execSQL("CREATE INDEX media_type_index ON files(media_type);");
// Copy all data from our obsolete tables to the new files table
db.execSQL("INSERT INTO files (" + IMAGE_COLUMNS + ",old_id,media_type) SELECT "
+ IMAGE_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_IMAGE + " FROM images;");
db.execSQL("INSERT INTO files (" + AUDIO_COLUMNSv99 + ",old_id,media_type) SELECT "
+ AUDIO_COLUMNSv99 + ",_id," + FileColumns.MEDIA_TYPE_AUDIO + " FROM audio_meta;");
db.execSQL("INSERT INTO files (" + VIDEO_COLUMNS + ",old_id,media_type) SELECT "
+ VIDEO_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_VIDEO + " FROM video;");
if (!internal) {
db.execSQL("INSERT INTO files (" + PLAYLIST_COLUMNS + ",old_id,media_type) SELECT "
+ PLAYLIST_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_PLAYLIST
+ " FROM audio_playlists;");
}
// Delete the old tables
db.execSQL("DROP TABLE IF EXISTS images");
db.execSQL("DROP TABLE IF EXISTS audio_meta");
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TABLE IF EXISTS audio_playlists");
// Create views to replace our old tables
db.execSQL("CREATE VIEW images AS SELECT _id," + IMAGE_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_IMAGE + ";");
// audio_meta will be created below for schema 100
// db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv99 +
// " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
// + FileColumns.MEDIA_TYPE_AUDIO + ";");
db.execSQL("CREATE VIEW video AS SELECT _id," + VIDEO_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_VIDEO + ";");
if (!internal) {
db.execSQL("CREATE VIEW audio_playlists AS SELECT _id," + PLAYLIST_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_PLAYLIST + ";");
}
// update the image_id column in the thumbnails table.
db.execSQL("UPDATE thumbnails SET image_id = (SELECT _id FROM files "
+ "WHERE files.old_id = thumbnails.image_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_IMAGE + ");");
if (!internal) {
// update audio_id in the audio_genres_map and audio_playlists_map tables.
db.execSQL("UPDATE audio_genres_map SET audio_id = (SELECT _id FROM files "
+ "WHERE files.old_id = audio_genres_map.audio_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_AUDIO + ");");
db.execSQL("UPDATE audio_playlists_map SET audio_id = (SELECT _id FROM files "
+ "WHERE files.old_id = audio_playlists_map.audio_id "
+ "AND files.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + ");");
}
// update video_id in the videothumbnails table.
db.execSQL("UPDATE videothumbnails SET video_id = (SELECT _id FROM files "
+ "WHERE files.old_id = videothumbnails.video_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_VIDEO + ");");
// update indices to work on the files table
db.execSQL("DROP INDEX IF EXISTS title_idx");
db.execSQL("DROP INDEX IF EXISTS album_id_idx");
db.execSQL("DROP INDEX IF EXISTS image_bucket_index");
db.execSQL("DROP INDEX IF EXISTS video_bucket_index");
db.execSQL("DROP INDEX IF EXISTS sort_index");
db.execSQL("DROP INDEX IF EXISTS titlekey_index");
db.execSQL("DROP INDEX IF EXISTS artist_id_idx");
db.execSQL("CREATE INDEX title_idx ON files(title);");
db.execSQL("CREATE INDEX album_id_idx ON files(album_id);");
db.execSQL("CREATE INDEX bucket_index ON files(bucket_id, datetaken);");
db.execSQL("CREATE INDEX sort_index ON files(datetaken ASC, _id ASC);");
db.execSQL("CREATE INDEX titlekey_index ON files(title_key);");
db.execSQL("CREATE INDEX artist_id_idx ON files(artist_id);");
// Recreate triggers for our obsolete tables on the new files table
db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_delete");
db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_IMAGE + " " +
"BEGIN " +
"DELETE FROM thumbnails WHERE image_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON files " +
- "WHEN old.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + " " +
+ "WHEN old.media_type = " + FileColumns.MEDIA_TYPE_VIDEO + " " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
if (!internal) {
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + " " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
"DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_PLAYLIST + " " +
"BEGIN " +
"DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_delete INSTEAD OF DELETE ON audio " +
"BEGIN " +
"DELETE from files where _id=old._id;" +
"DELETE from audio_playlists_map where audio_id=old._id;" +
"DELETE from audio_genres_map where audio_id=old._id;" +
"END");
}
}
if (fromVersion < 100) {
db.execSQL("ALTER TABLE files ADD COLUMN album_artist TEXT;");
db.execSQL("DROP VIEW IF EXISTS audio_meta;");
db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv100 +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_AUDIO + ";");
db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_AUDIO + ";");
}
sanityCheck(db, fromVersion);
}
/**
* Perform a simple sanity check on the database. Currently this tests
* whether all the _data entries in audio_meta are unique
*/
private static void sanityCheck(SQLiteDatabase db, int fromVersion) {
Cursor c1 = db.query("audio_meta", new String[] {"count(*)"},
null, null, null, null, null);
Cursor c2 = db.query("audio_meta", new String[] {"count(distinct _data)"},
null, null, null, null, null);
c1.moveToFirst();
c2.moveToFirst();
int num1 = c1.getInt(0);
int num2 = c2.getInt(0);
c1.close();
c2.close();
if (num1 != num2) {
Log.e(TAG, "audio_meta._data column is not unique while upgrading" +
" from schema " +fromVersion + " : " + num1 +"/" + num2);
// Delete all audio_meta rows so they will be rebuilt by the media scanner
db.execSQL("DELETE FROM audio_meta;");
}
}
private static void recreateAudioView(SQLiteDatabase db) {
// Provides a unified audio/artist/album info view.
// Note that views are read-only, so we define a trigger to allow deletes.
db.execSQL("DROP VIEW IF EXISTS audio");
db.execSQL("DROP TRIGGER IF EXISTS audio_delete");
db.execSQL("CREATE VIEW IF NOT EXISTS audio as SELECT * FROM audio_meta " +
"LEFT OUTER JOIN artists ON audio_meta.artist_id=artists.artist_id " +
"LEFT OUTER JOIN albums ON audio_meta.album_id=albums.album_id;");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_delete INSTEAD OF DELETE ON audio " +
"BEGIN " +
"DELETE from audio_meta where _id=old._id;" +
"DELETE from audio_playlists_map where audio_id=old._id;" +
"DELETE from audio_genres_map where audio_id=old._id;" +
"END");
}
/**
* Iterate through the rows of a table in a database, ensuring that the bucket_id and
* bucket_display_name columns are correct.
* @param db
* @param tableName
*/
private static void updateBucketNames(SQLiteDatabase db, String tableName) {
// Rebuild the bucket_display_name column using the natural case rather than lower case.
db.beginTransaction();
try {
String[] columns = {BaseColumns._ID, MediaColumns.DATA};
Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
try {
final int idColumnIndex = cursor.getColumnIndex(BaseColumns._ID);
final int dataColumnIndex = cursor.getColumnIndex(MediaColumns.DATA);
while (cursor.moveToNext()) {
String data = cursor.getString(dataColumnIndex);
ContentValues values = new ContentValues();
computeBucketValues(data, values);
int rowId = cursor.getInt(idColumnIndex);
db.update(tableName, values, "_id=" + rowId, null);
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* Iterate through the rows of a table in a database, ensuring that the
* display name column has a value.
* @param db
* @param tableName
*/
private static void updateDisplayName(SQLiteDatabase db, String tableName) {
// Fill in default values for null displayName values
db.beginTransaction();
try {
String[] columns = {BaseColumns._ID, MediaColumns.DATA, MediaColumns.DISPLAY_NAME};
Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
try {
final int idColumnIndex = cursor.getColumnIndex(BaseColumns._ID);
final int dataColumnIndex = cursor.getColumnIndex(MediaColumns.DATA);
final int displayNameIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
ContentValues values = new ContentValues();
while (cursor.moveToNext()) {
String displayName = cursor.getString(displayNameIndex);
if (displayName == null) {
String data = cursor.getString(dataColumnIndex);
values.clear();
computeDisplayName(data, values);
int rowId = cursor.getInt(idColumnIndex);
db.update(tableName, values, "_id=" + rowId, null);
}
}
} finally {
cursor.close();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* @param data The input path
* @param values the content values, where the bucked id name and bucket display name are updated.
*
*/
private static void computeBucketValues(String data, ContentValues values) {
data = fixExternalStoragePath(data);
File parentFile = new File(data).getParentFile();
if (parentFile == null) {
parentFile = new File("/");
}
// Lowercase the path for hashing. This avoids duplicate buckets if the
// filepath case is changed externally.
// Keep the original case for display.
String path = parentFile.toString().toLowerCase();
String name = parentFile.getName();
// Note: the BUCKET_ID and BUCKET_DISPLAY_NAME attributes are spelled the
// same for both images and video. However, for backwards-compatibility reasons
// there is no common base class. We use the ImageColumns version here
values.put(ImageColumns.BUCKET_ID, path.hashCode());
values.put(ImageColumns.BUCKET_DISPLAY_NAME, name);
}
/**
* @param data The input path
* @param values the content values, where the display name is updated.
*
*/
private static void computeDisplayName(String data, ContentValues values) {
String s = (data == null ? "" : data.toString());
int idx = s.lastIndexOf('/');
if (idx >= 0) {
s = s.substring(idx + 1);
}
values.put("_display_name", s);
}
/**
* Copy taken time from date_modified if we lost the original value (e.g. after factory reset)
* This works for both video and image tables.
*
* @param values the content values, where taken time is updated.
*/
private static void computeTakenTime(ContentValues values) {
if (! values.containsKey(Images.Media.DATE_TAKEN)) {
// This only happens when MediaScanner finds an image file that doesn't have any useful
// reference to get this value. (e.g. GPSTimeStamp)
Long lastModified = values.getAsLong(MediaColumns.DATE_MODIFIED);
if (lastModified != null) {
values.put(Images.Media.DATE_TAKEN, lastModified * 1000);
}
}
}
/**
* This method blocks until thumbnail is ready.
*
* @param thumbUri
* @return
*/
private boolean waitForThumbnailReady(Uri origUri) {
Cursor c = this.query(origUri, new String[] { ImageColumns._ID, ImageColumns.DATA,
ImageColumns.MINI_THUMB_MAGIC}, null, null, null);
if (c == null) return false;
boolean result = false;
if (c.moveToFirst()) {
long id = c.getLong(0);
String path = c.getString(1);
long magic = c.getLong(2);
path = fixExternalStoragePath(path);
MediaThumbRequest req = requestMediaThumbnail(path, origUri,
MediaThumbRequest.PRIORITY_HIGH, magic);
if (req == null) {
return false;
}
synchronized (req) {
try {
while (req.mState == MediaThumbRequest.State.WAIT) {
req.wait();
}
} catch (InterruptedException e) {
Log.w(TAG, e);
}
if (req.mState == MediaThumbRequest.State.DONE) {
result = true;
}
}
}
c.close();
return result;
}
private boolean matchThumbRequest(MediaThumbRequest req, int pid, long id, long gid,
boolean isVideo) {
boolean cancelAllOrigId = (id == -1);
boolean cancelAllGroupId = (gid == -1);
return (req.mCallingPid == pid) &&
(cancelAllGroupId || req.mGroupId == gid) &&
(cancelAllOrigId || req.mOrigId == id) &&
(req.mIsVideo == isVideo);
}
private boolean queryThumbnail(SQLiteQueryBuilder qb, Uri uri, String table,
String column, boolean hasThumbnailId) {
qb.setTables(table);
if (hasThumbnailId) {
// For uri dispatched to this method, the 4th path segment is always
// the thumbnail id.
qb.appendWhere("_id = " + uri.getPathSegments().get(3));
// client already knows which thumbnail it wants, bypass it.
return true;
}
String origId = uri.getQueryParameter("orig_id");
// We can't query ready_flag unless we know original id
if (origId == null) {
// this could be thumbnail query for other purpose, bypass it.
return true;
}
boolean needBlocking = "1".equals(uri.getQueryParameter("blocking"));
boolean cancelRequest = "1".equals(uri.getQueryParameter("cancel"));
Uri origUri = uri.buildUpon().encodedPath(
uri.getPath().replaceFirst("thumbnails", "media"))
.appendPath(origId).build();
if (needBlocking && !waitForThumbnailReady(origUri)) {
Log.w(TAG, "original media doesn't exist or it's canceled.");
return false;
} else if (cancelRequest) {
String groupId = uri.getQueryParameter("group_id");
boolean isVideo = "video".equals(uri.getPathSegments().get(1));
int pid = Binder.getCallingPid();
long id = -1;
long gid = -1;
try {
id = Long.parseLong(origId);
gid = Long.parseLong(groupId);
} catch (NumberFormatException ex) {
// invalid cancel request
return false;
}
synchronized (mMediaThumbQueue) {
if (mCurrentThumbRequest != null &&
matchThumbRequest(mCurrentThumbRequest, pid, id, gid, isVideo)) {
synchronized (mCurrentThumbRequest) {
mCurrentThumbRequest.mState = MediaThumbRequest.State.CANCEL;
mCurrentThumbRequest.notifyAll();
}
}
for (MediaThumbRequest mtq : mMediaThumbQueue) {
if (matchThumbRequest(mtq, pid, id, gid, isVideo)) {
synchronized (mtq) {
mtq.mState = MediaThumbRequest.State.CANCEL;
mtq.notifyAll();
}
mMediaThumbQueue.remove(mtq);
}
}
}
}
if (origId != null) {
qb.appendWhere(column + " = " + origId);
}
return true;
}
@SuppressWarnings("fallthrough")
@Override
public Cursor query(Uri uri, String[] projectionIn, String selection,
String[] selectionArgs, String sort) {
int table = URI_MATCHER.match(uri);
// Log.v(TAG, "query: uri="+uri+", selection="+selection);
// handle MEDIA_SCANNER before calling getDatabaseForUri()
if (table == MEDIA_SCANNER) {
if (mMediaScannerVolume == null) {
return null;
} else {
// create a cursor to return volume currently being scanned by the media scanner
MatrixCursor c = new MatrixCursor(new String[] {MediaStore.MEDIA_SCANNER_VOLUME});
c.addRow(new String[] {mMediaScannerVolume});
return c;
}
}
// Used temporarily (until we have unique media IDs) to get an identifier
// for the current sd card, so that the music app doesn't have to use the
// non-public getFatVolumeId method
if (table == FS_ID) {
MatrixCursor c = new MatrixCursor(new String[] {"fsid"});
c.addRow(new Integer[] {mVolumeId});
return c;
}
String groupBy = null;
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null) {
return null;
}
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String limit = uri.getQueryParameter("limit");
String filter = uri.getQueryParameter("filter");
String [] keywords = null;
if (filter != null) {
filter = Uri.decode(filter).trim();
if (!TextUtils.isEmpty(filter)) {
String [] searchWords = filter.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
String key = MediaStore.Audio.keyFor(searchWords[i]);
key = key.replace("\\", "\\\\");
key = key.replace("%", "\\%");
key = key.replace("_", "\\_");
keywords[i] = key;
}
}
}
boolean hasThumbnailId = false;
switch (table) {
case IMAGES_MEDIA:
qb.setTables("images");
if (uri.getQueryParameter("distinct") != null)
qb.setDistinct(true);
// set the project map so that data dir is prepended to _data.
//qb.setProjectionMap(mImagesProjectionMap, true);
break;
case IMAGES_MEDIA_ID:
qb.setTables("images");
if (uri.getQueryParameter("distinct") != null)
qb.setDistinct(true);
// set the project map so that data dir is prepended to _data.
//qb.setProjectionMap(mImagesProjectionMap, true);
qb.appendWhere("_id = " + uri.getPathSegments().get(3));
break;
case IMAGES_THUMBNAILS_ID:
hasThumbnailId = true;
case IMAGES_THUMBNAILS:
if (!queryThumbnail(qb, uri, "thumbnails", "image_id", hasThumbnailId)) {
return null;
}
break;
case AUDIO_MEDIA:
if (projectionIn != null && projectionIn.length == 1 && selectionArgs == null
&& (selection == null || selection.equalsIgnoreCase("is_music=1")
|| selection.equalsIgnoreCase("is_podcast=1") )
&& projectionIn[0].equalsIgnoreCase("count(*)")
&& keywords != null) {
//Log.i("@@@@", "taking fast path for counting songs");
qb.setTables("audio_meta");
} else {
qb.setTables("audio");
for (int i = 0; keywords != null && i < keywords.length; i++) {
if (i > 0) {
qb.appendWhere(" AND ");
}
qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
"||" + MediaStore.Audio.Media.ALBUM_KEY +
"||" + MediaStore.Audio.Media.TITLE_KEY + " LIKE '%" +
keywords[i] + "%' ESCAPE '\\'");
}
}
break;
case AUDIO_MEDIA_ID:
qb.setTables("audio");
qb.appendWhere("_id=" + uri.getPathSegments().get(3));
break;
case AUDIO_MEDIA_ID_GENRES:
qb.setTables("audio_genres");
qb.appendWhere("_id IN (SELECT genre_id FROM " +
"audio_genres_map WHERE audio_id = " +
uri.getPathSegments().get(3) + ")");
break;
case AUDIO_MEDIA_ID_GENRES_ID:
qb.setTables("audio_genres");
qb.appendWhere("_id=" + uri.getPathSegments().get(5));
break;
case AUDIO_MEDIA_ID_PLAYLISTS:
qb.setTables("audio_playlists");
qb.appendWhere("_id IN (SELECT playlist_id FROM " +
"audio_playlists_map WHERE audio_id = " +
uri.getPathSegments().get(3) + ")");
break;
case AUDIO_MEDIA_ID_PLAYLISTS_ID:
qb.setTables("audio_playlists");
qb.appendWhere("_id=" + uri.getPathSegments().get(5));
break;
case AUDIO_GENRES:
qb.setTables("audio_genres");
break;
case AUDIO_GENRES_ID:
qb.setTables("audio_genres");
qb.appendWhere("_id=" + uri.getPathSegments().get(3));
break;
case AUDIO_GENRES_ID_MEMBERS:
qb.setTables("audio");
qb.appendWhere("_id IN (SELECT audio_id FROM " +
"audio_genres_map WHERE genre_id = " +
uri.getPathSegments().get(3) + ")");
break;
case AUDIO_GENRES_ID_MEMBERS_ID:
qb.setTables("audio");
qb.appendWhere("_id=" + uri.getPathSegments().get(5));
break;
case AUDIO_PLAYLISTS:
qb.setTables("audio_playlists");
break;
case AUDIO_PLAYLISTS_ID:
qb.setTables("audio_playlists");
qb.appendWhere("_id=" + uri.getPathSegments().get(3));
break;
case AUDIO_PLAYLISTS_ID_MEMBERS:
if (projectionIn != null) {
for (int i = 0; i < projectionIn.length; i++) {
if (projectionIn[i].equals("_id")) {
projectionIn[i] = "audio_playlists_map._id AS _id";
}
}
}
qb.setTables("audio_playlists_map, audio");
qb.appendWhere("audio._id = audio_id AND playlist_id = "
+ uri.getPathSegments().get(3));
for (int i = 0; keywords != null && i < keywords.length; i++) {
qb.appendWhere(" AND ");
qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
"||" + MediaStore.Audio.Media.ALBUM_KEY +
"||" + MediaStore.Audio.Media.TITLE_KEY +
" LIKE '%" + keywords[i] + "%' ESCAPE '\\'");
}
break;
case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
qb.setTables("audio");
qb.appendWhere("_id=" + uri.getPathSegments().get(5));
break;
case VIDEO_MEDIA:
qb.setTables("video");
if (uri.getQueryParameter("distinct") != null) {
qb.setDistinct(true);
}
break;
case VIDEO_MEDIA_ID:
qb.setTables("video");
if (uri.getQueryParameter("distinct") != null) {
qb.setDistinct(true);
}
qb.appendWhere("_id=" + uri.getPathSegments().get(3));
break;
case VIDEO_THUMBNAILS_ID:
hasThumbnailId = true;
case VIDEO_THUMBNAILS:
if (!queryThumbnail(qb, uri, "videothumbnails", "video_id", hasThumbnailId)) {
return null;
}
break;
case AUDIO_ARTISTS:
if (projectionIn != null && projectionIn.length == 1 && selectionArgs == null
&& (selection == null || selection.length() == 0)
&& projectionIn[0].equalsIgnoreCase("count(*)")
&& keywords != null) {
//Log.i("@@@@", "taking fast path for counting artists");
qb.setTables("audio_meta");
projectionIn[0] = "count(distinct artist_id)";
qb.appendWhere("is_music=1");
} else {
qb.setTables("artist_info");
for (int i = 0; keywords != null && i < keywords.length; i++) {
if (i > 0) {
qb.appendWhere(" AND ");
}
qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
" LIKE '%" + keywords[i] + "%' ESCAPE '\\'");
}
}
break;
case AUDIO_ARTISTS_ID:
qb.setTables("artist_info");
qb.appendWhere("_id=" + uri.getPathSegments().get(3));
break;
case AUDIO_ARTISTS_ID_ALBUMS:
String aid = uri.getPathSegments().get(3);
qb.setTables("audio LEFT OUTER JOIN album_art ON" +
" audio.album_id=album_art.album_id");
qb.appendWhere("is_music=1 AND audio.album_id IN (SELECT album_id FROM " +
"artists_albums_map WHERE artist_id = " +
aid + ")");
for (int i = 0; keywords != null && i < keywords.length; i++) {
qb.appendWhere(" AND ");
qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
"||" + MediaStore.Audio.Media.ALBUM_KEY +
" LIKE '%" + keywords[i] + "%' ESCAPE '\\'");
}
groupBy = "audio.album_id";
sArtistAlbumsMap.put(MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST,
"count(CASE WHEN artist_id==" + aid + " THEN 'foo' ELSE NULL END) AS " +
MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST);
qb.setProjectionMap(sArtistAlbumsMap);
break;
case AUDIO_ALBUMS:
if (projectionIn != null && projectionIn.length == 1 && selectionArgs == null
&& (selection == null || selection.length() == 0)
&& projectionIn[0].equalsIgnoreCase("count(*)")
&& keywords != null) {
//Log.i("@@@@", "taking fast path for counting albums");
qb.setTables("audio_meta");
projectionIn[0] = "count(distinct album_id)";
qb.appendWhere("is_music=1");
} else {
qb.setTables("album_info");
for (int i = 0; keywords != null && i < keywords.length; i++) {
if (i > 0) {
qb.appendWhere(" AND ");
}
qb.appendWhere(MediaStore.Audio.Media.ARTIST_KEY +
"||" + MediaStore.Audio.Media.ALBUM_KEY +
" LIKE '%" + keywords[i] + "%' ESCAPE '\\'");
}
}
break;
case AUDIO_ALBUMS_ID:
qb.setTables("album_info");
qb.appendWhere("_id=" + uri.getPathSegments().get(3));
break;
case AUDIO_ALBUMART_ID:
qb.setTables("album_art");
qb.appendWhere("album_id=" + uri.getPathSegments().get(3));
break;
case AUDIO_SEARCH_LEGACY:
Log.w(TAG, "Legacy media search Uri used. Please update your code.");
// fall through
case AUDIO_SEARCH_FANCY:
case AUDIO_SEARCH_BASIC:
return doAudioSearch(db, qb, uri, projectionIn, selection, selectionArgs, sort,
table, limit);
case FILES_ID:
case MTP_OBJECTS_ID:
qb.appendWhere("_id=" + uri.getPathSegments().get(2));
// fall through
case FILES:
case MTP_OBJECTS:
qb.setTables("files");
break;
case MTP_OBJECT_REFERENCES:
int handle = Integer.parseInt(uri.getPathSegments().get(2));
return getObjectReferences(db, handle);
default:
throw new IllegalStateException("Unknown URL: " + uri.toString());
}
// Log.v(TAG, "query = "+ qb.buildQuery(projectionIn, selection, selectionArgs, groupBy, null, sort, limit));
Cursor c = qb.query(db, projectionIn, selection,
selectionArgs, groupBy, null, sort, limit);
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
private Cursor doAudioSearch(SQLiteDatabase db, SQLiteQueryBuilder qb,
Uri uri, String[] projectionIn, String selection,
String[] selectionArgs, String sort, int mode,
String limit) {
String mSearchString = uri.getPath().endsWith("/") ? "" : uri.getLastPathSegment();
mSearchString = mSearchString.replaceAll(" ", " ").trim().toLowerCase();
String [] searchWords = mSearchString.length() > 0 ?
mSearchString.split(" ") : new String[0];
String [] wildcardWords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
int len = searchWords.length;
for (int i = 0; i < len; i++) {
// Because we match on individual words here, we need to remove words
// like 'a' and 'the' that aren't part of the keys.
String key = MediaStore.Audio.keyFor(searchWords[i]);
key = key.replace("\\", "\\\\");
key = key.replace("%", "\\%");
key = key.replace("_", "\\_");
wildcardWords[i] =
(searchWords[i].equals("a") || searchWords[i].equals("an") ||
searchWords[i].equals("the")) ? "%" : "%" + key + "%";
}
String where = "";
for (int i = 0; i < searchWords.length; i++) {
if (i == 0) {
where = "match LIKE ? ESCAPE '\\'";
} else {
where += " AND match LIKE ? ESCAPE '\\'";
}
}
qb.setTables("search");
String [] cols;
if (mode == AUDIO_SEARCH_FANCY) {
cols = mSearchColsFancy;
} else if (mode == AUDIO_SEARCH_BASIC) {
cols = mSearchColsBasic;
} else {
cols = mSearchColsLegacy;
}
return qb.query(db, cols, where, wildcardWords, null, null, null, limit);
}
@Override
public String getType(Uri url)
{
switch (URI_MATCHER.match(url)) {
case IMAGES_MEDIA_ID:
case AUDIO_MEDIA_ID:
case AUDIO_GENRES_ID_MEMBERS_ID:
case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
case VIDEO_MEDIA_ID:
case FILES_ID:
Cursor c = null;
try {
c = query(url, MIME_TYPE_PROJECTION, null, null, null);
if (c != null && c.getCount() == 1) {
c.moveToFirst();
String mimeType = c.getString(1);
c.deactivate();
return mimeType;
}
} finally {
if (c != null) {
c.close();
}
}
break;
case IMAGES_MEDIA:
case IMAGES_THUMBNAILS:
return Images.Media.CONTENT_TYPE;
case AUDIO_ALBUMART_ID:
case IMAGES_THUMBNAILS_ID:
return "image/jpeg";
case AUDIO_MEDIA:
case AUDIO_GENRES_ID_MEMBERS:
case AUDIO_PLAYLISTS_ID_MEMBERS:
return Audio.Media.CONTENT_TYPE;
case AUDIO_GENRES:
case AUDIO_MEDIA_ID_GENRES:
return Audio.Genres.CONTENT_TYPE;
case AUDIO_GENRES_ID:
case AUDIO_MEDIA_ID_GENRES_ID:
return Audio.Genres.ENTRY_CONTENT_TYPE;
case AUDIO_PLAYLISTS:
case AUDIO_MEDIA_ID_PLAYLISTS:
return Audio.Playlists.CONTENT_TYPE;
case AUDIO_PLAYLISTS_ID:
case AUDIO_MEDIA_ID_PLAYLISTS_ID:
return Audio.Playlists.ENTRY_CONTENT_TYPE;
case VIDEO_MEDIA:
return Video.Media.CONTENT_TYPE;
}
throw new IllegalStateException("Unknown URL : " + url);
}
/**
* Ensures there is a file in the _data column of values, if one isn't
* present a new file is created.
*
* @param initialValues the values passed to insert by the caller
* @return the new values
*/
private ContentValues ensureFile(boolean internal, ContentValues initialValues,
String preferredExtension, String directoryName) {
ContentValues values;
String file = initialValues.getAsString("_data");
file = fixExternalStoragePath(file);
if (TextUtils.isEmpty(file)) {
file = generateFileName(internal, preferredExtension, directoryName);
values = new ContentValues(initialValues);
values.put("_data", file);
} else {
values = initialValues;
}
if (!ensureFileExists(file)) {
throw new IllegalStateException("Unable to create new file: " + file);
}
return values;
}
private void sendObjectAdded(long objectHandle) {
IMtpService mtpService = mMtpService;
if (mtpService != null) {
try {
mtpService.sendObjectAdded((int)objectHandle);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in sendObjectAdded", e);
}
}
}
private void sendObjectRemoved(long objectHandle) {
IMtpService mtpService = mMtpService;
if (mtpService != null) {
try {
mtpService.sendObjectRemoved((int)objectHandle);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in sendObjectRemoved", e);
}
}
}
@Override
public int bulkInsert(Uri uri, ContentValues values[]) {
for (int i = 0; i < values.length; i++) {
values[i] = fixExternalStoragePath(values[i]);
}
int match = URI_MATCHER.match(uri);
if (match == VOLUMES) {
return super.bulkInsert(uri, values);
}
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null) {
throw new UnsupportedOperationException(
"Unknown URI: " + uri);
}
SQLiteDatabase db = database.getWritableDatabase();
if (match == AUDIO_PLAYLISTS_ID || match == AUDIO_PLAYLISTS_ID_MEMBERS) {
return playlistBulkInsert(db, uri, values);
} else if (match == MTP_OBJECT_REFERENCES) {
int handle = Integer.parseInt(uri.getPathSegments().get(2));
return setObjectReferences(db, handle, values);
}
db.beginTransaction();
int numInserted = 0;
try {
int len = values.length;
for (int i = 0; i < len; i++) {
insertInternal(uri, match, values[i]);
}
numInserted = len;
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return numInserted;
}
@Override
public Uri insert(Uri uri, ContentValues initialValues)
{
initialValues = fixExternalStoragePath(initialValues);
int match = URI_MATCHER.match(uri);
Uri newUri = insertInternal(uri, match, initialValues);
// do not signal notification for MTP objects.
// we will signal instead after file transfer is successful.
if (newUri != null && match != MTP_OBJECTS) {
getContext().getContentResolver().notifyChange(uri, null);
}
return newUri;
}
private int playlistBulkInsert(SQLiteDatabase db, Uri uri, ContentValues values[]) {
DatabaseUtils.InsertHelper helper =
new DatabaseUtils.InsertHelper(db, "audio_playlists_map");
int audioidcolidx = helper.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
int playlistididx = helper.getColumnIndex(Audio.Playlists.Members.PLAYLIST_ID);
int playorderidx = helper.getColumnIndex(MediaStore.Audio.Playlists.Members.PLAY_ORDER);
long playlistId = Long.parseLong(uri.getPathSegments().get(3));
db.beginTransaction();
int numInserted = 0;
try {
int len = values.length;
for (int i = 0; i < len; i++) {
helper.prepareForInsert();
// getting the raw Object and converting it long ourselves saves
// an allocation (the alternative is ContentValues.getAsLong, which
// returns a Long object)
long audioid = ((Number) values[i].get(
MediaStore.Audio.Playlists.Members.AUDIO_ID)).longValue();
helper.bind(audioidcolidx, audioid);
helper.bind(playlistididx, playlistId);
// convert to int ourselves to save an allocation.
int playorder = ((Number) values[i].get(
MediaStore.Audio.Playlists.Members.PLAY_ORDER)).intValue();
helper.bind(playorderidx, playorder);
helper.execute();
}
numInserted = len;
db.setTransactionSuccessful();
} finally {
db.endTransaction();
helper.close();
}
getContext().getContentResolver().notifyChange(uri, null);
return numInserted;
}
private long getParent(SQLiteDatabase db, String path) {
int lastSlash = path.lastIndexOf('/');
if (lastSlash > 0) {
String parentPath = path.substring(0, lastSlash);
if (parentPath.equals(mExternalStoragePath)) {
return 0;
}
String [] selargs = { parentPath };
Cursor c = db.query("files", null, MediaStore.MediaColumns.DATA + "=?",
selargs, null, null, null);
try {
if (c == null || c.getCount() == 0) {
// parent isn't in the database - so add it
ContentValues values = new ContentValues();
values.put(FileColumns.FORMAT, MtpConstants.FORMAT_ASSOCIATION);
values.put(FileColumns.DATA, parentPath);
values.put(FileColumns.PARENT, getParent(db, parentPath));
long parent = db.insert("files", FileColumns.DATE_MODIFIED, values);
sendObjectAdded(parent);
return parent;
} else {
c.moveToFirst();
return c.getLong(0);
}
} finally {
if (c != null) c.close();
}
} else {
return 0;
}
}
private long insertFile(DatabaseHelper database, Uri uri, ContentValues initialValues, int mediaType,
boolean notify) {
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = null;
switch (mediaType) {
case FileColumns.MEDIA_TYPE_IMAGE: {
values = ensureFile(database.mInternal, initialValues, ".jpg", "DCIM/Camera");
values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
String data = values.getAsString(MediaColumns.DATA);
if (! values.containsKey(MediaColumns.DISPLAY_NAME)) {
computeDisplayName(data, values);
}
computeBucketValues(data, values);
computeTakenTime(values);
break;
}
case FileColumns.MEDIA_TYPE_AUDIO: {
// SQLite Views are read-only, so we need to deconstruct this
// insert and do inserts into the underlying tables.
// If doing this here turns out to be a performance bottleneck,
// consider moving this to native code and using triggers on
// the view.
values = new ContentValues(initialValues);
// Insert the artist into the artist table and remove it from
// the input values
Object so = values.get("artist");
String s = (so == null ? "" : so.toString());
values.remove("artist");
long artistRowId;
HashMap<String, Long> artistCache = database.mArtistCache;
String path = values.getAsString("_data");
path = fixExternalStoragePath(path);
synchronized(artistCache) {
Long temp = artistCache.get(s);
if (temp == null) {
artistRowId = getKeyIdForName(db, "artists", "artist_key", "artist",
s, s, path, 0, null, artistCache, uri);
} else {
artistRowId = temp.longValue();
}
}
String artist = s;
// Do the same for the album field
so = values.get("album");
s = (so == null ? "" : so.toString());
values.remove("album");
long albumRowId;
HashMap<String, Long> albumCache = database.mAlbumCache;
synchronized(albumCache) {
int albumhash = path.substring(0, path.lastIndexOf('/')).hashCode();
String cacheName = s + albumhash;
Long temp = albumCache.get(cacheName);
if (temp == null) {
albumRowId = getKeyIdForName(db, "albums", "album_key", "album",
s, cacheName, path, albumhash, artist, albumCache, uri);
} else {
albumRowId = temp;
}
}
values.put("artist_id", Integer.toString((int)artistRowId));
values.put("album_id", Integer.toString((int)albumRowId));
so = values.getAsString("title");
s = (so == null ? "" : so.toString());
values.put("title_key", MediaStore.Audio.keyFor(s));
// do a final trim of the title, in case it started with the special
// "sort first" character (ascii \001)
values.remove("title");
values.put("title", s.trim());
computeDisplayName(values.getAsString("_data"), values);
values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
break;
}
case FileColumns.MEDIA_TYPE_VIDEO: {
values = ensureFile(database.mInternal, initialValues, ".3gp", "video");
String data = values.getAsString("_data");
computeDisplayName(data, values);
computeBucketValues(data, values);
values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
computeTakenTime(values);
break;
}
}
if (values == null) {
values = new ContentValues(initialValues);
}
String path = values.getAsString(MediaStore.MediaColumns.DATA);
long rowId = 0;
Integer i = values.getAsInteger(
MediaStore.MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID);
if (i != null) {
rowId = i.intValue();
values = new ContentValues(values);
values.remove(MediaStore.MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID);
}
String title = values.getAsString(MediaStore.MediaColumns.TITLE);
if (title == null) {
title = MediaFile.getFileTitle(path);
}
values.put(FileColumns.TITLE, title);
String mimeType = values.getAsString(MediaStore.MediaColumns.MIME_TYPE);
Integer formatObject = values.getAsInteger(FileColumns.FORMAT);
int format = (formatObject == null ? 0 : formatObject.intValue());
if (format == 0) {
if (path == null) {
// special case device created playlists
if (mediaType == FileColumns.MEDIA_TYPE_PLAYLIST) {
values.put(FileColumns.FORMAT, MtpConstants.FORMAT_ABSTRACT_AV_PLAYLIST);
// create a file path for the benefit of MTP
path = mExternalStoragePath
+ "/Playlists/" + values.getAsString(Audio.Playlists.NAME);
values.put(MediaStore.MediaColumns.DATA, path);
values.put(FileColumns.PARENT, getParent(db, path));
} else {
Log.e(TAG, "path is null in insertObject()");
}
} else {
format = MediaFile.getFormatCode(path, mimeType);
}
}
if (format != 0) {
values.put(FileColumns.FORMAT, format);
if (mimeType == null) {
mimeType = MediaFile.getMimeTypeForFormatCode(format);
}
}
if (mimeType == null) {
mimeType = MediaFile.getMimeTypeForFile(path);
}
if (mimeType != null) {
values.put(FileColumns.MIME_TYPE, mimeType);
if (mediaType == FileColumns.MEDIA_TYPE_NONE) {
int fileType = MediaFile.getFileTypeForMimeType(mimeType);
if (MediaFile.isAudioFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_AUDIO;
} else if (MediaFile.isVideoFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_VIDEO;
} else if (MediaFile.isImageFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_IMAGE;
} else if (MediaFile.isPlayListFileType(fileType)) {
mediaType = FileColumns.MEDIA_TYPE_PLAYLIST;
}
}
}
values.put(FileColumns.MEDIA_TYPE, mediaType);
if (rowId == 0) {
if (mediaType == FileColumns.MEDIA_TYPE_PLAYLIST) {
String name = values.getAsString(Audio.Playlists.Members.AUDIO_ID);
if (name == null) {
throw new IllegalArgumentException(
"no name was provided when inserting playlist");
}
} else {
if (path == null) {
// path might be null for playlists created on the device
// or transfered via MTP
throw new IllegalArgumentException(
"no path was provided when inserting new file");
}
}
Long size = values.getAsLong(MediaStore.MediaColumns.SIZE);
if (size == null) {
if (path != null) {
File file = new File(path);
values.put(FileColumns.SIZE, file.length());
}
} else {
values.put(FileColumns.SIZE, size);
}
Long parent = values.getAsLong(FileColumns.PARENT);
if (parent == null) {
if (path != null) {
long parentId = getParent(db, path);
values.put(FileColumns.PARENT, parentId);
}
} else {
values.put(FileColumns.PARENT, parent);
}
Integer modified = values.getAsInteger(MediaStore.MediaColumns.DATE_MODIFIED);
if (modified != null) {
values.put(FileColumns.DATE_MODIFIED, modified);
}
rowId = db.insert("files", FileColumns.DATE_MODIFIED, values);
if (LOCAL_LOGV) Log.v(TAG, "insertFile: values=" + values + " returned: " + rowId);
if (rowId != 0 && notify) {
sendObjectAdded(rowId);
}
} else {
db.update("files", values, FileColumns._ID + "=?",
new String[] { Long.toString(rowId) });
}
return rowId;
}
private Cursor getObjectReferences(SQLiteDatabase db, int handle) {
Cursor c = db.query("files", mMediaTableColumns, "_id=?",
new String[] { Integer.toString(handle) },
null, null, null);
try {
if (c != null && c.moveToNext()) {
long playlistId = c.getLong(0);
int mediaType = c.getInt(1);
if (mediaType != FileColumns.MEDIA_TYPE_PLAYLIST) {
// we only support object references for playlist objects
return null;
}
return db.rawQuery(OBJECT_REFERENCES_QUERY,
new String[] { Long.toString(playlistId) } );
}
} finally {
if (c != null) {
c.close();
}
}
return null;
}
private int setObjectReferences(SQLiteDatabase db, int handle, ContentValues values[]) {
// first look up the media table and media ID for the object
long playlistId = 0;
Cursor c = db.query("files", mMediaTableColumns, "_id=?",
new String[] { Integer.toString(handle) },
null, null, null);
try {
if (c != null && c.moveToNext()) {
int mediaType = c.getInt(1);
if (mediaType != FileColumns.MEDIA_TYPE_PLAYLIST) {
// we only support object references for playlist objects
return 0;
}
playlistId = c.getLong(0);
}
} finally {
if (c != null) {
c.close();
}
}
if (playlistId == 0) {
return 0;
}
// next delete any existing entries
db.delete("audio_playlists_map", "playlist_id=?",
new String[] { Long.toString(playlistId) });
// finally add the new entries
int count = values.length;
int added = 0;
ContentValues[] valuesList = new ContentValues[count];
for (int i = 0; i < count; i++) {
// convert object ID to audio ID
long audioId = 0;
long objectId = values[i].getAsLong(MediaStore.MediaColumns._ID);
c = db.query("files", mMediaTableColumns, "_id=?",
new String[] { Long.toString(objectId) },
null, null, null);
try {
if (c != null && c.moveToNext()) {
int mediaType = c.getInt(1);
if (mediaType != FileColumns.MEDIA_TYPE_PLAYLIST) {
// we only allow audio files in playlists, so skip
continue;
}
audioId = c.getLong(0);
}
} finally {
if (c != null) {
c.close();
}
}
if (audioId != 0) {
ContentValues v = new ContentValues();
v.put(MediaStore.Audio.Playlists.Members.PLAYLIST_ID, playlistId);
v.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audioId);
v.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, added++);
valuesList[i] = v;
}
}
if (added < count) {
// we weren't able to find everything on the list, so lets resize the array
// and pass what we have.
ContentValues[] newValues = new ContentValues[added];
System.arraycopy(valuesList, 0, newValues, 0, added);
valuesList = newValues;
}
return playlistBulkInsert(db,
Audio.Playlists.Members.getContentUri(EXTERNAL_VOLUME, playlistId),
valuesList);
}
private Uri insertInternal(Uri uri, int match, ContentValues initialValues) {
long rowId;
if (LOCAL_LOGV) Log.v(TAG, "insertInternal: "+uri+", initValues="+initialValues);
// handle MEDIA_SCANNER before calling getDatabaseForUri()
if (match == MEDIA_SCANNER) {
mMediaScannerVolume = initialValues.getAsString(MediaStore.MEDIA_SCANNER_VOLUME);
return MediaStore.getMediaScannerUri();
}
Uri newUri = null;
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null && match != VOLUMES) {
throw new UnsupportedOperationException(
"Unknown URI: " + uri);
}
SQLiteDatabase db = (match == VOLUMES ? null : database.getWritableDatabase());
switch (match) {
case IMAGES_MEDIA: {
rowId = insertFile(database, uri, initialValues, FileColumns.MEDIA_TYPE_IMAGE, true);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(
Images.Media.getContentUri(uri.getPathSegments().get(0)), rowId);
}
break;
}
// This will be triggered by requestMediaThumbnail (see getThumbnailUri)
case IMAGES_THUMBNAILS: {
ContentValues values = ensureFile(database.mInternal, initialValues, ".jpg",
"DCIM/.thumbnails");
rowId = db.insert("thumbnails", "name", values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(Images.Thumbnails.
getContentUri(uri.getPathSegments().get(0)), rowId);
}
break;
}
// This is currently only used by MICRO_KIND video thumbnail (see getThumbnailUri)
case VIDEO_THUMBNAILS: {
ContentValues values = ensureFile(database.mInternal, initialValues, ".jpg",
"DCIM/.thumbnails");
rowId = db.insert("videothumbnails", "name", values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(Video.Thumbnails.
getContentUri(uri.getPathSegments().get(0)), rowId);
}
break;
}
case AUDIO_MEDIA: {
rowId = insertFile(database, uri, initialValues, FileColumns.MEDIA_TYPE_AUDIO, true);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(Audio.Media.getContentUri(uri.getPathSegments().get(0)), rowId);
}
break;
}
case AUDIO_MEDIA_ID_GENRES: {
Long audioId = Long.parseLong(uri.getPathSegments().get(2));
ContentValues values = new ContentValues(initialValues);
values.put(Audio.Genres.Members.AUDIO_ID, audioId);
rowId = db.insert("audio_genres_map", "genre_id", values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(uri, rowId);
}
break;
}
case AUDIO_MEDIA_ID_PLAYLISTS: {
Long audioId = Long.parseLong(uri.getPathSegments().get(2));
ContentValues values = new ContentValues(initialValues);
values.put(Audio.Playlists.Members.AUDIO_ID, audioId);
rowId = db.insert("audio_playlists_map", "playlist_id",
values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(uri, rowId);
}
break;
}
case AUDIO_GENRES: {
rowId = db.insert("audio_genres", "audio_id", initialValues);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(Audio.Genres.getContentUri(uri.getPathSegments().get(0)), rowId);
}
break;
}
case AUDIO_GENRES_ID_MEMBERS: {
Long genreId = Long.parseLong(uri.getPathSegments().get(3));
ContentValues values = new ContentValues(initialValues);
values.put(Audio.Genres.Members.GENRE_ID, genreId);
rowId = db.insert("audio_genres_map", "genre_id", values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(uri, rowId);
}
break;
}
case AUDIO_PLAYLISTS: {
ContentValues values = new ContentValues(initialValues);
values.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis() / 1000);
rowId = insertFile(database, uri, values, FileColumns.MEDIA_TYPE_PLAYLIST, true);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(Audio.Playlists.getContentUri(uri.getPathSegments().get(0)), rowId);
}
break;
}
case AUDIO_PLAYLISTS_ID:
case AUDIO_PLAYLISTS_ID_MEMBERS: {
Long playlistId = Long.parseLong(uri.getPathSegments().get(3));
ContentValues values = new ContentValues(initialValues);
values.put(Audio.Playlists.Members.PLAYLIST_ID, playlistId);
rowId = db.insert("audio_playlists_map", "playlist_id", values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(uri, rowId);
}
break;
}
case VIDEO_MEDIA: {
rowId = insertFile(database, uri, initialValues, FileColumns.MEDIA_TYPE_VIDEO, true);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(Video.Media.getContentUri(
uri.getPathSegments().get(0)), rowId);
}
break;
}
case AUDIO_ALBUMART: {
if (database.mInternal) {
throw new UnsupportedOperationException("no internal album art allowed");
}
ContentValues values = null;
try {
values = ensureFile(false, initialValues, "", ALBUM_THUMB_FOLDER);
} catch (IllegalStateException ex) {
// probably no more room to store albumthumbs
values = initialValues;
}
rowId = db.insert("album_art", "_data", values);
if (rowId > 0) {
newUri = ContentUris.withAppendedId(uri, rowId);
}
break;
}
case VOLUMES:
return attachVolume(initialValues.getAsString("name"));
case FILES:
case MTP_OBJECTS:
// don't send a notification if the insert originated from MTP
rowId = insertFile(database, uri, initialValues, FileColumns.MEDIA_TYPE_NONE,
(match != MTP_OBJECTS));
if (rowId > 0) {
newUri = Files.getMtpObjectsUri(uri.getPathSegments().get(0), rowId);
}
break;
default:
throw new UnsupportedOperationException("Invalid URI " + uri);
}
return newUri;
}
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
// The operations array provides no overall information about the URI(s) being operated
// on, so begin a transaction for ALL of the databases.
DatabaseHelper ihelper = getDatabaseForUri(MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
DatabaseHelper ehelper = getDatabaseForUri(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
SQLiteDatabase idb = ihelper.getWritableDatabase();
idb.beginTransaction();
SQLiteDatabase edb = null;
if (ehelper != null) {
edb = ehelper.getWritableDatabase();
edb.beginTransaction();
}
try {
ContentProviderResult[] result = super.applyBatch(operations);
idb.setTransactionSuccessful();
if (edb != null) {
edb.setTransactionSuccessful();
}
// Rather than sending targeted change notifications for every Uri
// affected by the batch operation, just invalidate the entire internal
// and external name space.
ContentResolver res = getContext().getContentResolver();
res.notifyChange(Uri.parse("content://media/"), null);
return result;
} finally {
idb.endTransaction();
if (edb != null) {
edb.endTransaction();
}
}
}
private MediaThumbRequest requestMediaThumbnail(String path, Uri uri, int priority, long magic) {
path = fixExternalStoragePath(path);
synchronized (mMediaThumbQueue) {
MediaThumbRequest req = null;
try {
req = new MediaThumbRequest(
getContext().getContentResolver(), path, uri, priority, magic);
mMediaThumbQueue.add(req);
// Trigger the handler.
Message msg = mThumbHandler.obtainMessage(IMAGE_THUMB);
msg.sendToTarget();
} catch (Throwable t) {
Log.w(TAG, t);
}
return req;
}
}
private String generateFileName(boolean internal, String preferredExtension, String directoryName)
{
// create a random file
String name = String.valueOf(System.currentTimeMillis());
if (internal) {
throw new UnsupportedOperationException("Writing to internal storage is not supported.");
// return Environment.getDataDirectory()
// + "/" + directoryName + "/" + name + preferredExtension;
} else {
return mExternalStoragePath + "/" + directoryName + "/" + name + preferredExtension;
}
}
private boolean ensureFileExists(String path) {
File file = new File(path);
if (file.exists()) {
return true;
} else {
// we will not attempt to create the first directory in the path
// (for example, do not create /sdcard if the SD card is not mounted)
int secondSlash = path.indexOf('/', 1);
if (secondSlash < 1) return false;
String directoryPath = path.substring(0, secondSlash);
File directory = new File(directoryPath);
if (!directory.exists())
return false;
File parent = file.getParentFile();
// create parent directories if necessary, and ensure they have correct permissions
if (!parent.exists()) {
parent.mkdirs();
String parentPath = parent.getPath();
if (parentPath.startsWith(mExternalStoragePath)) {
while (parent != null && !mExternalStoragePath.equals(parentPath)) {
FileUtils.setPermissions(parentPath, 0775, Process.myUid(),
Process.SDCARD_RW_GID);
parent = parent.getParentFile();
parentPath = parent.getPath();
}
}
}
try {
if (file.createNewFile()) {
// file should be writeable for SDCARD_RW group and world readable
FileUtils.setPermissions(file.getPath(), 0664, Process.myUid(),
Process.SDCARD_RW_GID);
return true;
}
} catch(IOException ioe) {
Log.e(TAG, "File creation failed", ioe);
}
return false;
}
}
private static final class GetTableAndWhereOutParameter {
public String table;
public String where;
}
static final GetTableAndWhereOutParameter sGetTableAndWhereParam =
new GetTableAndWhereOutParameter();
private void getTableAndWhere(Uri uri, int match, String userWhere,
GetTableAndWhereOutParameter out) {
String where = null;
switch (match) {
case IMAGES_MEDIA:
out.table = "files";
where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_IMAGE;
break;
case IMAGES_MEDIA_ID:
out.table = "files";
where = "_id = " + uri.getPathSegments().get(3);
break;
case IMAGES_THUMBNAILS_ID:
where = "_id=" + uri.getPathSegments().get(3);
case IMAGES_THUMBNAILS:
out.table = "thumbnails";
break;
case AUDIO_MEDIA:
out.table = "files";
where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_AUDIO;
break;
case AUDIO_MEDIA_ID:
out.table = "files";
where = "_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_MEDIA_ID_GENRES:
out.table = "audio_genres";
where = "audio_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_MEDIA_ID_GENRES_ID:
out.table = "audio_genres";
where = "audio_id=" + uri.getPathSegments().get(3) +
" AND genre_id=" + uri.getPathSegments().get(5);
break;
case AUDIO_MEDIA_ID_PLAYLISTS:
out.table = "audio_playlists";
where = "audio_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_MEDIA_ID_PLAYLISTS_ID:
out.table = "audio_playlists";
where = "audio_id=" + uri.getPathSegments().get(3) +
" AND playlists_id=" + uri.getPathSegments().get(5);
break;
case AUDIO_GENRES:
out.table = "audio_genres";
break;
case AUDIO_GENRES_ID:
out.table = "audio_genres";
where = "_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_GENRES_ID_MEMBERS:
out.table = "audio_genres";
where = "genre_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_GENRES_ID_MEMBERS_ID:
out.table = "audio_genres";
where = "genre_id=" + uri.getPathSegments().get(3) +
" AND audio_id =" + uri.getPathSegments().get(5);
break;
case AUDIO_PLAYLISTS:
out.table = "files";
where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_PLAYLIST;
break;
case AUDIO_PLAYLISTS_ID:
out.table = "files";
where = "_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_PLAYLISTS_ID_MEMBERS:
out.table = "audio_playlists_map";
where = "playlist_id=" + uri.getPathSegments().get(3);
break;
case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
out.table = "audio_playlists_map";
where = "playlist_id=" + uri.getPathSegments().get(3) +
" AND _id=" + uri.getPathSegments().get(5);
break;
case AUDIO_ALBUMART_ID:
out.table = "album_art";
where = "album_id=" + uri.getPathSegments().get(3);
break;
case VIDEO_MEDIA:
out.table = "files";
where = FileColumns.MEDIA_TYPE + "=" + FileColumns.MEDIA_TYPE_VIDEO;
break;
case VIDEO_MEDIA_ID:
out.table = "files";
where = "_id=" + uri.getPathSegments().get(3);
break;
case VIDEO_THUMBNAILS_ID:
where = "_id=" + uri.getPathSegments().get(3);
case VIDEO_THUMBNAILS:
out.table = "videothumbnails";
break;
case FILES_ID:
case MTP_OBJECTS_ID:
where = "_id=" + uri.getPathSegments().get(2);
case FILES:
case MTP_OBJECTS:
out.table = "files";
break;
default:
throw new UnsupportedOperationException(
"Unknown or unsupported URL: " + uri.toString());
}
// Add in the user requested WHERE clause, if needed
if (!TextUtils.isEmpty(userWhere)) {
if (!TextUtils.isEmpty(where)) {
out.where = where + " AND (" + userWhere + ")";
} else {
out.where = userWhere;
}
} else {
out.where = where;
}
}
@Override
public int delete(Uri uri, String userWhere, String[] whereArgs) {
int count;
int match = URI_MATCHER.match(uri);
// handle MEDIA_SCANNER before calling getDatabaseForUri()
if (match == MEDIA_SCANNER) {
if (mMediaScannerVolume == null) {
return 0;
}
mMediaScannerVolume = null;
return 1;
}
if (match != VOLUMES_ID) {
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null) {
throw new UnsupportedOperationException(
"Unknown URI: " + uri);
}
SQLiteDatabase db = database.getWritableDatabase();
synchronized (sGetTableAndWhereParam) {
getTableAndWhere(uri, match, userWhere, sGetTableAndWhereParam);
switch (match) {
case MTP_OBJECTS:
case MTP_OBJECTS_ID:
try {
// don't send objectRemoved event since this originated from MTP
mDisableMtpObjectCallbacks = true;
count = db.delete("files", sGetTableAndWhereParam.where, whereArgs);
} finally {
mDisableMtpObjectCallbacks = false;
}
break;
default:
count = db.delete(sGetTableAndWhereParam.table,
sGetTableAndWhereParam.where, whereArgs);
break;
}
getContext().getContentResolver().notifyChange(uri, null);
}
} else {
detachVolume(uri);
count = 1;
}
return count;
}
@Override
public int update(Uri uri, ContentValues initialValues, String userWhere,
String[] whereArgs) {
initialValues = fixExternalStoragePath(initialValues);
int count;
// Log.v(TAG, "update for uri="+uri+", initValues="+initialValues);
int match = URI_MATCHER.match(uri);
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null) {
throw new UnsupportedOperationException(
"Unknown URI: " + uri);
}
SQLiteDatabase db = database.getWritableDatabase();
synchronized (sGetTableAndWhereParam) {
getTableAndWhere(uri, match, userWhere, sGetTableAndWhereParam);
switch (match) {
case AUDIO_MEDIA:
case AUDIO_MEDIA_ID:
{
ContentValues values = new ContentValues(initialValues);
// Insert the artist into the artist table and remove it from
// the input values
String artist = values.getAsString("artist");
values.remove("artist");
if (artist != null) {
long artistRowId;
HashMap<String, Long> artistCache = database.mArtistCache;
synchronized(artistCache) {
Long temp = artistCache.get(artist);
if (temp == null) {
artistRowId = getKeyIdForName(db, "artists", "artist_key", "artist",
artist, artist, null, 0, null, artistCache, uri);
} else {
artistRowId = temp.longValue();
}
}
values.put("artist_id", Integer.toString((int)artistRowId));
}
// Do the same for the album field.
String so = values.getAsString("album");
values.remove("album");
if (so != null) {
String path = values.getAsString("_data");
int albumHash = 0;
if (path == null) {
// If the path is null, we don't have a hash for the file in question.
Log.w(TAG, "Update without specified path.");
} else {
path = fixExternalStoragePath(path);
albumHash = path.substring(0, path.lastIndexOf('/')).hashCode();
}
String s = so.toString();
long albumRowId;
HashMap<String, Long> albumCache = database.mAlbumCache;
synchronized(albumCache) {
String cacheName = s + albumHash;
Long temp = albumCache.get(cacheName);
if (temp == null) {
albumRowId = getKeyIdForName(db, "albums", "album_key", "album",
s, cacheName, path, albumHash, artist, albumCache, uri);
} else {
albumRowId = temp.longValue();
}
}
values.put("album_id", Integer.toString((int)albumRowId));
}
// don't allow the title_key field to be updated directly
values.remove("title_key");
// If the title field is modified, update the title_key
so = values.getAsString("title");
if (so != null) {
String s = so.toString();
values.put("title_key", MediaStore.Audio.keyFor(s));
// do a final trim of the title, in case it started with the special
// "sort first" character (ascii \001)
values.remove("title");
values.put("title", s.trim());
}
count = db.update(sGetTableAndWhereParam.table, values,
sGetTableAndWhereParam.where, whereArgs);
}
break;
case IMAGES_MEDIA:
case IMAGES_MEDIA_ID:
case VIDEO_MEDIA:
case VIDEO_MEDIA_ID:
{
ContentValues values = new ContentValues(initialValues);
// Don't allow bucket id or display name to be updated directly.
// The same names are used for both images and table columns, so
// we use the ImageColumns constants here.
values.remove(ImageColumns.BUCKET_ID);
values.remove(ImageColumns.BUCKET_DISPLAY_NAME);
// If the data is being modified update the bucket values
String data = values.getAsString(MediaColumns.DATA);
if (data != null) {
computeBucketValues(data, values);
}
computeTakenTime(values);
count = db.update(sGetTableAndWhereParam.table, values,
sGetTableAndWhereParam.where, whereArgs);
// if this is a request from MediaScanner, DATA should contains file path
// we only process update request from media scanner, otherwise the requests
// could be duplicate.
if (count > 0 && values.getAsString(MediaStore.MediaColumns.DATA) != null) {
Cursor c = db.query(sGetTableAndWhereParam.table,
READY_FLAG_PROJECTION, sGetTableAndWhereParam.where,
whereArgs, null, null, null);
if (c != null) {
try {
while (c.moveToNext()) {
long magic = c.getLong(2);
if (magic == 0) {
requestMediaThumbnail(c.getString(1), uri,
MediaThumbRequest.PRIORITY_NORMAL, 0);
}
}
} finally {
c.close();
}
}
}
}
break;
case AUDIO_PLAYLISTS_ID_MEMBERS_ID:
String moveit = uri.getQueryParameter("move");
if (moveit != null) {
String key = MediaStore.Audio.Playlists.Members.PLAY_ORDER;
if (initialValues.containsKey(key)) {
int newpos = initialValues.getAsInteger(key);
List <String> segments = uri.getPathSegments();
long playlist = Long.valueOf(segments.get(3));
int oldpos = Integer.valueOf(segments.get(5));
return movePlaylistEntry(db, playlist, oldpos, newpos);
}
throw new IllegalArgumentException("Need to specify " + key +
" when using 'move' parameter");
}
// fall through
default:
count = db.update(sGetTableAndWhereParam.table, initialValues,
sGetTableAndWhereParam.where, whereArgs);
break;
}
}
// in a transaction, the code that began the transaction should be taking
// care of notifications once it ends the transaction successfully
if (count > 0 && !db.inTransaction()) {
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
private int movePlaylistEntry(SQLiteDatabase db, long playlist, int from, int to) {
if (from == to) {
return 0;
}
db.beginTransaction();
try {
int numlines = 0;
db.execSQL("UPDATE audio_playlists_map SET play_order=-1" +
" WHERE play_order=" + from +
" AND playlist_id=" + playlist);
// We could just run both of the next two statements, but only one of
// of them will actually do anything, so might as well skip the compile
// and execute steps.
if (from < to) {
db.execSQL("UPDATE audio_playlists_map SET play_order=play_order-1" +
" WHERE play_order<=" + to + " AND play_order>" + from +
" AND playlist_id=" + playlist);
numlines = to - from + 1;
} else {
db.execSQL("UPDATE audio_playlists_map SET play_order=play_order+1" +
" WHERE play_order>=" + to + " AND play_order<" + from +
" AND playlist_id=" + playlist);
numlines = from - to + 1;
}
db.execSQL("UPDATE audio_playlists_map SET play_order=" + to +
" WHERE play_order=-1 AND playlist_id=" + playlist);
db.setTransactionSuccessful();
Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI
.buildUpon().appendEncodedPath(String.valueOf(playlist)).build();
getContext().getContentResolver().notifyChange(uri, null);
return numlines;
} finally {
db.endTransaction();
}
}
private static final String[] openFileColumns = new String[] {
MediaStore.MediaColumns.DATA,
};
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
ParcelFileDescriptor pfd = null;
if (URI_MATCHER.match(uri) == AUDIO_ALBUMART_FILE_ID) {
// get album art for the specified media file
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null) {
throw new IllegalStateException("Couldn't open database for " + uri);
}
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
int songid = Integer.parseInt(uri.getPathSegments().get(3));
qb.setTables("audio_meta");
qb.appendWhere("_id=" + songid);
Cursor c = qb.query(db,
new String [] {
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID },
null, null, null, null, null);
if (c.moveToFirst()) {
String audiopath = c.getString(0);
int albumid = c.getInt(1);
// Try to get existing album art for this album first, which
// could possibly have been obtained from a different file.
// If that fails, try to get it from this specific file.
Uri newUri = ContentUris.withAppendedId(ALBUMART_URI, albumid);
try {
pfd = openFile(newUri, mode); // recursive call
} catch (FileNotFoundException ex) {
// That didn't work, now try to get it from the specific file
pfd = getThumb(db, audiopath, albumid, null);
}
}
c.close();
return pfd;
}
try {
pfd = openFileHelper(uri, mode);
} catch (FileNotFoundException ex) {
if (mode.contains("w")) {
// if the file couldn't be created, we shouldn't extract album art
throw ex;
}
if (URI_MATCHER.match(uri) == AUDIO_ALBUMART_ID) {
// Tried to open an album art file which does not exist. Regenerate.
DatabaseHelper database = getDatabaseForUri(uri);
if (database == null) {
throw ex;
}
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
int albumid = Integer.parseInt(uri.getPathSegments().get(3));
qb.setTables("audio_meta");
qb.appendWhere("album_id=" + albumid);
Cursor c = qb.query(db,
new String [] {
MediaStore.Audio.Media.DATA },
null, null, null, null, MediaStore.Audio.Media.TRACK);
if (c.moveToFirst()) {
String audiopath = c.getString(0);
pfd = getThumb(db, audiopath, albumid, uri);
}
c.close();
}
if (pfd == null) {
throw ex;
}
}
return pfd;
}
private class ThumbData {
SQLiteDatabase db;
String path;
long album_id;
Uri albumart_uri;
}
private void makeThumbAsync(SQLiteDatabase db, String path, long album_id) {
synchronized (mPendingThumbs) {
if (mPendingThumbs.contains(path)) {
// There's already a request to make an album art thumbnail
// for this audio file in the queue.
return;
}
mPendingThumbs.add(path);
}
ThumbData d = new ThumbData();
d.db = db;
d.path = path;
d.album_id = album_id;
d.albumart_uri = ContentUris.withAppendedId(mAlbumArtBaseUri, album_id);
// Instead of processing thumbnail requests in the order they were
// received we instead process them stack-based, i.e. LIFO.
// The idea behind this is that the most recently requested thumbnails
// are most likely the ones still in the user's view, whereas those
// requested earlier may have already scrolled off.
synchronized (mThumbRequestStack) {
mThumbRequestStack.push(d);
}
// Trigger the handler.
Message msg = mThumbHandler.obtainMessage(ALBUM_THUMB);
msg.sendToTarget();
}
// Extract compressed image data from the audio file itself or, if that fails,
// look for a file "AlbumArt.jpg" in the containing directory.
private static byte[] getCompressedAlbumArt(Context context, String path) {
byte[] compressed = null;
try {
path = fixExternalStoragePath(path);
File f = new File(path);
ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_ONLY);
MediaScanner scanner = new MediaScanner(context);
compressed = scanner.extractAlbumArt(pfd.getFileDescriptor());
pfd.close();
// If no embedded art exists, look for a suitable image file in the
// same directory as the media file, except if that directory is
// is the root directory of the sd card or the download directory.
// We look for, in order of preference:
// 0 AlbumArt.jpg
// 1 AlbumArt*Large.jpg
// 2 Any other jpg image with 'albumart' anywhere in the name
// 3 Any other jpg image
// 4 any other png image
if (compressed == null && path != null) {
int lastSlash = path.lastIndexOf('/');
if (lastSlash > 0) {
String artPath = path.substring(0, lastSlash);
String sdroot = mExternalStoragePath;
String dwndir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String bestmatch = null;
synchronized (sFolderArtMap) {
if (sFolderArtMap.containsKey(artPath)) {
bestmatch = sFolderArtMap.get(artPath);
} else if (!artPath.equalsIgnoreCase(sdroot) &&
!artPath.equalsIgnoreCase(dwndir)) {
File dir = new File(artPath);
String [] entrynames = dir.list();
if (entrynames == null) {
return null;
}
bestmatch = null;
int matchlevel = 1000;
for (int i = entrynames.length - 1; i >=0; i--) {
String entry = entrynames[i].toLowerCase();
if (entry.equals("albumart.jpg")) {
bestmatch = entrynames[i];
break;
} else if (entry.startsWith("albumart")
&& entry.endsWith("large.jpg")
&& matchlevel > 1) {
bestmatch = entrynames[i];
matchlevel = 1;
} else if (entry.contains("albumart")
&& entry.endsWith(".jpg")
&& matchlevel > 2) {
bestmatch = entrynames[i];
matchlevel = 2;
} else if (entry.endsWith(".jpg") && matchlevel > 3) {
bestmatch = entrynames[i];
matchlevel = 3;
} else if (entry.endsWith(".png") && matchlevel > 4) {
bestmatch = entrynames[i];
matchlevel = 4;
}
}
// note that this may insert null if no album art was found
sFolderArtMap.put(artPath, bestmatch);
}
}
if (bestmatch != null) {
File file = new File(artPath, bestmatch);
if (file.exists()) {
compressed = new byte[(int)file.length()];
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
stream.read(compressed);
} catch (IOException ex) {
compressed = null;
} finally {
if (stream != null) {
stream.close();
}
}
}
}
}
}
} catch (IOException e) {
}
return compressed;
}
// Return a URI to write the album art to and update the database as necessary.
Uri getAlbumArtOutputUri(SQLiteDatabase db, long album_id, Uri albumart_uri) {
Uri out = null;
// TODO: this could be done more efficiently with a call to db.replace(), which
// replaces or inserts as needed, making it unnecessary to query() first.
if (albumart_uri != null) {
Cursor c = query(albumart_uri, new String [] { "_data" },
null, null, null);
if (c.moveToFirst()) {
String albumart_path = c.getString(0);
if (ensureFileExists(albumart_path)) {
out = albumart_uri;
}
} else {
albumart_uri = null;
}
c.close();
}
if (albumart_uri == null){
ContentValues initialValues = new ContentValues();
initialValues.put("album_id", album_id);
try {
ContentValues values = ensureFile(false, initialValues, "", ALBUM_THUMB_FOLDER);
long rowId = db.insert("album_art", "_data", values);
if (rowId > 0) {
out = ContentUris.withAppendedId(ALBUMART_URI, rowId);
}
} catch (IllegalStateException ex) {
Log.e(TAG, "error creating album thumb file");
}
}
return out;
}
// Write out the album art to the output URI, recompresses the given Bitmap
// if necessary, otherwise writes the compressed data.
private void writeAlbumArt(
boolean need_to_recompress, Uri out, byte[] compressed, Bitmap bm) {
boolean success = false;
try {
OutputStream outstream = getContext().getContentResolver().openOutputStream(out);
if (!need_to_recompress) {
// No need to recompress here, just write out the original
// compressed data here.
outstream.write(compressed);
success = true;
} else {
success = bm.compress(Bitmap.CompressFormat.JPEG, 75, outstream);
}
outstream.close();
} catch (FileNotFoundException ex) {
Log.e(TAG, "error creating file", ex);
} catch (IOException ex) {
Log.e(TAG, "error creating file", ex);
}
if (!success) {
// the thumbnail was not written successfully, delete the entry that refers to it
getContext().getContentResolver().delete(out, null, null);
}
}
private ParcelFileDescriptor getThumb(SQLiteDatabase db, String path, long album_id,
Uri albumart_uri) {
ThumbData d = new ThumbData();
d.db = db;
d.path = path;
d.album_id = album_id;
d.albumart_uri = albumart_uri;
return makeThumbInternal(d);
}
private ParcelFileDescriptor makeThumbInternal(ThumbData d) {
byte[] compressed = getCompressedAlbumArt(getContext(), d.path);
if (compressed == null) {
return null;
}
Bitmap bm = null;
boolean need_to_recompress = true;
try {
// get the size of the bitmap
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inSampleSize = 1;
BitmapFactory.decodeByteArray(compressed, 0, compressed.length, opts);
// request a reasonably sized output image
// TODO: don't hardcode the size
while (opts.outHeight > 320 || opts.outWidth > 320) {
opts.outHeight /= 2;
opts.outWidth /= 2;
opts.inSampleSize *= 2;
}
if (opts.inSampleSize == 1) {
// The original album art was of proper size, we won't have to
// recompress the bitmap later.
need_to_recompress = false;
} else {
// get the image for real now
opts.inJustDecodeBounds = false;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
bm = BitmapFactory.decodeByteArray(compressed, 0, compressed.length, opts);
if (bm != null && bm.getConfig() == null) {
Bitmap nbm = bm.copy(Bitmap.Config.RGB_565, false);
if (nbm != null && nbm != bm) {
bm.recycle();
bm = nbm;
}
}
}
} catch (Exception e) {
}
if (need_to_recompress && bm == null) {
return null;
}
if (d.albumart_uri == null) {
// this one doesn't need to be saved (probably a song with an unknown album),
// so stick it in a memory file and return that
try {
return ParcelFileDescriptor.fromData(compressed, "albumthumb");
} catch (IOException e) {
}
} else {
// This one needs to actually be saved on the sd card.
// This is wrapped in a transaction because there are various things
// that could go wrong while generating the thumbnail, and we only want
// to update the database when all steps succeeded.
d.db.beginTransaction();
try {
Uri out = getAlbumArtOutputUri(d.db, d.album_id, d.albumart_uri);
if (out != null) {
writeAlbumArt(need_to_recompress, out, compressed, bm);
getContext().getContentResolver().notifyChange(MEDIA_URI, null);
ParcelFileDescriptor pfd = openFileHelper(out, "r");
d.db.setTransactionSuccessful();
return pfd;
}
} catch (FileNotFoundException ex) {
// do nothing, just return null below
} catch (UnsupportedOperationException ex) {
// do nothing, just return null below
} finally {
d.db.endTransaction();
if (bm != null) {
bm.recycle();
}
}
}
return null;
}
/**
* Look up the artist or album entry for the given name, creating that entry
* if it does not already exists.
* @param db The database
* @param table The table to store the key/name pair in.
* @param keyField The name of the key-column
* @param nameField The name of the name-column
* @param rawName The name that the calling app was trying to insert into the database
* @param cacheName The string that will be inserted in to the cache
* @param path The full path to the file being inserted in to the audio table
* @param albumHash A hash to distinguish between different albums of the same name
* @param artist The name of the artist, if known
* @param cache The cache to add this entry to
* @param srcuri The Uri that prompted the call to this method, used for determining whether this is
* the internal or external database
* @return The row ID for this artist/album, or -1 if the provided name was invalid
*/
private long getKeyIdForName(SQLiteDatabase db, String table, String keyField, String nameField,
String rawName, String cacheName, String path, int albumHash,
String artist, HashMap<String, Long> cache, Uri srcuri) {
long rowId;
if (rawName == null || rawName.length() == 0) {
return -1;
}
String k = MediaStore.Audio.keyFor(rawName);
if (k == null) {
return -1;
}
boolean isAlbum = table.equals("albums");
boolean isUnknown = MediaStore.UNKNOWN_STRING.equals(rawName);
// To distinguish same-named albums, we append a hash of the path.
// Ideally we would also take things like CDDB ID in to account, so
// we can group files from the same album that aren't in the same
// folder, but this is a quick and easy start that works immediately
// without requiring support from the mp3, mp4 and Ogg meta data
// readers, as long as the albums are in different folders.
if (isAlbum) {
k = k + albumHash;
if (isUnknown) {
k = k + artist;
}
}
String [] selargs = { k };
Cursor c = db.query(table, null, keyField + "=?", selargs, null, null, null);
try {
switch (c.getCount()) {
case 0: {
// insert new entry into table
ContentValues otherValues = new ContentValues();
otherValues.put(keyField, k);
otherValues.put(nameField, rawName);
rowId = db.insert(table, "duration", otherValues);
if (path != null && isAlbum && ! isUnknown) {
// We just inserted a new album. Now create an album art thumbnail for it.
makeThumbAsync(db, path, rowId);
}
if (rowId > 0) {
String volume = srcuri.toString().substring(16, 24); // extract internal/external
Uri uri = Uri.parse("content://media/" + volume + "/audio/" + table + "/" + rowId);
getContext().getContentResolver().notifyChange(uri, null);
}
}
break;
case 1: {
// Use the existing entry
c.moveToFirst();
rowId = c.getLong(0);
// Determine whether the current rawName is better than what's
// currently stored in the table, and update the table if it is.
String currentFancyName = c.getString(2);
String bestName = makeBestName(rawName, currentFancyName);
if (!bestName.equals(currentFancyName)) {
// update the table with the new name
ContentValues newValues = new ContentValues();
newValues.put(nameField, bestName);
db.update(table, newValues, "rowid="+Integer.toString((int)rowId), null);
String volume = srcuri.toString().substring(16, 24); // extract internal/external
Uri uri = Uri.parse("content://media/" + volume + "/audio/" + table + "/" + rowId);
getContext().getContentResolver().notifyChange(uri, null);
}
}
break;
default:
// corrupt database
Log.e(TAG, "Multiple entries in table " + table + " for key " + k);
rowId = -1;
break;
}
} finally {
if (c != null) c.close();
}
if (cache != null && ! isUnknown) {
cache.put(cacheName, rowId);
}
return rowId;
}
/**
* Returns the best string to use for display, given two names.
* Note that this function does not necessarily return either one
* of the provided names; it may decide to return a better alternative
* (for example, specifying the inputs "Police" and "Police, The" will
* return "The Police")
*
* The basic assumptions are:
* - longer is better ("The police" is better than "Police")
* - prefix is better ("The Police" is better than "Police, The")
* - accents are better ("Motörhead" is better than "Motorhead")
*
* @param one The first of the two names to consider
* @param two The last of the two names to consider
* @return The actual name to use
*/
String makeBestName(String one, String two) {
String name;
// Longer names are usually better.
if (one.length() > two.length()) {
name = one;
} else {
// Names with accents are usually better, and conveniently sort later
if (one.toLowerCase().compareTo(two.toLowerCase()) > 0) {
name = one;
} else {
name = two;
}
}
// Prefixes are better than postfixes.
if (name.endsWith(", the") || name.endsWith(",the") ||
name.endsWith(", an") || name.endsWith(",an") ||
name.endsWith(", a") || name.endsWith(",a")) {
String fix = name.substring(1 + name.lastIndexOf(','));
name = fix.trim() + " " + name.substring(0, name.lastIndexOf(','));
}
// TODO: word-capitalize the resulting name
return name;
}
/**
* Looks up the database based on the given URI.
*
* @param uri The requested URI
* @returns the database for the given URI
*/
private DatabaseHelper getDatabaseForUri(Uri uri) {
synchronized (mDatabases) {
if (uri.getPathSegments().size() > 1) {
return mDatabases.get(uri.getPathSegments().get(0));
}
}
return null;
}
/**
* Attach the database for a volume (internal or external).
* Does nothing if the volume is already attached, otherwise
* checks the volume ID and sets up the corresponding database.
*
* @param volume to attach, either {@link #INTERNAL_VOLUME} or {@link #EXTERNAL_VOLUME}.
* @return the content URI of the attached volume.
*/
private Uri attachVolume(String volume) {
if (Process.supportsProcesses() && Binder.getCallingPid() != Process.myPid()) {
throw new SecurityException(
"Opening and closing databases not allowed.");
}
synchronized (mDatabases) {
if (mDatabases.get(volume) != null) { // Already attached
return Uri.parse("content://media/" + volume);
}
DatabaseHelper db;
if (INTERNAL_VOLUME.equals(volume)) {
db = new DatabaseHelper(getContext(), INTERNAL_DATABASE_NAME, true);
} else if (EXTERNAL_VOLUME.equals(volume)) {
String path = mExternalStoragePath;
int volumeID = FileUtils.getFatVolumeId(path);
if (LOCAL_LOGV) Log.v(TAG, path + " volume ID: " + volumeID);
// generate database name based on volume ID
String dbName = "external-" + Integer.toHexString(volumeID) + ".db";
db = new DatabaseHelper(getContext(), dbName, false);
mVolumeId = volumeID;
} else {
throw new IllegalArgumentException("There is no volume named " + volume);
}
mDatabases.put(volume, db);
if (!db.mInternal) {
// clean up stray album art files: delete every file not in the database
File[] files = new File(mExternalStoragePath, ALBUM_THUMB_FOLDER).listFiles();
HashSet<String> fileSet = new HashSet();
for (int i = 0; files != null && i < files.length; i++) {
fileSet.add(files[i].getPath());
}
Cursor cursor = query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Albums.ALBUM_ART }, null, null, null);
try {
while (cursor != null && cursor.moveToNext()) {
fileSet.remove(cursor.getString(0));
}
} finally {
if (cursor != null) cursor.close();
}
Iterator<String> iterator = fileSet.iterator();
while (iterator.hasNext()) {
String filename = iterator.next();
if (LOCAL_LOGV) Log.v(TAG, "deleting obsolete album art " + filename);
new File(filename).delete();
}
}
}
if (LOCAL_LOGV) Log.v(TAG, "Attached volume: " + volume);
return Uri.parse("content://media/" + volume);
}
/**
* Detach the database for a volume (must be external).
* Does nothing if the volume is already detached, otherwise
* closes the database and sends a notification to listeners.
*
* @param uri The content URI of the volume, as returned by {@link #attachVolume}
*/
private void detachVolume(Uri uri) {
if (Process.supportsProcesses() && Binder.getCallingPid() != Process.myPid()) {
throw new SecurityException(
"Opening and closing databases not allowed.");
}
String volume = uri.getPathSegments().get(0);
if (INTERNAL_VOLUME.equals(volume)) {
throw new UnsupportedOperationException(
"Deleting the internal volume is not allowed");
} else if (!EXTERNAL_VOLUME.equals(volume)) {
throw new IllegalArgumentException(
"There is no volume named " + volume);
}
synchronized (mDatabases) {
DatabaseHelper database = mDatabases.get(volume);
if (database == null) return;
try {
// touch the database file to show it is most recently used
File file = new File(database.getReadableDatabase().getPath());
file.setLastModified(System.currentTimeMillis());
} catch (SQLException e) {
Log.e(TAG, "Can't touch database file", e);
}
mDatabases.remove(volume);
database.close();
}
getContext().getContentResolver().notifyChange(uri, null);
if (LOCAL_LOGV) Log.v(TAG, "Detached volume: " + volume);
}
private static String TAG = "MediaProvider";
private static final boolean LOCAL_LOGV = false;
private static final int DATABASE_VERSION = 100;
private static final String INTERNAL_DATABASE_NAME = "internal.db";
// maximum number of cached external databases to keep
private static final int MAX_EXTERNAL_DATABASES = 3;
// Delete databases that have not been used in two months
// 60 days in milliseconds (1000 * 60 * 60 * 24 * 60)
private static final long OBSOLETE_DATABASE_DB = 5184000000L;
private HashMap<String, DatabaseHelper> mDatabases;
private Handler mThumbHandler;
// name of the volume currently being scanned by the media scanner (or null)
private String mMediaScannerVolume;
// current FAT volume ID
private int mVolumeId;
static final String INTERNAL_VOLUME = "internal";
static final String EXTERNAL_VOLUME = "external";
static final String ALBUM_THUMB_FOLDER = "Android/data/com.android.providers.media/albumthumbs";
// path for writing contents of in memory temp database
private String mTempDatabasePath;
// WARNING: the values of IMAGES_MEDIA, AUDIO_MEDIA, and VIDEO_MEDIA and AUDIO_PLAYLISTS
// are stored in the "files" table, so do not renumber them unless you also add
// a corresponding database upgrade step for it.
private static final int IMAGES_MEDIA = 1;
private static final int IMAGES_MEDIA_ID = 2;
private static final int IMAGES_THUMBNAILS = 3;
private static final int IMAGES_THUMBNAILS_ID = 4;
private static final int AUDIO_MEDIA = 100;
private static final int AUDIO_MEDIA_ID = 101;
private static final int AUDIO_MEDIA_ID_GENRES = 102;
private static final int AUDIO_MEDIA_ID_GENRES_ID = 103;
private static final int AUDIO_MEDIA_ID_PLAYLISTS = 104;
private static final int AUDIO_MEDIA_ID_PLAYLISTS_ID = 105;
private static final int AUDIO_GENRES = 106;
private static final int AUDIO_GENRES_ID = 107;
private static final int AUDIO_GENRES_ID_MEMBERS = 108;
private static final int AUDIO_GENRES_ID_MEMBERS_ID = 109;
private static final int AUDIO_PLAYLISTS = 110;
private static final int AUDIO_PLAYLISTS_ID = 111;
private static final int AUDIO_PLAYLISTS_ID_MEMBERS = 112;
private static final int AUDIO_PLAYLISTS_ID_MEMBERS_ID = 113;
private static final int AUDIO_ARTISTS = 114;
private static final int AUDIO_ARTISTS_ID = 115;
private static final int AUDIO_ALBUMS = 116;
private static final int AUDIO_ALBUMS_ID = 117;
private static final int AUDIO_ARTISTS_ID_ALBUMS = 118;
private static final int AUDIO_ALBUMART = 119;
private static final int AUDIO_ALBUMART_ID = 120;
private static final int AUDIO_ALBUMART_FILE_ID = 121;
private static final int VIDEO_MEDIA = 200;
private static final int VIDEO_MEDIA_ID = 201;
private static final int VIDEO_THUMBNAILS = 202;
private static final int VIDEO_THUMBNAILS_ID = 203;
private static final int VOLUMES = 300;
private static final int VOLUMES_ID = 301;
private static final int AUDIO_SEARCH_LEGACY = 400;
private static final int AUDIO_SEARCH_BASIC = 401;
private static final int AUDIO_SEARCH_FANCY = 402;
private static final int MEDIA_SCANNER = 500;
private static final int FS_ID = 600;
private static final int FILES = 700;
private static final int FILES_ID = 701;
// Used only by the MTP implementation
private static final int MTP_OBJECTS = 702;
private static final int MTP_OBJECTS_ID = 703;
private static final int MTP_OBJECT_REFERENCES = 704;
private static final UriMatcher URI_MATCHER =
new UriMatcher(UriMatcher.NO_MATCH);
private static final String[] ID_PROJECTION = new String[] {
MediaStore.MediaColumns._ID
};
private static final String[] MIME_TYPE_PROJECTION = new String[] {
MediaStore.MediaColumns._ID, // 0
MediaStore.MediaColumns.MIME_TYPE, // 1
};
private static final String[] READY_FLAG_PROJECTION = new String[] {
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.DATA,
Images.Media.MINI_THUMB_MAGIC
};
private static final String OBJECT_REFERENCES_QUERY =
"SELECT " + Audio.Playlists.Members.AUDIO_ID + " FROM audio_playlists_map"
+ " WHERE " + Audio.Playlists.Members.PLAYLIST_ID + "=?"
+ " ORDER BY " + Audio.Playlists.Members.PLAY_ORDER;
static
{
URI_MATCHER.addURI("media", "*/images/media", IMAGES_MEDIA);
URI_MATCHER.addURI("media", "*/images/media/#", IMAGES_MEDIA_ID);
URI_MATCHER.addURI("media", "*/images/thumbnails", IMAGES_THUMBNAILS);
URI_MATCHER.addURI("media", "*/images/thumbnails/#", IMAGES_THUMBNAILS_ID);
URI_MATCHER.addURI("media", "*/audio/media", AUDIO_MEDIA);
URI_MATCHER.addURI("media", "*/audio/media/#", AUDIO_MEDIA_ID);
URI_MATCHER.addURI("media", "*/audio/media/#/genres", AUDIO_MEDIA_ID_GENRES);
URI_MATCHER.addURI("media", "*/audio/media/#/genres/#", AUDIO_MEDIA_ID_GENRES_ID);
URI_MATCHER.addURI("media", "*/audio/media/#/playlists", AUDIO_MEDIA_ID_PLAYLISTS);
URI_MATCHER.addURI("media", "*/audio/media/#/playlists/#", AUDIO_MEDIA_ID_PLAYLISTS_ID);
URI_MATCHER.addURI("media", "*/audio/genres", AUDIO_GENRES);
URI_MATCHER.addURI("media", "*/audio/genres/#", AUDIO_GENRES_ID);
URI_MATCHER.addURI("media", "*/audio/genres/#/members", AUDIO_GENRES_ID_MEMBERS);
URI_MATCHER.addURI("media", "*/audio/genres/#/members/#", AUDIO_GENRES_ID_MEMBERS_ID);
URI_MATCHER.addURI("media", "*/audio/playlists", AUDIO_PLAYLISTS);
URI_MATCHER.addURI("media", "*/audio/playlists/#", AUDIO_PLAYLISTS_ID);
URI_MATCHER.addURI("media", "*/audio/playlists/#/members", AUDIO_PLAYLISTS_ID_MEMBERS);
URI_MATCHER.addURI("media", "*/audio/playlists/#/members/#", AUDIO_PLAYLISTS_ID_MEMBERS_ID);
URI_MATCHER.addURI("media", "*/audio/artists", AUDIO_ARTISTS);
URI_MATCHER.addURI("media", "*/audio/artists/#", AUDIO_ARTISTS_ID);
URI_MATCHER.addURI("media", "*/audio/artists/#/albums", AUDIO_ARTISTS_ID_ALBUMS);
URI_MATCHER.addURI("media", "*/audio/albums", AUDIO_ALBUMS);
URI_MATCHER.addURI("media", "*/audio/albums/#", AUDIO_ALBUMS_ID);
URI_MATCHER.addURI("media", "*/audio/albumart", AUDIO_ALBUMART);
URI_MATCHER.addURI("media", "*/audio/albumart/#", AUDIO_ALBUMART_ID);
URI_MATCHER.addURI("media", "*/audio/media/#/albumart", AUDIO_ALBUMART_FILE_ID);
URI_MATCHER.addURI("media", "*/video/media", VIDEO_MEDIA);
URI_MATCHER.addURI("media", "*/video/media/#", VIDEO_MEDIA_ID);
URI_MATCHER.addURI("media", "*/video/thumbnails", VIDEO_THUMBNAILS);
URI_MATCHER.addURI("media", "*/video/thumbnails/#", VIDEO_THUMBNAILS_ID);
URI_MATCHER.addURI("media", "*/media_scanner", MEDIA_SCANNER);
URI_MATCHER.addURI("media", "*/fs_id", FS_ID);
URI_MATCHER.addURI("media", "*", VOLUMES_ID);
URI_MATCHER.addURI("media", null, VOLUMES);
// Used by MTP implementation
URI_MATCHER.addURI("media", "*/file", FILES);
URI_MATCHER.addURI("media", "*/file/#", FILES_ID);
URI_MATCHER.addURI("media", "*/object", MTP_OBJECTS);
URI_MATCHER.addURI("media", "*/object/#", MTP_OBJECTS_ID);
URI_MATCHER.addURI("media", "*/object/#/references", MTP_OBJECT_REFERENCES);
/**
* @deprecated use the 'basic' or 'fancy' search Uris instead
*/
URI_MATCHER.addURI("media", "*/audio/" + SearchManager.SUGGEST_URI_PATH_QUERY,
AUDIO_SEARCH_LEGACY);
URI_MATCHER.addURI("media", "*/audio/" + SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
AUDIO_SEARCH_LEGACY);
// used for search suggestions
URI_MATCHER.addURI("media", "*/audio/search/" + SearchManager.SUGGEST_URI_PATH_QUERY,
AUDIO_SEARCH_BASIC);
URI_MATCHER.addURI("media", "*/audio/search/" + SearchManager.SUGGEST_URI_PATH_QUERY +
"/*", AUDIO_SEARCH_BASIC);
// used by the music app's search activity
URI_MATCHER.addURI("media", "*/audio/search/fancy", AUDIO_SEARCH_FANCY);
URI_MATCHER.addURI("media", "*/audio/search/fancy/*", AUDIO_SEARCH_FANCY);
}
}
| true | true | private static void updateDatabase(SQLiteDatabase db, boolean internal,
int fromVersion, int toVersion) {
// sanity checks
if (toVersion != DATABASE_VERSION) {
Log.e(TAG, "Illegal update request. Got " + toVersion + ", expected " +
DATABASE_VERSION);
throw new IllegalArgumentException();
} else if (fromVersion > toVersion) {
Log.e(TAG, "Illegal update request: can't downgrade from " + fromVersion +
" to " + toVersion + ". Did you forget to wipe data?");
throw new IllegalArgumentException();
}
// Revisions 84-86 were a failed attempt at supporting the "album artist" id3 tag.
// We can't downgrade from those revisions, so start over.
// (the initial change to do this was wrong, so now we actually need to start over
// if the database version is 84-89)
// Post-gingerbread, revisions 91-94 were broken in a way that is not easy to repair.
// However version 91 was reused in a divergent development path for gingerbread,
// so we need to support upgrades from 91.
// Therefore we will only force a reset for versions 92 - 94.
if (fromVersion < 63 || (fromVersion >= 84 && fromVersion <= 89) ||
(fromVersion >= 92 && fromVersion <= 94)) {
fromVersion = 63;
// Drop everything and start over.
Log.i(TAG, "Upgrading media database from version " +
fromVersion + " to " + toVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS images");
db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
db.execSQL("DROP TABLE IF EXISTS thumbnails");
db.execSQL("DROP TRIGGER IF EXISTS thumbnails_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_meta");
db.execSQL("DROP TABLE IF EXISTS artists");
db.execSQL("DROP TABLE IF EXISTS albums");
db.execSQL("DROP TABLE IF EXISTS album_art");
db.execSQL("DROP VIEW IF EXISTS artist_info");
db.execSQL("DROP VIEW IF EXISTS album_info");
db.execSQL("DROP VIEW IF EXISTS artists_albums_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_genres");
db.execSQL("DROP TABLE IF EXISTS audio_genres_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_genres_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_playlists");
db.execSQL("DROP TABLE IF EXISTS audio_playlists_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup1");
db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup2");
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
db.execSQL("DROP TABLE IF EXISTS objects");
db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup");
db.execSQL("CREATE TABLE IF NOT EXISTS images (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"_size INTEGER," +
"_display_name TEXT," +
"mime_type TEXT," +
"title TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"description TEXT," +
"picasa_id TEXT," +
"isprivate INTEGER," +
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"orientation INTEGER," +
"mini_thumb_magic INTEGER," +
"bucket_id TEXT," +
"bucket_display_name TEXT" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS mini_thumb_magic_index on images(mini_thumb_magic);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON images " +
"BEGIN " +
"DELETE FROM thumbnails WHERE image_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
// create image thumbnail table
db.execSQL("CREATE TABLE IF NOT EXISTS thumbnails (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"image_id INTEGER," +
"kind INTEGER," +
"width INTEGER," +
"height INTEGER" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS image_id_index on thumbnails(image_id);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS thumbnails_cleanup DELETE ON thumbnails " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
// Contains meta data about audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_meta (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT UNIQUE NOT NULL," +
"_display_name TEXT," +
"_size INTEGER," +
"mime_type TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"title TEXT NOT NULL," +
"title_key TEXT NOT NULL," +
"duration INTEGER," +
"artist_id INTEGER," +
"composer TEXT," +
"album_id INTEGER," +
"track INTEGER," + // track is an integer to allow proper sorting
"year INTEGER CHECK(year!=0)," +
"is_ringtone INTEGER," +
"is_music INTEGER," +
"is_alarm INTEGER," +
"is_notification INTEGER" +
");");
// Contains a sort/group "key" and the preferred display name for artists
db.execSQL("CREATE TABLE IF NOT EXISTS artists (" +
"artist_id INTEGER PRIMARY KEY," +
"artist_key TEXT NOT NULL UNIQUE," +
"artist TEXT NOT NULL" +
");");
// Contains a sort/group "key" and the preferred display name for albums
db.execSQL("CREATE TABLE IF NOT EXISTS albums (" +
"album_id INTEGER PRIMARY KEY," +
"album_key TEXT NOT NULL UNIQUE," +
"album TEXT NOT NULL" +
");");
db.execSQL("CREATE TABLE IF NOT EXISTS album_art (" +
"album_id INTEGER PRIMARY KEY," +
"_data TEXT" +
");");
recreateAudioView(db);
// Provides some extra info about artists, like the number of tracks
// and albums for this artist
db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
"SELECT artist_id AS _id, artist, artist_key, " +
"COUNT(DISTINCT album) AS number_of_albums, " +
"COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
"GROUP BY artist_key;");
// Provides extra info albums, such as the number of tracks
db.execSQL("CREATE VIEW IF NOT EXISTS album_info AS " +
"SELECT audio.album_id AS _id, album, album_key, " +
"MIN(year) AS minyear, " +
"MAX(year) AS maxyear, artist, artist_id, artist_key, " +
"count(*) AS " + MediaStore.Audio.Albums.NUMBER_OF_SONGS +
",album_art._data AS album_art" +
" FROM audio LEFT OUTER JOIN album_art ON audio.album_id=album_art.album_id" +
" WHERE is_music=1 GROUP BY audio.album_id;");
// For a given artist_id, provides the album_id for albums on
// which the artist appears.
db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
"SELECT DISTINCT artist_id, album_id FROM audio_meta;");
/*
* Only external media volumes can handle genres, playlists, etc.
*/
if (!internal) {
// Cleans up when an audio file is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON audio_meta " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
"DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
"END");
// Contains audio genre definitions
db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres (" +
"_id INTEGER PRIMARY KEY," +
"name TEXT NOT NULL" +
");");
// Contiains mappings between audio genres and audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres_map (" +
"_id INTEGER PRIMARY KEY," +
"audio_id INTEGER NOT NULL," +
"genre_id INTEGER NOT NULL" +
");");
// Cleans up when an audio genre is delete
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_genres_cleanup DELETE ON audio_genres " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE genre_id = old._id;" +
"END");
// Contains audio playlist definitions
db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," + // _data is path for file based playlists, or null
"name TEXT NOT NULL," +
"date_added INTEGER," +
"date_modified INTEGER" +
");");
// Contains mappings between audio playlists and audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists_map (" +
"_id INTEGER PRIMARY KEY," +
"audio_id INTEGER NOT NULL," +
"playlist_id INTEGER NOT NULL," +
"play_order INTEGER NOT NULL" +
");");
// Cleans up when an audio playlist is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON audio_playlists " +
"BEGIN " +
"DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
// Cleans up album_art table entry when an album is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup1 DELETE ON albums " +
"BEGIN " +
"DELETE FROM album_art WHERE album_id = old.album_id;" +
"END");
// Cleans up album_art when an album is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup2 DELETE ON album_art " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
// Contains meta data about video files
db.execSQL("CREATE TABLE IF NOT EXISTS video (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT NOT NULL," +
"_display_name TEXT," +
"_size INTEGER," +
"mime_type TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"title TEXT," +
"duration INTEGER," +
"artist TEXT," +
"album TEXT," +
"resolution TEXT," +
"description TEXT," +
"isprivate INTEGER," + // for YouTube videos
"tags TEXT," + // for YouTube videos
"category TEXT," + // for YouTube videos
"language TEXT," + // for YouTube videos
"mini_thumb_data TEXT," +
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"mini_thumb_magic INTEGER" +
");");
db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON video " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
// At this point the database is at least at schema version 63 (it was
// either created at version 63 by the code above, or was already at
// version 63 or later)
if (fromVersion < 64) {
// create the index that updates the database to schema version 64
db.execSQL("CREATE INDEX IF NOT EXISTS sort_index on images(datetaken ASC, _id ASC);");
}
/*
* Android 1.0 shipped with database version 64
*/
if (fromVersion < 65) {
// create the index that updates the database to schema version 65
db.execSQL("CREATE INDEX IF NOT EXISTS titlekey_index on audio_meta(title_key);");
}
// In version 66, originally we updateBucketNames(db, "images"),
// but we need to do it in version 89 and therefore save the update here.
if (fromVersion < 67) {
// create the indices that update the database to schema version 67
db.execSQL("CREATE INDEX IF NOT EXISTS albumkey_index on albums(album_key);");
db.execSQL("CREATE INDEX IF NOT EXISTS artistkey_index on artists(artist_key);");
}
if (fromVersion < 68) {
// Create bucket_id and bucket_display_name columns for the video table.
db.execSQL("ALTER TABLE video ADD COLUMN bucket_id TEXT;");
db.execSQL("ALTER TABLE video ADD COLUMN bucket_display_name TEXT");
// In version 68, originally we updateBucketNames(db, "video"),
// but we need to do it in version 89 and therefore save the update here.
}
if (fromVersion < 69) {
updateDisplayName(db, "images");
}
if (fromVersion < 70) {
// Create bookmark column for the video table.
db.execSQL("ALTER TABLE video ADD COLUMN bookmark INTEGER;");
}
if (fromVersion < 71) {
// There is no change to the database schema, however a code change
// fixed parsing of metadata for certain files bought from the
// iTunes music store, so we want to rescan files that might need it.
// We do this by clearing the modification date in the database for
// those files, so that the media scanner will see them as updated
// and rescan them.
db.execSQL("UPDATE audio_meta SET date_modified=0 WHERE _id IN (" +
"SELECT _id FROM audio where mime_type='audio/mp4' AND " +
"artist='" + MediaStore.UNKNOWN_STRING + "' AND " +
"album='" + MediaStore.UNKNOWN_STRING + "'" +
");");
}
if (fromVersion < 72) {
// Create is_podcast and bookmark columns for the audio table.
db.execSQL("ALTER TABLE audio_meta ADD COLUMN is_podcast INTEGER;");
db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE _data LIKE '%/podcasts/%';");
db.execSQL("UPDATE audio_meta SET is_music=0 WHERE is_podcast=1" +
" AND _data NOT LIKE '%/music/%';");
db.execSQL("ALTER TABLE audio_meta ADD COLUMN bookmark INTEGER;");
// New columns added to tables aren't visible in views on those tables
// without opening and closing the database (or using the 'vacuum' command,
// which we can't do here because all this code runs inside a transaction).
// To work around this, we drop and recreate the affected view and trigger.
recreateAudioView(db);
}
/*
* Android 1.5 shipped with database version 72
*/
if (fromVersion < 73) {
// There is no change to the database schema, but we now do case insensitive
// matching of folder names when determining whether something is music, a
// ringtone, podcast, etc, so we might need to reclassify some files.
db.execSQL("UPDATE audio_meta SET is_music=1 WHERE is_music=0 AND " +
"_data LIKE '%/music/%';");
db.execSQL("UPDATE audio_meta SET is_ringtone=1 WHERE is_ringtone=0 AND " +
"_data LIKE '%/ringtones/%';");
db.execSQL("UPDATE audio_meta SET is_notification=1 WHERE is_notification=0 AND " +
"_data LIKE '%/notifications/%';");
db.execSQL("UPDATE audio_meta SET is_alarm=1 WHERE is_alarm=0 AND " +
"_data LIKE '%/alarms/%';");
db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE is_podcast=0 AND " +
"_data LIKE '%/podcasts/%';");
}
if (fromVersion < 74) {
// This view is used instead of the audio view by the union below, to force
// sqlite to use the title_key index. This greatly reduces memory usage
// (no separate copy pass needed for sorting, which could cause errors on
// large datasets) and improves speed (by about 35% on a large dataset)
db.execSQL("CREATE VIEW IF NOT EXISTS searchhelpertitle AS SELECT * FROM audio " +
"ORDER BY title_key;");
db.execSQL("CREATE VIEW IF NOT EXISTS search AS " +
"SELECT _id," +
"'artist' AS mime_type," +
"artist," +
"NULL AS album," +
"NULL AS title," +
"artist AS text1," +
"NULL AS text2," +
"number_of_albums AS data1," +
"number_of_tracks AS data2," +
"artist_key AS match," +
"'content://media/external/audio/artists/'||_id AS suggest_intent_data," +
"1 AS grouporder " +
"FROM artist_info WHERE (artist!='" + MediaStore.UNKNOWN_STRING + "') " +
"UNION ALL " +
"SELECT _id," +
"'album' AS mime_type," +
"artist," +
"album," +
"NULL AS title," +
"album AS text1," +
"artist AS text2," +
"NULL AS data1," +
"NULL AS data2," +
"artist_key||' '||album_key AS match," +
"'content://media/external/audio/albums/'||_id AS suggest_intent_data," +
"2 AS grouporder " +
"FROM album_info WHERE (album!='" + MediaStore.UNKNOWN_STRING + "') " +
"UNION ALL " +
"SELECT searchhelpertitle._id AS _id," +
"mime_type," +
"artist," +
"album," +
"title," +
"title AS text1," +
"artist AS text2," +
"NULL AS data1," +
"NULL AS data2," +
"artist_key||' '||album_key||' '||title_key AS match," +
"'content://media/external/audio/media/'||searchhelpertitle._id AS " +
"suggest_intent_data," +
"3 AS grouporder " +
"FROM searchhelpertitle WHERE (title != '') "
);
}
if (fromVersion < 75) {
// Force a rescan of the audio entries so we can apply the new logic to
// distinguish same-named albums.
db.execSQL("UPDATE audio_meta SET date_modified=0;");
db.execSQL("DELETE FROM albums");
}
if (fromVersion < 76) {
// We now ignore double quotes when building the key, so we have to remove all of them
// from existing keys.
db.execSQL("UPDATE audio_meta SET title_key=" +
"REPLACE(title_key,x'081D08C29F081D',x'081D') " +
"WHERE title_key LIKE '%'||x'081D08C29F081D'||'%';");
db.execSQL("UPDATE albums SET album_key=" +
"REPLACE(album_key,x'081D08C29F081D',x'081D') " +
"WHERE album_key LIKE '%'||x'081D08C29F081D'||'%';");
db.execSQL("UPDATE artists SET artist_key=" +
"REPLACE(artist_key,x'081D08C29F081D',x'081D') " +
"WHERE artist_key LIKE '%'||x'081D08C29F081D'||'%';");
}
/*
* Android 1.6 shipped with database version 76
*/
if (fromVersion < 77) {
// create video thumbnail table
db.execSQL("CREATE TABLE IF NOT EXISTS videothumbnails (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"video_id INTEGER," +
"kind INTEGER," +
"width INTEGER," +
"height INTEGER" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS video_id_index on videothumbnails(video_id);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS videothumbnails_cleanup DELETE ON videothumbnails " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
/*
* Android 2.0 and 2.0.1 shipped with database version 77
*/
if (fromVersion < 78) {
// Force a rescan of the video entries so we can update
// latest changed DATE_TAKEN units (in milliseconds).
db.execSQL("UPDATE video SET date_modified=0;");
}
/*
* Android 2.1 shipped with database version 78
*/
if (fromVersion < 79) {
// move /sdcard/albumthumbs to
// /sdcard/Android/data/com.android.providers.media/albumthumbs,
// and update the database accordingly
String oldthumbspath = mExternalStoragePath + "/albumthumbs";
String newthumbspath = mExternalStoragePath + "/" + ALBUM_THUMB_FOLDER;
File thumbsfolder = new File(oldthumbspath);
if (thumbsfolder.exists()) {
// move folder to its new location
File newthumbsfolder = new File(newthumbspath);
newthumbsfolder.getParentFile().mkdirs();
if(thumbsfolder.renameTo(newthumbsfolder)) {
// update the database
db.execSQL("UPDATE album_art SET _data=REPLACE(_data, '" +
oldthumbspath + "','" + newthumbspath + "');");
}
}
}
if (fromVersion < 80) {
// Force rescan of image entries to update DATE_TAKEN as UTC timestamp.
db.execSQL("UPDATE images SET date_modified=0;");
}
if (fromVersion < 81 && !internal) {
// Delete entries starting with /mnt/sdcard. This is for the benefit
// of users running builds between 2.0.1 and 2.1 final only, since
// users updating from 2.0 or earlier will not have such entries.
// First we need to update the _data fields in the affected tables, since
// otherwise deleting the entries will also delete the underlying files
// (via a trigger), and we want to keep them.
db.execSQL("UPDATE audio_playlists SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE images SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE video SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE videothumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE thumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE album_art SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE audio_meta SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
// Once the paths have been renamed, we can safely delete the entries
db.execSQL("DELETE FROM audio_playlists WHERE _data IS '////';");
db.execSQL("DELETE FROM images WHERE _data IS '////';");
db.execSQL("DELETE FROM video WHERE _data IS '////';");
db.execSQL("DELETE FROM videothumbnails WHERE _data IS '////';");
db.execSQL("DELETE FROM thumbnails WHERE _data IS '////';");
db.execSQL("DELETE FROM audio_meta WHERE _data IS '////';");
db.execSQL("DELETE FROM album_art WHERE _data IS '////';");
// rename existing entries starting with /sdcard to /mnt/sdcard
db.execSQL("UPDATE audio_meta" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE audio_playlists" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE images" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE video" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE videothumbnails" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE thumbnails" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE album_art" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
// Delete albums and artists, then clear the modification time on songs, which
// will cause the media scanner to rescan everything, rebuilding the artist and
// album tables along the way, while preserving playlists.
// We need this rescan because ICU also changed, and now generates different
// collation keys
db.execSQL("DELETE from albums");
db.execSQL("DELETE from artists");
db.execSQL("UPDATE audio_meta SET date_modified=0;");
}
if (fromVersion < 82) {
// recreate this view with the correct "group by" specifier
db.execSQL("DROP VIEW IF EXISTS artist_info");
db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
"SELECT artist_id AS _id, artist, artist_key, " +
"COUNT(DISTINCT album_key) AS number_of_albums, " +
"COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
"GROUP BY artist_key;");
}
/* we skipped over version 83, and reverted versions 84, 85 and 86 */
if (fromVersion < 87) {
// The fastscroll thumb needs an index on the strings being displayed,
// otherwise the queries it does to determine the correct position
// becomes really inefficient
db.execSQL("CREATE INDEX IF NOT EXISTS title_idx on audio_meta(title);");
db.execSQL("CREATE INDEX IF NOT EXISTS artist_idx on artists(artist);");
db.execSQL("CREATE INDEX IF NOT EXISTS album_idx on albums(album);");
}
if (fromVersion < 88) {
// Clean up a few more things from versions 84/85/86, and recreate
// the few things worth keeping from those changes.
db.execSQL("DROP TRIGGER IF EXISTS albums_update1;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update2;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update3;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update4;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update1;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update2;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update3;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update4;");
db.execSQL("DROP VIEW IF EXISTS album_artists;");
db.execSQL("CREATE INDEX IF NOT EXISTS album_id_idx on audio_meta(album_id);");
db.execSQL("CREATE INDEX IF NOT EXISTS artist_id_idx on audio_meta(artist_id);");
// For a given artist_id, provides the album_id for albums on
// which the artist appears.
db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
"SELECT DISTINCT artist_id, album_id FROM audio_meta;");
}
if (fromVersion < 89) {
updateBucketNames(db, "images");
updateBucketNames(db, "video");
}
if (fromVersion < 91) {
// Never query by mini_thumb_magic_index
db.execSQL("DROP INDEX IF EXISTS mini_thumb_magic_index");
// sort the items by taken date in each bucket
db.execSQL("CREATE INDEX IF NOT EXISTS image_bucket_index ON images(bucket_id, datetaken)");
db.execSQL("CREATE INDEX IF NOT EXISTS video_bucket_index ON video(bucket_id, datetaken)");
}
// versions 92 - 98 were work in progress on MTP obsoleted by version 99
if (fromVersion < 99) {
// Remove various stages of work in progress for MTP support
db.execSQL("DROP TABLE IF EXISTS objects");
db.execSQL("DROP TABLE IF EXISTS files");
db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_images;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_audio;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_video;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_playlists;");
db.execSQL("DROP TRIGGER IF EXISTS media_cleanup;");
// Create a new table to manage all files in our storage.
// This contains a union of all the columns from the old
// images, audio_meta, videos and audio_playlist tables.
db.execSQL("CREATE TABLE files (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," + // this can be null for playlists
"_size INTEGER," +
"format INTEGER," +
"parent INTEGER," +
"date_added INTEGER," +
"date_modified INTEGER," +
"mime_type TEXT," +
"title TEXT," +
"description TEXT," +
"_display_name TEXT," +
// for images
"picasa_id TEXT," +
"orientation INTEGER," +
// for images and video
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"mini_thumb_magic INTEGER," +
"bucket_id TEXT," +
"bucket_display_name TEXT," +
"isprivate INTEGER," +
// for audio
"title_key TEXT," +
"artist_id INTEGER," +
"album_id INTEGER," +
"composer TEXT," +
"track INTEGER," +
"year INTEGER CHECK(year!=0)," +
"is_ringtone INTEGER," +
"is_music INTEGER," +
"is_alarm INTEGER," +
"is_notification INTEGER," +
"is_podcast INTEGER," +
// for audio and video
"duration INTEGER," +
"bookmark INTEGER," +
// for video
"artist TEXT," +
"album TEXT," +
"resolution TEXT," +
"tags TEXT," +
"category TEXT," +
"language TEXT," +
"mini_thumb_data TEXT," +
// for playlists
"name TEXT," +
// media_type is used by the views to emulate the old
// images, audio_meta, videos and audio_playlist tables.
"media_type INTEGER," +
// Value of _id from the old media table.
// Used only for updating other tables during database upgrade.
"old_id INTEGER" +
");");
db.execSQL("CREATE INDEX path_index ON files(_data);");
db.execSQL("CREATE INDEX media_type_index ON files(media_type);");
// Copy all data from our obsolete tables to the new files table
db.execSQL("INSERT INTO files (" + IMAGE_COLUMNS + ",old_id,media_type) SELECT "
+ IMAGE_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_IMAGE + " FROM images;");
db.execSQL("INSERT INTO files (" + AUDIO_COLUMNSv99 + ",old_id,media_type) SELECT "
+ AUDIO_COLUMNSv99 + ",_id," + FileColumns.MEDIA_TYPE_AUDIO + " FROM audio_meta;");
db.execSQL("INSERT INTO files (" + VIDEO_COLUMNS + ",old_id,media_type) SELECT "
+ VIDEO_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_VIDEO + " FROM video;");
if (!internal) {
db.execSQL("INSERT INTO files (" + PLAYLIST_COLUMNS + ",old_id,media_type) SELECT "
+ PLAYLIST_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_PLAYLIST
+ " FROM audio_playlists;");
}
// Delete the old tables
db.execSQL("DROP TABLE IF EXISTS images");
db.execSQL("DROP TABLE IF EXISTS audio_meta");
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TABLE IF EXISTS audio_playlists");
// Create views to replace our old tables
db.execSQL("CREATE VIEW images AS SELECT _id," + IMAGE_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_IMAGE + ";");
// audio_meta will be created below for schema 100
// db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv99 +
// " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
// + FileColumns.MEDIA_TYPE_AUDIO + ";");
db.execSQL("CREATE VIEW video AS SELECT _id," + VIDEO_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_VIDEO + ";");
if (!internal) {
db.execSQL("CREATE VIEW audio_playlists AS SELECT _id," + PLAYLIST_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_PLAYLIST + ";");
}
// update the image_id column in the thumbnails table.
db.execSQL("UPDATE thumbnails SET image_id = (SELECT _id FROM files "
+ "WHERE files.old_id = thumbnails.image_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_IMAGE + ");");
if (!internal) {
// update audio_id in the audio_genres_map and audio_playlists_map tables.
db.execSQL("UPDATE audio_genres_map SET audio_id = (SELECT _id FROM files "
+ "WHERE files.old_id = audio_genres_map.audio_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_AUDIO + ");");
db.execSQL("UPDATE audio_playlists_map SET audio_id = (SELECT _id FROM files "
+ "WHERE files.old_id = audio_playlists_map.audio_id "
+ "AND files.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + ");");
}
// update video_id in the videothumbnails table.
db.execSQL("UPDATE videothumbnails SET video_id = (SELECT _id FROM files "
+ "WHERE files.old_id = videothumbnails.video_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_VIDEO + ");");
// update indices to work on the files table
db.execSQL("DROP INDEX IF EXISTS title_idx");
db.execSQL("DROP INDEX IF EXISTS album_id_idx");
db.execSQL("DROP INDEX IF EXISTS image_bucket_index");
db.execSQL("DROP INDEX IF EXISTS video_bucket_index");
db.execSQL("DROP INDEX IF EXISTS sort_index");
db.execSQL("DROP INDEX IF EXISTS titlekey_index");
db.execSQL("DROP INDEX IF EXISTS artist_id_idx");
db.execSQL("CREATE INDEX title_idx ON files(title);");
db.execSQL("CREATE INDEX album_id_idx ON files(album_id);");
db.execSQL("CREATE INDEX bucket_index ON files(bucket_id, datetaken);");
db.execSQL("CREATE INDEX sort_index ON files(datetaken ASC, _id ASC);");
db.execSQL("CREATE INDEX titlekey_index ON files(title_key);");
db.execSQL("CREATE INDEX artist_id_idx ON files(artist_id);");
// Recreate triggers for our obsolete tables on the new files table
db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_delete");
db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_IMAGE + " " +
"BEGIN " +
"DELETE FROM thumbnails WHERE image_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + " " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
if (!internal) {
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + " " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
"DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_PLAYLIST + " " +
"BEGIN " +
"DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_delete INSTEAD OF DELETE ON audio " +
"BEGIN " +
"DELETE from files where _id=old._id;" +
"DELETE from audio_playlists_map where audio_id=old._id;" +
"DELETE from audio_genres_map where audio_id=old._id;" +
"END");
}
}
if (fromVersion < 100) {
db.execSQL("ALTER TABLE files ADD COLUMN album_artist TEXT;");
db.execSQL("DROP VIEW IF EXISTS audio_meta;");
db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv100 +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_AUDIO + ";");
db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_AUDIO + ";");
}
sanityCheck(db, fromVersion);
}
| private static void updateDatabase(SQLiteDatabase db, boolean internal,
int fromVersion, int toVersion) {
// sanity checks
if (toVersion != DATABASE_VERSION) {
Log.e(TAG, "Illegal update request. Got " + toVersion + ", expected " +
DATABASE_VERSION);
throw new IllegalArgumentException();
} else if (fromVersion > toVersion) {
Log.e(TAG, "Illegal update request: can't downgrade from " + fromVersion +
" to " + toVersion + ". Did you forget to wipe data?");
throw new IllegalArgumentException();
}
// Revisions 84-86 were a failed attempt at supporting the "album artist" id3 tag.
// We can't downgrade from those revisions, so start over.
// (the initial change to do this was wrong, so now we actually need to start over
// if the database version is 84-89)
// Post-gingerbread, revisions 91-94 were broken in a way that is not easy to repair.
// However version 91 was reused in a divergent development path for gingerbread,
// so we need to support upgrades from 91.
// Therefore we will only force a reset for versions 92 - 94.
if (fromVersion < 63 || (fromVersion >= 84 && fromVersion <= 89) ||
(fromVersion >= 92 && fromVersion <= 94)) {
fromVersion = 63;
// Drop everything and start over.
Log.i(TAG, "Upgrading media database from version " +
fromVersion + " to " + toVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS images");
db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
db.execSQL("DROP TABLE IF EXISTS thumbnails");
db.execSQL("DROP TRIGGER IF EXISTS thumbnails_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_meta");
db.execSQL("DROP TABLE IF EXISTS artists");
db.execSQL("DROP TABLE IF EXISTS albums");
db.execSQL("DROP TABLE IF EXISTS album_art");
db.execSQL("DROP VIEW IF EXISTS artist_info");
db.execSQL("DROP VIEW IF EXISTS album_info");
db.execSQL("DROP VIEW IF EXISTS artists_albums_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_genres");
db.execSQL("DROP TABLE IF EXISTS audio_genres_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_genres_cleanup");
db.execSQL("DROP TABLE IF EXISTS audio_playlists");
db.execSQL("DROP TABLE IF EXISTS audio_playlists_map");
db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup1");
db.execSQL("DROP TRIGGER IF EXISTS albumart_cleanup2");
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
db.execSQL("DROP TABLE IF EXISTS objects");
db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup");
db.execSQL("CREATE TABLE IF NOT EXISTS images (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"_size INTEGER," +
"_display_name TEXT," +
"mime_type TEXT," +
"title TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"description TEXT," +
"picasa_id TEXT," +
"isprivate INTEGER," +
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"orientation INTEGER," +
"mini_thumb_magic INTEGER," +
"bucket_id TEXT," +
"bucket_display_name TEXT" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS mini_thumb_magic_index on images(mini_thumb_magic);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON images " +
"BEGIN " +
"DELETE FROM thumbnails WHERE image_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
// create image thumbnail table
db.execSQL("CREATE TABLE IF NOT EXISTS thumbnails (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"image_id INTEGER," +
"kind INTEGER," +
"width INTEGER," +
"height INTEGER" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS image_id_index on thumbnails(image_id);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS thumbnails_cleanup DELETE ON thumbnails " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
// Contains meta data about audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_meta (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT UNIQUE NOT NULL," +
"_display_name TEXT," +
"_size INTEGER," +
"mime_type TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"title TEXT NOT NULL," +
"title_key TEXT NOT NULL," +
"duration INTEGER," +
"artist_id INTEGER," +
"composer TEXT," +
"album_id INTEGER," +
"track INTEGER," + // track is an integer to allow proper sorting
"year INTEGER CHECK(year!=0)," +
"is_ringtone INTEGER," +
"is_music INTEGER," +
"is_alarm INTEGER," +
"is_notification INTEGER" +
");");
// Contains a sort/group "key" and the preferred display name for artists
db.execSQL("CREATE TABLE IF NOT EXISTS artists (" +
"artist_id INTEGER PRIMARY KEY," +
"artist_key TEXT NOT NULL UNIQUE," +
"artist TEXT NOT NULL" +
");");
// Contains a sort/group "key" and the preferred display name for albums
db.execSQL("CREATE TABLE IF NOT EXISTS albums (" +
"album_id INTEGER PRIMARY KEY," +
"album_key TEXT NOT NULL UNIQUE," +
"album TEXT NOT NULL" +
");");
db.execSQL("CREATE TABLE IF NOT EXISTS album_art (" +
"album_id INTEGER PRIMARY KEY," +
"_data TEXT" +
");");
recreateAudioView(db);
// Provides some extra info about artists, like the number of tracks
// and albums for this artist
db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
"SELECT artist_id AS _id, artist, artist_key, " +
"COUNT(DISTINCT album) AS number_of_albums, " +
"COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
"GROUP BY artist_key;");
// Provides extra info albums, such as the number of tracks
db.execSQL("CREATE VIEW IF NOT EXISTS album_info AS " +
"SELECT audio.album_id AS _id, album, album_key, " +
"MIN(year) AS minyear, " +
"MAX(year) AS maxyear, artist, artist_id, artist_key, " +
"count(*) AS " + MediaStore.Audio.Albums.NUMBER_OF_SONGS +
",album_art._data AS album_art" +
" FROM audio LEFT OUTER JOIN album_art ON audio.album_id=album_art.album_id" +
" WHERE is_music=1 GROUP BY audio.album_id;");
// For a given artist_id, provides the album_id for albums on
// which the artist appears.
db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
"SELECT DISTINCT artist_id, album_id FROM audio_meta;");
/*
* Only external media volumes can handle genres, playlists, etc.
*/
if (!internal) {
// Cleans up when an audio file is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON audio_meta " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
"DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
"END");
// Contains audio genre definitions
db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres (" +
"_id INTEGER PRIMARY KEY," +
"name TEXT NOT NULL" +
");");
// Contiains mappings between audio genres and audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_genres_map (" +
"_id INTEGER PRIMARY KEY," +
"audio_id INTEGER NOT NULL," +
"genre_id INTEGER NOT NULL" +
");");
// Cleans up when an audio genre is delete
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_genres_cleanup DELETE ON audio_genres " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE genre_id = old._id;" +
"END");
// Contains audio playlist definitions
db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," + // _data is path for file based playlists, or null
"name TEXT NOT NULL," +
"date_added INTEGER," +
"date_modified INTEGER" +
");");
// Contains mappings between audio playlists and audio files
db.execSQL("CREATE TABLE IF NOT EXISTS audio_playlists_map (" +
"_id INTEGER PRIMARY KEY," +
"audio_id INTEGER NOT NULL," +
"playlist_id INTEGER NOT NULL," +
"play_order INTEGER NOT NULL" +
");");
// Cleans up when an audio playlist is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON audio_playlists " +
"BEGIN " +
"DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
// Cleans up album_art table entry when an album is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup1 DELETE ON albums " +
"BEGIN " +
"DELETE FROM album_art WHERE album_id = old.album_id;" +
"END");
// Cleans up album_art when an album is deleted
db.execSQL("CREATE TRIGGER IF NOT EXISTS albumart_cleanup2 DELETE ON album_art " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
// Contains meta data about video files
db.execSQL("CREATE TABLE IF NOT EXISTS video (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT NOT NULL," +
"_display_name TEXT," +
"_size INTEGER," +
"mime_type TEXT," +
"date_added INTEGER," +
"date_modified INTEGER," +
"title TEXT," +
"duration INTEGER," +
"artist TEXT," +
"album TEXT," +
"resolution TEXT," +
"description TEXT," +
"isprivate INTEGER," + // for YouTube videos
"tags TEXT," + // for YouTube videos
"category TEXT," + // for YouTube videos
"language TEXT," + // for YouTube videos
"mini_thumb_data TEXT," +
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"mini_thumb_magic INTEGER" +
");");
db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON video " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
// At this point the database is at least at schema version 63 (it was
// either created at version 63 by the code above, or was already at
// version 63 or later)
if (fromVersion < 64) {
// create the index that updates the database to schema version 64
db.execSQL("CREATE INDEX IF NOT EXISTS sort_index on images(datetaken ASC, _id ASC);");
}
/*
* Android 1.0 shipped with database version 64
*/
if (fromVersion < 65) {
// create the index that updates the database to schema version 65
db.execSQL("CREATE INDEX IF NOT EXISTS titlekey_index on audio_meta(title_key);");
}
// In version 66, originally we updateBucketNames(db, "images"),
// but we need to do it in version 89 and therefore save the update here.
if (fromVersion < 67) {
// create the indices that update the database to schema version 67
db.execSQL("CREATE INDEX IF NOT EXISTS albumkey_index on albums(album_key);");
db.execSQL("CREATE INDEX IF NOT EXISTS artistkey_index on artists(artist_key);");
}
if (fromVersion < 68) {
// Create bucket_id and bucket_display_name columns for the video table.
db.execSQL("ALTER TABLE video ADD COLUMN bucket_id TEXT;");
db.execSQL("ALTER TABLE video ADD COLUMN bucket_display_name TEXT");
// In version 68, originally we updateBucketNames(db, "video"),
// but we need to do it in version 89 and therefore save the update here.
}
if (fromVersion < 69) {
updateDisplayName(db, "images");
}
if (fromVersion < 70) {
// Create bookmark column for the video table.
db.execSQL("ALTER TABLE video ADD COLUMN bookmark INTEGER;");
}
if (fromVersion < 71) {
// There is no change to the database schema, however a code change
// fixed parsing of metadata for certain files bought from the
// iTunes music store, so we want to rescan files that might need it.
// We do this by clearing the modification date in the database for
// those files, so that the media scanner will see them as updated
// and rescan them.
db.execSQL("UPDATE audio_meta SET date_modified=0 WHERE _id IN (" +
"SELECT _id FROM audio where mime_type='audio/mp4' AND " +
"artist='" + MediaStore.UNKNOWN_STRING + "' AND " +
"album='" + MediaStore.UNKNOWN_STRING + "'" +
");");
}
if (fromVersion < 72) {
// Create is_podcast and bookmark columns for the audio table.
db.execSQL("ALTER TABLE audio_meta ADD COLUMN is_podcast INTEGER;");
db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE _data LIKE '%/podcasts/%';");
db.execSQL("UPDATE audio_meta SET is_music=0 WHERE is_podcast=1" +
" AND _data NOT LIKE '%/music/%';");
db.execSQL("ALTER TABLE audio_meta ADD COLUMN bookmark INTEGER;");
// New columns added to tables aren't visible in views on those tables
// without opening and closing the database (or using the 'vacuum' command,
// which we can't do here because all this code runs inside a transaction).
// To work around this, we drop and recreate the affected view and trigger.
recreateAudioView(db);
}
/*
* Android 1.5 shipped with database version 72
*/
if (fromVersion < 73) {
// There is no change to the database schema, but we now do case insensitive
// matching of folder names when determining whether something is music, a
// ringtone, podcast, etc, so we might need to reclassify some files.
db.execSQL("UPDATE audio_meta SET is_music=1 WHERE is_music=0 AND " +
"_data LIKE '%/music/%';");
db.execSQL("UPDATE audio_meta SET is_ringtone=1 WHERE is_ringtone=0 AND " +
"_data LIKE '%/ringtones/%';");
db.execSQL("UPDATE audio_meta SET is_notification=1 WHERE is_notification=0 AND " +
"_data LIKE '%/notifications/%';");
db.execSQL("UPDATE audio_meta SET is_alarm=1 WHERE is_alarm=0 AND " +
"_data LIKE '%/alarms/%';");
db.execSQL("UPDATE audio_meta SET is_podcast=1 WHERE is_podcast=0 AND " +
"_data LIKE '%/podcasts/%';");
}
if (fromVersion < 74) {
// This view is used instead of the audio view by the union below, to force
// sqlite to use the title_key index. This greatly reduces memory usage
// (no separate copy pass needed for sorting, which could cause errors on
// large datasets) and improves speed (by about 35% on a large dataset)
db.execSQL("CREATE VIEW IF NOT EXISTS searchhelpertitle AS SELECT * FROM audio " +
"ORDER BY title_key;");
db.execSQL("CREATE VIEW IF NOT EXISTS search AS " +
"SELECT _id," +
"'artist' AS mime_type," +
"artist," +
"NULL AS album," +
"NULL AS title," +
"artist AS text1," +
"NULL AS text2," +
"number_of_albums AS data1," +
"number_of_tracks AS data2," +
"artist_key AS match," +
"'content://media/external/audio/artists/'||_id AS suggest_intent_data," +
"1 AS grouporder " +
"FROM artist_info WHERE (artist!='" + MediaStore.UNKNOWN_STRING + "') " +
"UNION ALL " +
"SELECT _id," +
"'album' AS mime_type," +
"artist," +
"album," +
"NULL AS title," +
"album AS text1," +
"artist AS text2," +
"NULL AS data1," +
"NULL AS data2," +
"artist_key||' '||album_key AS match," +
"'content://media/external/audio/albums/'||_id AS suggest_intent_data," +
"2 AS grouporder " +
"FROM album_info WHERE (album!='" + MediaStore.UNKNOWN_STRING + "') " +
"UNION ALL " +
"SELECT searchhelpertitle._id AS _id," +
"mime_type," +
"artist," +
"album," +
"title," +
"title AS text1," +
"artist AS text2," +
"NULL AS data1," +
"NULL AS data2," +
"artist_key||' '||album_key||' '||title_key AS match," +
"'content://media/external/audio/media/'||searchhelpertitle._id AS " +
"suggest_intent_data," +
"3 AS grouporder " +
"FROM searchhelpertitle WHERE (title != '') "
);
}
if (fromVersion < 75) {
// Force a rescan of the audio entries so we can apply the new logic to
// distinguish same-named albums.
db.execSQL("UPDATE audio_meta SET date_modified=0;");
db.execSQL("DELETE FROM albums");
}
if (fromVersion < 76) {
// We now ignore double quotes when building the key, so we have to remove all of them
// from existing keys.
db.execSQL("UPDATE audio_meta SET title_key=" +
"REPLACE(title_key,x'081D08C29F081D',x'081D') " +
"WHERE title_key LIKE '%'||x'081D08C29F081D'||'%';");
db.execSQL("UPDATE albums SET album_key=" +
"REPLACE(album_key,x'081D08C29F081D',x'081D') " +
"WHERE album_key LIKE '%'||x'081D08C29F081D'||'%';");
db.execSQL("UPDATE artists SET artist_key=" +
"REPLACE(artist_key,x'081D08C29F081D',x'081D') " +
"WHERE artist_key LIKE '%'||x'081D08C29F081D'||'%';");
}
/*
* Android 1.6 shipped with database version 76
*/
if (fromVersion < 77) {
// create video thumbnail table
db.execSQL("CREATE TABLE IF NOT EXISTS videothumbnails (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," +
"video_id INTEGER," +
"kind INTEGER," +
"width INTEGER," +
"height INTEGER" +
");");
db.execSQL("CREATE INDEX IF NOT EXISTS video_id_index on videothumbnails(video_id);");
db.execSQL("CREATE TRIGGER IF NOT EXISTS videothumbnails_cleanup DELETE ON videothumbnails " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
}
/*
* Android 2.0 and 2.0.1 shipped with database version 77
*/
if (fromVersion < 78) {
// Force a rescan of the video entries so we can update
// latest changed DATE_TAKEN units (in milliseconds).
db.execSQL("UPDATE video SET date_modified=0;");
}
/*
* Android 2.1 shipped with database version 78
*/
if (fromVersion < 79) {
// move /sdcard/albumthumbs to
// /sdcard/Android/data/com.android.providers.media/albumthumbs,
// and update the database accordingly
String oldthumbspath = mExternalStoragePath + "/albumthumbs";
String newthumbspath = mExternalStoragePath + "/" + ALBUM_THUMB_FOLDER;
File thumbsfolder = new File(oldthumbspath);
if (thumbsfolder.exists()) {
// move folder to its new location
File newthumbsfolder = new File(newthumbspath);
newthumbsfolder.getParentFile().mkdirs();
if(thumbsfolder.renameTo(newthumbsfolder)) {
// update the database
db.execSQL("UPDATE album_art SET _data=REPLACE(_data, '" +
oldthumbspath + "','" + newthumbspath + "');");
}
}
}
if (fromVersion < 80) {
// Force rescan of image entries to update DATE_TAKEN as UTC timestamp.
db.execSQL("UPDATE images SET date_modified=0;");
}
if (fromVersion < 81 && !internal) {
// Delete entries starting with /mnt/sdcard. This is for the benefit
// of users running builds between 2.0.1 and 2.1 final only, since
// users updating from 2.0 or earlier will not have such entries.
// First we need to update the _data fields in the affected tables, since
// otherwise deleting the entries will also delete the underlying files
// (via a trigger), and we want to keep them.
db.execSQL("UPDATE audio_playlists SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE images SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE video SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE videothumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE thumbnails SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE album_art SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
db.execSQL("UPDATE audio_meta SET _data='////' WHERE _data LIKE '/mnt/sdcard/%';");
// Once the paths have been renamed, we can safely delete the entries
db.execSQL("DELETE FROM audio_playlists WHERE _data IS '////';");
db.execSQL("DELETE FROM images WHERE _data IS '////';");
db.execSQL("DELETE FROM video WHERE _data IS '////';");
db.execSQL("DELETE FROM videothumbnails WHERE _data IS '////';");
db.execSQL("DELETE FROM thumbnails WHERE _data IS '////';");
db.execSQL("DELETE FROM audio_meta WHERE _data IS '////';");
db.execSQL("DELETE FROM album_art WHERE _data IS '////';");
// rename existing entries starting with /sdcard to /mnt/sdcard
db.execSQL("UPDATE audio_meta" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE audio_playlists" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE images" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE video" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE videothumbnails" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE thumbnails" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
db.execSQL("UPDATE album_art" +
" SET _data='/mnt/sdcard'||SUBSTR(_data,8) WHERE _data LIKE '/sdcard/%';");
// Delete albums and artists, then clear the modification time on songs, which
// will cause the media scanner to rescan everything, rebuilding the artist and
// album tables along the way, while preserving playlists.
// We need this rescan because ICU also changed, and now generates different
// collation keys
db.execSQL("DELETE from albums");
db.execSQL("DELETE from artists");
db.execSQL("UPDATE audio_meta SET date_modified=0;");
}
if (fromVersion < 82) {
// recreate this view with the correct "group by" specifier
db.execSQL("DROP VIEW IF EXISTS artist_info");
db.execSQL("CREATE VIEW IF NOT EXISTS artist_info AS " +
"SELECT artist_id AS _id, artist, artist_key, " +
"COUNT(DISTINCT album_key) AS number_of_albums, " +
"COUNT(*) AS number_of_tracks FROM audio WHERE is_music=1 "+
"GROUP BY artist_key;");
}
/* we skipped over version 83, and reverted versions 84, 85 and 86 */
if (fromVersion < 87) {
// The fastscroll thumb needs an index on the strings being displayed,
// otherwise the queries it does to determine the correct position
// becomes really inefficient
db.execSQL("CREATE INDEX IF NOT EXISTS title_idx on audio_meta(title);");
db.execSQL("CREATE INDEX IF NOT EXISTS artist_idx on artists(artist);");
db.execSQL("CREATE INDEX IF NOT EXISTS album_idx on albums(album);");
}
if (fromVersion < 88) {
// Clean up a few more things from versions 84/85/86, and recreate
// the few things worth keeping from those changes.
db.execSQL("DROP TRIGGER IF EXISTS albums_update1;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update2;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update3;");
db.execSQL("DROP TRIGGER IF EXISTS albums_update4;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update1;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update2;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update3;");
db.execSQL("DROP TRIGGER IF EXISTS artist_update4;");
db.execSQL("DROP VIEW IF EXISTS album_artists;");
db.execSQL("CREATE INDEX IF NOT EXISTS album_id_idx on audio_meta(album_id);");
db.execSQL("CREATE INDEX IF NOT EXISTS artist_id_idx on audio_meta(artist_id);");
// For a given artist_id, provides the album_id for albums on
// which the artist appears.
db.execSQL("CREATE VIEW IF NOT EXISTS artists_albums_map AS " +
"SELECT DISTINCT artist_id, album_id FROM audio_meta;");
}
if (fromVersion < 89) {
updateBucketNames(db, "images");
updateBucketNames(db, "video");
}
if (fromVersion < 91) {
// Never query by mini_thumb_magic_index
db.execSQL("DROP INDEX IF EXISTS mini_thumb_magic_index");
// sort the items by taken date in each bucket
db.execSQL("CREATE INDEX IF NOT EXISTS image_bucket_index ON images(bucket_id, datetaken)");
db.execSQL("CREATE INDEX IF NOT EXISTS video_bucket_index ON video(bucket_id, datetaken)");
}
// versions 92 - 98 were work in progress on MTP obsoleted by version 99
if (fromVersion < 99) {
// Remove various stages of work in progress for MTP support
db.execSQL("DROP TABLE IF EXISTS objects");
db.execSQL("DROP TABLE IF EXISTS files");
db.execSQL("DROP TRIGGER IF EXISTS images_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS audio_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS video_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS playlists_objects_cleanup;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_images;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_audio;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_video;");
db.execSQL("DROP TRIGGER IF EXISTS files_cleanup_playlists;");
db.execSQL("DROP TRIGGER IF EXISTS media_cleanup;");
// Create a new table to manage all files in our storage.
// This contains a union of all the columns from the old
// images, audio_meta, videos and audio_playlist tables.
db.execSQL("CREATE TABLE files (" +
"_id INTEGER PRIMARY KEY," +
"_data TEXT," + // this can be null for playlists
"_size INTEGER," +
"format INTEGER," +
"parent INTEGER," +
"date_added INTEGER," +
"date_modified INTEGER," +
"mime_type TEXT," +
"title TEXT," +
"description TEXT," +
"_display_name TEXT," +
// for images
"picasa_id TEXT," +
"orientation INTEGER," +
// for images and video
"latitude DOUBLE," +
"longitude DOUBLE," +
"datetaken INTEGER," +
"mini_thumb_magic INTEGER," +
"bucket_id TEXT," +
"bucket_display_name TEXT," +
"isprivate INTEGER," +
// for audio
"title_key TEXT," +
"artist_id INTEGER," +
"album_id INTEGER," +
"composer TEXT," +
"track INTEGER," +
"year INTEGER CHECK(year!=0)," +
"is_ringtone INTEGER," +
"is_music INTEGER," +
"is_alarm INTEGER," +
"is_notification INTEGER," +
"is_podcast INTEGER," +
// for audio and video
"duration INTEGER," +
"bookmark INTEGER," +
// for video
"artist TEXT," +
"album TEXT," +
"resolution TEXT," +
"tags TEXT," +
"category TEXT," +
"language TEXT," +
"mini_thumb_data TEXT," +
// for playlists
"name TEXT," +
// media_type is used by the views to emulate the old
// images, audio_meta, videos and audio_playlist tables.
"media_type INTEGER," +
// Value of _id from the old media table.
// Used only for updating other tables during database upgrade.
"old_id INTEGER" +
");");
db.execSQL("CREATE INDEX path_index ON files(_data);");
db.execSQL("CREATE INDEX media_type_index ON files(media_type);");
// Copy all data from our obsolete tables to the new files table
db.execSQL("INSERT INTO files (" + IMAGE_COLUMNS + ",old_id,media_type) SELECT "
+ IMAGE_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_IMAGE + " FROM images;");
db.execSQL("INSERT INTO files (" + AUDIO_COLUMNSv99 + ",old_id,media_type) SELECT "
+ AUDIO_COLUMNSv99 + ",_id," + FileColumns.MEDIA_TYPE_AUDIO + " FROM audio_meta;");
db.execSQL("INSERT INTO files (" + VIDEO_COLUMNS + ",old_id,media_type) SELECT "
+ VIDEO_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_VIDEO + " FROM video;");
if (!internal) {
db.execSQL("INSERT INTO files (" + PLAYLIST_COLUMNS + ",old_id,media_type) SELECT "
+ PLAYLIST_COLUMNS + ",_id," + FileColumns.MEDIA_TYPE_PLAYLIST
+ " FROM audio_playlists;");
}
// Delete the old tables
db.execSQL("DROP TABLE IF EXISTS images");
db.execSQL("DROP TABLE IF EXISTS audio_meta");
db.execSQL("DROP TABLE IF EXISTS video");
db.execSQL("DROP TABLE IF EXISTS audio_playlists");
// Create views to replace our old tables
db.execSQL("CREATE VIEW images AS SELECT _id," + IMAGE_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_IMAGE + ";");
// audio_meta will be created below for schema 100
// db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv99 +
// " FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
// + FileColumns.MEDIA_TYPE_AUDIO + ";");
db.execSQL("CREATE VIEW video AS SELECT _id," + VIDEO_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_VIDEO + ";");
if (!internal) {
db.execSQL("CREATE VIEW audio_playlists AS SELECT _id," + PLAYLIST_COLUMNS +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_PLAYLIST + ";");
}
// update the image_id column in the thumbnails table.
db.execSQL("UPDATE thumbnails SET image_id = (SELECT _id FROM files "
+ "WHERE files.old_id = thumbnails.image_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_IMAGE + ");");
if (!internal) {
// update audio_id in the audio_genres_map and audio_playlists_map tables.
db.execSQL("UPDATE audio_genres_map SET audio_id = (SELECT _id FROM files "
+ "WHERE files.old_id = audio_genres_map.audio_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_AUDIO + ");");
db.execSQL("UPDATE audio_playlists_map SET audio_id = (SELECT _id FROM files "
+ "WHERE files.old_id = audio_playlists_map.audio_id "
+ "AND files.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + ");");
}
// update video_id in the videothumbnails table.
db.execSQL("UPDATE videothumbnails SET video_id = (SELECT _id FROM files "
+ "WHERE files.old_id = videothumbnails.video_id AND files.media_type = "
+ FileColumns.MEDIA_TYPE_VIDEO + ");");
// update indices to work on the files table
db.execSQL("DROP INDEX IF EXISTS title_idx");
db.execSQL("DROP INDEX IF EXISTS album_id_idx");
db.execSQL("DROP INDEX IF EXISTS image_bucket_index");
db.execSQL("DROP INDEX IF EXISTS video_bucket_index");
db.execSQL("DROP INDEX IF EXISTS sort_index");
db.execSQL("DROP INDEX IF EXISTS titlekey_index");
db.execSQL("DROP INDEX IF EXISTS artist_id_idx");
db.execSQL("CREATE INDEX title_idx ON files(title);");
db.execSQL("CREATE INDEX album_id_idx ON files(album_id);");
db.execSQL("CREATE INDEX bucket_index ON files(bucket_id, datetaken);");
db.execSQL("CREATE INDEX sort_index ON files(datetaken ASC, _id ASC);");
db.execSQL("CREATE INDEX titlekey_index ON files(title_key);");
db.execSQL("CREATE INDEX artist_id_idx ON files(artist_id);");
// Recreate triggers for our obsolete tables on the new files table
db.execSQL("DROP TRIGGER IF EXISTS images_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_meta_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS video_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_playlists_cleanup");
db.execSQL("DROP TRIGGER IF EXISTS audio_delete");
db.execSQL("CREATE TRIGGER IF NOT EXISTS images_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_IMAGE + " " +
"BEGIN " +
"DELETE FROM thumbnails WHERE image_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS video_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_VIDEO + " " +
"BEGIN " +
"SELECT _DELETE_FILE(old._data);" +
"END");
if (!internal) {
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_meta_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_AUDIO + " " +
"BEGIN " +
"DELETE FROM audio_genres_map WHERE audio_id = old._id;" +
"DELETE FROM audio_playlists_map WHERE audio_id = old._id;" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_playlists_cleanup DELETE ON files " +
"WHEN old.media_type = " + FileColumns.MEDIA_TYPE_PLAYLIST + " " +
"BEGIN " +
"DELETE FROM audio_playlists_map WHERE playlist_id = old._id;" +
"SELECT _DELETE_FILE(old._data);" +
"END");
db.execSQL("CREATE TRIGGER IF NOT EXISTS audio_delete INSTEAD OF DELETE ON audio " +
"BEGIN " +
"DELETE from files where _id=old._id;" +
"DELETE from audio_playlists_map where audio_id=old._id;" +
"DELETE from audio_genres_map where audio_id=old._id;" +
"END");
}
}
if (fromVersion < 100) {
db.execSQL("ALTER TABLE files ADD COLUMN album_artist TEXT;");
db.execSQL("DROP VIEW IF EXISTS audio_meta;");
db.execSQL("CREATE VIEW audio_meta AS SELECT _id," + AUDIO_COLUMNSv100 +
" FROM files WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_AUDIO + ";");
db.execSQL("UPDATE files SET date_modified=0 WHERE " + FileColumns.MEDIA_TYPE + "="
+ FileColumns.MEDIA_TYPE_AUDIO + ";");
}
sanityCheck(db, fromVersion);
}
|
diff --git a/src/main/java/org/jasig/ssp/web/api/reference/SelfHelpGuideQuestionController.java b/src/main/java/org/jasig/ssp/web/api/reference/SelfHelpGuideQuestionController.java
index bf05583c5..be7f5294b 100644
--- a/src/main/java/org/jasig/ssp/web/api/reference/SelfHelpGuideQuestionController.java
+++ b/src/main/java/org/jasig/ssp/web/api/reference/SelfHelpGuideQuestionController.java
@@ -1,106 +1,106 @@
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.ssp.web.api.reference;
import java.util.ArrayList;
import org.jasig.ssp.factory.TOFactory;
import org.jasig.ssp.factory.reference.SelfHelpGuideQuestionTOFactory;
import org.jasig.ssp.model.ObjectStatus;
import org.jasig.ssp.model.reference.SelfHelpGuideQuestion;
import org.jasig.ssp.security.permissions.Permission;
import org.jasig.ssp.service.AuditableCrudService;
import org.jasig.ssp.service.reference.SelfHelpGuideQuestionService;
import org.jasig.ssp.transferobject.PagedResponse;
import org.jasig.ssp.transferobject.reference.SelfHelpGuideQuestionTO;
import org.jasig.ssp.util.sort.PagingWrapper;
import org.jasig.ssp.util.sort.SortingAndPaging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/1/selfHelpGuides/selfHelpGuideQuestions")
public class SelfHelpGuideQuestionController
extends
AbstractAuditableReferenceController<SelfHelpGuideQuestion, SelfHelpGuideQuestionTO> {
@Autowired
protected transient SelfHelpGuideQuestionService service;
@Override
protected AuditableCrudService<SelfHelpGuideQuestion> getService() {
return service;
}
@Autowired
protected transient SelfHelpGuideQuestionTOFactory factory;
@Override
protected TOFactory<SelfHelpGuideQuestionTO, SelfHelpGuideQuestion> getFactory() {
return factory;
}
protected SelfHelpGuideQuestionController() {
super(SelfHelpGuideQuestion.class, SelfHelpGuideQuestionTO.class);
}
private static final Logger LOGGER = LoggerFactory
.getLogger(SelfHelpGuideQuestionController.class);
@Override
protected Logger getLogger() {
return LOGGER;
}
@PreAuthorize(Permission.SECURITY_REFERENCE_WRITE)
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody
PagedResponse<SelfHelpGuideQuestionTO> getAllForParent(
final @RequestParam(required = false) String selfReferenceGuideId
) {
if(selfReferenceGuideId == null || "".equals(selfReferenceGuideId))
{
return new PagedResponse<SelfHelpGuideQuestionTO>(true,0L,new ArrayList<SelfHelpGuideQuestionTO>());
}
final PagingWrapper<SelfHelpGuideQuestion> data =service.getAllForParent(
- SortingAndPaging.createForSingleSort(
+ SortingAndPaging.createForSingleSortWithPaging(
ObjectStatus.ACTIVE , null,
null, null, null, "questionNumber"),selfReferenceGuideId);
PagedResponse<SelfHelpGuideQuestionTO> pagedResponse = new PagedResponse<SelfHelpGuideQuestionTO>(true, data.getResults(), getFactory()
.asTOList(data.getRows()));
return pagedResponse;
}
@Override
@PreAuthorize(Permission.SECURITY_PERSON_READ)
@RequestMapping
public @ResponseBody
PagedResponse<SelfHelpGuideQuestionTO> getAll(ObjectStatus status,
Integer start, Integer limit, String sort, String sortDirection) {
return super.getAll(status, start, limit, sort, sortDirection);
}
}
| true | true | PagedResponse<SelfHelpGuideQuestionTO> getAllForParent(
final @RequestParam(required = false) String selfReferenceGuideId
) {
if(selfReferenceGuideId == null || "".equals(selfReferenceGuideId))
{
return new PagedResponse<SelfHelpGuideQuestionTO>(true,0L,new ArrayList<SelfHelpGuideQuestionTO>());
}
final PagingWrapper<SelfHelpGuideQuestion> data =service.getAllForParent(
SortingAndPaging.createForSingleSort(
ObjectStatus.ACTIVE , null,
null, null, null, "questionNumber"),selfReferenceGuideId);
PagedResponse<SelfHelpGuideQuestionTO> pagedResponse = new PagedResponse<SelfHelpGuideQuestionTO>(true, data.getResults(), getFactory()
.asTOList(data.getRows()));
return pagedResponse;
}
| PagedResponse<SelfHelpGuideQuestionTO> getAllForParent(
final @RequestParam(required = false) String selfReferenceGuideId
) {
if(selfReferenceGuideId == null || "".equals(selfReferenceGuideId))
{
return new PagedResponse<SelfHelpGuideQuestionTO>(true,0L,new ArrayList<SelfHelpGuideQuestionTO>());
}
final PagingWrapper<SelfHelpGuideQuestion> data =service.getAllForParent(
SortingAndPaging.createForSingleSortWithPaging(
ObjectStatus.ACTIVE , null,
null, null, null, "questionNumber"),selfReferenceGuideId);
PagedResponse<SelfHelpGuideQuestionTO> pagedResponse = new PagedResponse<SelfHelpGuideQuestionTO>(true, data.getResults(), getFactory()
.asTOList(data.getRows()));
return pagedResponse;
}
|
diff --git a/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/HostedSiteServlet.java b/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/HostedSiteServlet.java
index ae81454a..3ab3086f 100644
--- a/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/HostedSiteServlet.java
+++ b/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/HostedSiteServlet.java
@@ -1,369 +1,363 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 IBM Corporation and others.
* 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.orion.internal.server.hosting;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.*;
import org.eclipse.jetty.servlets.ProxyServlet;
import org.eclipse.orion.internal.server.servlets.Activator;
import org.eclipse.orion.internal.server.servlets.ServletResourceHandler;
import org.eclipse.orion.internal.server.servlets.file.ServletFileStoreHandler;
import org.eclipse.orion.internal.server.servlets.hosting.IHostedSite;
import org.eclipse.orion.internal.server.servlets.workspace.WebProject;
import org.eclipse.orion.internal.server.servlets.workspace.WebWorkspace;
import org.eclipse.orion.internal.server.servlets.workspace.authorization.AuthorizationService;
import org.eclipse.orion.server.core.LogHelper;
import org.eclipse.orion.server.core.ServerStatus;
import org.eclipse.orion.server.servlets.OrionServlet;
import org.eclipse.osgi.util.NLS;
import org.json.JSONException;
/**
* Handles requests for URIs that are part of a running hosted site.
*/
public class HostedSiteServlet extends OrionServlet {
static class LocationHeaderServletResponseWrapper extends HttpServletResponseWrapper {
private static final String LOCATION = "Location";
private HttpServletRequest request;
private IHostedSite site;
public LocationHeaderServletResponseWrapper(HttpServletRequest request, HttpServletResponse response, IHostedSite site) {
super(response);
this.request = request;
this.site = site;
}
private String mapLocation(String location) {
Map<String, List<String>> mappings = site.getMappings();
String bestMatch = "";
String prefix = null;
for (Iterator<Entry<String, List<String>>> iterator = mappings.entrySet().iterator(); iterator.hasNext();) {
Entry<String, List<String>> entry = iterator.next();
List<String> candidates = entry.getValue();
for (Iterator<String> candidateIt = candidates.iterator(); candidateIt.hasNext();) {
String candidate = candidateIt.next();
if (location.startsWith(candidate) && candidate.length() > bestMatch.length()) {
bestMatch = candidate;
prefix = entry.getKey();
}
}
}
if (prefix != null) {
String suffix = location.substring(bestMatch.length());
String separator = suffix.length() > 0 && !prefix.endsWith("/") && !suffix.startsWith("/") ? "/" : "";
String reverseMappedPath = prefix + separator + suffix;
try {
URI pathlessRequestURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), null, null, null);
return pathlessRequestURI.toString() + reverseMappedPath;
} catch (URISyntaxException t) {
// best effort
System.err.println(t);
}
}
return location;
}
@Override
public void addHeader(String name, String value) {
if (name.equals(LOCATION)) {
String newLocation = mapLocation(value.trim());
super.addHeader(name, newLocation);
} else {
super.addHeader(name, value);
}
}
@Override
public void setHeader(String name, String value) {
if (name.equals(LOCATION)) {
String newLocation = mapLocation(value.trim());
super.setHeader(name, newLocation);
} else {
super.setHeader(name, value);
}
}
}
private static final long serialVersionUID = 1L;
private static final String WORKSPACE_SERVLET_ALIAS = "/workspace"; //$NON-NLS-1$
private static final String FILE_SERVLET_ALIAS = "/file"; //$NON-NLS-1$
// FIXME these variables are copied from fileservlet
private ServletResourceHandler<IFileStore> fileSerializer;
private final URI rootStoreURI;
public HostedSiteServlet() {
rootStoreURI = Activator.getDefault().getRootLocationURI();
}
@Override
public void init() throws ServletException {
super.init();
fileSerializer = new ServletFileStoreHandler(rootStoreURI, getStatusHandler(), getServletContext());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Handled by service()
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Handled by service()
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Handled by service()
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Handled by service()
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
traceRequest(req);
String pathInfoString = req.getPathInfo();
IPath pathInfo = new Path(null /*don't parse host:port as device*/, pathInfoString == null ? "" : pathInfoString); //$NON-NLS-1$
if (pathInfo.segmentCount() > 0) {
String hostedHost = pathInfo.segment(0);
IHostedSite site = HostingActivator.getDefault().getHostingService().get(hostedHost);
if (site != null) {
IPath path = pathInfo.removeFirstSegments(1);
IPath contextPath = new Path(req.getContextPath());
IPath contextlessPath = path.makeRelativeTo(contextPath).makeAbsolute();
URI[] mappedPaths;
try {
mappedPaths = getMapped(site, contextlessPath, req.getQueryString());
} catch (URISyntaxException e) {
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Could not create target URI ", e));
return;
}
if (mappedPaths != null) {
serve(req, resp, site, mappedPaths);
} else {
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("No mappings matched {0}", path), null));
}
} else {
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
String msg = NLS.bind("Hosted site {0} is stopped", hostedHost);
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
}
} else {
super.doGet(req, resp);
}
}
/**
* Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
* Paths are ordered from most to least specific match.
* @param site The hosted site.
* @param pathInfo Path to be rewritten.
* @param queryString
* @return The rewritten path. May be either:<ul>
* <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code></li>
* <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code></li>
* </ul>
* @return The rewritten paths.
* @throws URISyntaxException
*/
private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString) throws URISyntaxException {
final Map<String, List<String>> map = site.getMappings();
final IPath originalPath = pathInfo;
IPath path = originalPath.removeTrailingSeparator();
List<URI> uris = new ArrayList<URI>();
String rest = null;
final int count = path.segmentCount();
for (int i = 0; i <= count; i++) {
List<String> base = map.get(path.toString());
if (base != null) {
rest = originalPath.removeFirstSegments(count - i).toString();
for (int j = 0; j < base.size(); j++) {
URI uri = (rest.equals("") || rest.equals("/")) ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
uris.add(createUri(uri, queryString));
}
}
path = path.removeLastSegments(1);
}
if (uris.size() == 0)
// No mapping for /
return null;
else
return uris.toArray(new URI[uris.size()]);
}
// Returns a copy of uri with queryString giving the query component. The query is not decoded.
private URI createUri(URI uri, String queryString) throws URISyntaxException {
String queryPart = queryString == null ? "" : "?" + queryString; //$NON-NLS-1$ //$NON-NLS-2$
String fragmentPart = uri.getFragment() == null ? "" : "#" + uri.getRawFragment();//$NON-NLS-1$ //$NON-NLS-2$
URI pathonly = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, null);
StringBuilder buf = new StringBuilder();
buf.append(pathonly.toString()).append(queryPart).append(fragmentPart);
return new URI(buf.toString());
}
private void serve(HttpServletRequest req, HttpServletResponse resp, IHostedSite site, URI[] mappedURIs) throws ServletException, IOException {
for (int i = 0; i < mappedURIs.length; i++) {
URI uri = mappedURIs[i];
// Bypass a 404 if any workspace or remote paths remain to be checked.
boolean failEarlyOn404 = i + 1 < mappedURIs.length;
if (uri.getScheme() == null) {
if ("GET".equals(req.getMethod())) { //$NON-NLS-1$
if (serveOrionFile(req, resp, site, new Path(uri.getPath()), failEarlyOn404))
return;
} else {
String message = "Only GET method is supported for workspace paths";
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_METHOD_NOT_ALLOWED, NLS.bind(message, mappedURIs), null));
return;
}
} else {
if (proxyRemotePath(req, new LocationHeaderServletResponseWrapper(req, resp, site), uri, failEarlyOn404))
return;
}
}
}
// returns true if the request has been served, false if not (only if failEarlyOn404 is true)
private boolean serveOrionFile(HttpServletRequest req, HttpServletResponse resp, IHostedSite site, IPath path, boolean failEarlyOn404) throws ServletException {
String userId = site.getUserId();
- String workspaceId = site.getWorkspaceId();
- String workspaceUri = WORKSPACE_SERVLET_ALIAS + "/" + workspaceId; //$NON-NLS-1$
String fileURI = FILE_SERVLET_ALIAS + path.toString();
boolean allow = false;
- // Check that user who launched the hosted site really has access to the workspace
+ // Check that user who launched the hosted site really has access to the files
try {
- if (AuthorizationService.checkRights(userId, workspaceUri, "GET")) { //$NON-NLS-1$
- boolean fileMatch = AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$
- boolean dirMatch = fileURI.endsWith("/") && AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$ //$NON-NLS-2$
- if (fileMatch || dirMatch) {
- allow = true;
- } else {
- handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("No rights to access {0}", fileURI), null));
- }
+ boolean fileMatch = AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$
+ boolean dirMatch = fileURI.endsWith("/") && AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (fileMatch || dirMatch) {
+ allow = true;
} else {
- handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("No rights to access {0}", workspaceUri), null));
+ handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("No rights to access {0}", fileURI), null));
}
} catch (JSONException e) {
throw new ServletException(e);
}
if (allow) {
// FIXME: this code is copied from NewFileServlet, fix it
// start copied
String pathInfo = path.toString();
IPath filePath = pathInfo == null ? Path.ROOT : new Path(pathInfo);
IFileStore file = tempGetFileStore(filePath);
if (file == null || !file.fetchInfo().exists()) {
if (failEarlyOn404) {
return false;
}
handleException(resp, new ServerStatus(IStatus.ERROR, 404, NLS.bind("File not found: {0}", filePath), null));
return true;
}
if (fileSerializer.handleRequest(req, resp, file)) {
//return;
}
// end copied
if (file != null) {
addEditHeaders(resp, site, path);
addContentTypeHeader(resp, file.getName());
}
}
return true;
}
private void addEditHeaders(HttpServletResponse resp, IHostedSite site, IPath path) {
resp.addHeader("X-Edit-Server", site.getEditServerUrl() + "/edit/edit.html#"); //$NON-NLS-1$ //$NON-NLS-2$
resp.addHeader("X-Edit-Token", FILE_SERVLET_ALIAS + path.toString()); //$NON-NLS-1$
}
private void addContentTypeHeader(HttpServletResponse resp, String filename) {
if (filename != null) {
String mimeType = getServletContext().getMimeType(filename);
if (mimeType != null)
resp.addHeader("Content-Type", mimeType);
}
}
// temp code for grabbing files from filesystem
protected IFileStore tempGetFileStore(IPath path) {
//path format is /workspaceId/projectName/[suffix]
if (path.segmentCount() <= 1)
return null;
WebWorkspace workspace = WebWorkspace.fromId(path.segment(0));
WebProject project = workspace.getProjectByName(path.segment(1));
if (project == null)
return null;
try {
return project.getProjectStore().getFileStore(path.removeFirstSegments(2));
} catch (CoreException e) {
LogHelper.log(new Status(IStatus.WARNING, Activator.PI_SERVER_SERVLETS, 1, NLS.bind("An error occurred when getting file store for path {0}", path), e));
// fallback and return null
}
return null;
}
/**
* @return true if the request was served.
*/
private boolean proxyRemotePath(HttpServletRequest req, HttpServletResponse resp, URI remoteURI, boolean failEarlyOn404) throws IOException, ServletException, UnknownHostException {
try {
return proxyRemoteUrl(req, resp, new URL(remoteURI.toString()), failEarlyOn404);
} catch (MalformedURLException e) {
String message = NLS.bind("Malformed remote URL: {0}", remoteURI.toString());
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, message, e));
} catch (UnknownHostException e) {
String message = NLS.bind("Unknown host {0}", e.getMessage());
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, message, e));
} catch (Exception e) {
String message = NLS.bind("An error occurred while retrieving {0}", remoteURI.toString());
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message, e));
}
return true;
}
/**
* @return true if the request was served.
*/
private boolean proxyRemoteUrl(HttpServletRequest req, HttpServletResponse resp, final URL mappedURL, boolean failEarlyOn404) throws IOException, ServletException, UnknownHostException {
ProxyServlet proxy = new RemoteURLProxyServlet(mappedURL, failEarlyOn404);
proxy.init(getServletConfig());
try {
// TODO: May want to avoid console noise from 4xx response codes?
traceRequest(req);
try {
proxy.service(req, resp);
} catch (NotFoundException ex) {
// This exception is only thrown in the "fail early on 404" case, in which case
// no output was written and we didn't serve the request.
return false;
}
} finally {
proxy.destroy();
}
// We served this request
return true;
}
}
| false | true | private boolean serveOrionFile(HttpServletRequest req, HttpServletResponse resp, IHostedSite site, IPath path, boolean failEarlyOn404) throws ServletException {
String userId = site.getUserId();
String workspaceId = site.getWorkspaceId();
String workspaceUri = WORKSPACE_SERVLET_ALIAS + "/" + workspaceId; //$NON-NLS-1$
String fileURI = FILE_SERVLET_ALIAS + path.toString();
boolean allow = false;
// Check that user who launched the hosted site really has access to the workspace
try {
if (AuthorizationService.checkRights(userId, workspaceUri, "GET")) { //$NON-NLS-1$
boolean fileMatch = AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$
boolean dirMatch = fileURI.endsWith("/") && AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$ //$NON-NLS-2$
if (fileMatch || dirMatch) {
allow = true;
} else {
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("No rights to access {0}", fileURI), null));
}
} else {
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("No rights to access {0}", workspaceUri), null));
}
} catch (JSONException e) {
throw new ServletException(e);
}
if (allow) {
// FIXME: this code is copied from NewFileServlet, fix it
// start copied
String pathInfo = path.toString();
IPath filePath = pathInfo == null ? Path.ROOT : new Path(pathInfo);
IFileStore file = tempGetFileStore(filePath);
if (file == null || !file.fetchInfo().exists()) {
if (failEarlyOn404) {
return false;
}
handleException(resp, new ServerStatus(IStatus.ERROR, 404, NLS.bind("File not found: {0}", filePath), null));
return true;
}
if (fileSerializer.handleRequest(req, resp, file)) {
//return;
}
// end copied
if (file != null) {
addEditHeaders(resp, site, path);
addContentTypeHeader(resp, file.getName());
}
}
return true;
}
| private boolean serveOrionFile(HttpServletRequest req, HttpServletResponse resp, IHostedSite site, IPath path, boolean failEarlyOn404) throws ServletException {
String userId = site.getUserId();
String fileURI = FILE_SERVLET_ALIAS + path.toString();
boolean allow = false;
// Check that user who launched the hosted site really has access to the files
try {
boolean fileMatch = AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$
boolean dirMatch = fileURI.endsWith("/") && AuthorizationService.checkRights(userId, fileURI, "GET"); //$NON-NLS-1$ //$NON-NLS-2$
if (fileMatch || dirMatch) {
allow = true;
} else {
handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("No rights to access {0}", fileURI), null));
}
} catch (JSONException e) {
throw new ServletException(e);
}
if (allow) {
// FIXME: this code is copied from NewFileServlet, fix it
// start copied
String pathInfo = path.toString();
IPath filePath = pathInfo == null ? Path.ROOT : new Path(pathInfo);
IFileStore file = tempGetFileStore(filePath);
if (file == null || !file.fetchInfo().exists()) {
if (failEarlyOn404) {
return false;
}
handleException(resp, new ServerStatus(IStatus.ERROR, 404, NLS.bind("File not found: {0}", filePath), null));
return true;
}
if (fileSerializer.handleRequest(req, resp, file)) {
//return;
}
// end copied
if (file != null) {
addEditHeaders(resp, site, path);
addContentTypeHeader(resp, file.getName());
}
}
return true;
}
|
diff --git a/javanet/gnu/cajo/utils/extra/TransparentItemProxy.java b/javanet/gnu/cajo/utils/extra/TransparentItemProxy.java
index bdbcda60..17410afe 100644
--- a/javanet/gnu/cajo/utils/extra/TransparentItemProxy.java
+++ b/javanet/gnu/cajo/utils/extra/TransparentItemProxy.java
@@ -1,173 +1,173 @@
package gnu.cajo.utils.extra;
import gnu.cajo.invoke.*;
import java.lang.reflect.*;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;
import java.net.MalformedURLException;
import java.lang.reflect.InvocationTargetException;
/*
* Item Transparent Dynamic Proxy (requires JRE 1.3+)
* Copyright (c) 2005 John Catherino
* The cajo project: https://cajo.dev.java.net
*
* For issues or suggestions mailto:[email protected]
*
* This file TransparentItemProxy.java is part of the cajo library.
*
* The cajo library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation, at version 3 of the licence, or (at your
* option) any later version.
*
* Th cajo library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public Licence for more details.
*
* You should have received a copy of the GNU Lesser General Public Licence
* along with this library. If not, see http://www.gnu.org/licenses/lgpl.html
*/
/**
* This class creates an object, representing a server item. The returned
* object will implement a list of interfaces defined by the client. The
* interfaces are completely independent of interfaces the server object
* implements, if any; they are simply logical groupings, of interest solely
* to the client. The interface methods <i>'should'</i> declare that they
* throw <tt>java.lang.Exception</tt>: However, the Java dynamic proxy
* mechanism very <i>doubiously</i> allows this to be optional.
*
* <p>Clients can dynamically create an item wrapper classes implementing
* <i>any</i> combination of interfaces. Combining interfaces provides a very
* important second order of abstraction. Whereas an interface is considered
* to be a grouping of functionality; the <i>'purpose'</i> of an item, could
* be determined by the group of interfaces it implements. Clients can
* customise the way they use remote items as a function of the interfaces
* implemented.
*
* <p>If an item can be best represented with a single interface, it would be
* well to consider using a {@link Wrapper Wrapper} class instead. It is
* conceptually much simpler.
*
* <p><i><u>Note</u>:</i> Unfortunately, this class only works with JREs 1.3
* and higher. Therefore I was reluctant to include it in the official
* codebase. However, some very convincing <a href=https://cajo.dev.java.net/servlets/ProjectForumMessageView?forumID=475&messageID=10199>
* discussion</a> in the cajo project Developer's forum, with project member
* Bharavi Gade, caused me to reconsider.
*
* <p><i><u>Also note</u>:</i> The three fundamental object methods; hashCode,
* equals, and toString, are performed locally. This is because the remote
* invocation could fail, most unintuitively. This is just to make the class
* operation much more intuitive.
*
* @version 1.1, 11-Nov-05 Support multiple interfaces
* @author John Catherino
*/
public final class TransparentItemProxy implements InvocationHandler {
private final Object item;
private final Object name;
private TransparentItemProxy(Object item) {
this.item = item;
Object temp = null;
try { temp = Remote.invoke(item, "toString", null); }
catch(Exception x) {
throw new IllegalArgumentException(x.getLocalizedMessage());
}
name = temp;
}
/**
* This method, inherited from InvocationHandler, simply passes all object
* method invocations on to the remote object, automatically and
* transparently. This allows the local runtime to perform remote item
* invocations, while appearing syntactically identical to local ones.
* @param proxy The local object on which the method was invoked, it is
* <i>ignored</i> in this context.
* @param method The method to invoke on the object, in this case the
* server item.
* @param args The arguments to provide to the method, if any.
* @return The resulting data from the method invocation, if any.
* @throws java.rmi.RemoteException For network communication related
* reasons.
* @throws NoSuchMethodException If no matching method can be found
* on the server item.
* @throws Exception If the server item rejected the invocation, for
* application specific reasons. The cause of the exception will be
* automatically unpacked from the internally resulting
* java.lang.reflect.InvocationTargetException, to provide the calling
* code with the actual exception resulting from the method invocation.
* Special thanks to Petr Stepan for pointing out this improvement, and
* providing a <a href=http://benpryor.com/blog/index.php?/archives/24-Java-Dynamic-Proxies-and-InvocationTargetException.html>
* link</a> to the discussion.
* @throws Throwable For some <i>very</i> unlikely reasons, not outlined
* above. (required, sorry)
*/
public Object invoke(Object proxy, Method method, Object args[])
throws Throwable {
try {
String name = method.getName();
if (name.equals("equals")) { // perform shallow equals...
return args[0] != null && args[0].equals(this) ?
Boolean.TRUE : Boolean.FALSE;
} else if (name.equals("hashCode")) // shallow hashCode too...
return new Integer(this.hashCode());
else if (name.equals("toString")) // shallow toString too...
- return name;
+ return this.name;
else return Remote.invoke(item, name, args);
} catch(InvocationTargetException x) { throw x.getTargetException(); }
}
/**
* This generates a class definition for a remote object reference at
* runtime, and returns a local object instance. The resulting dynamic
* proxy object will implement all the interfaces provided.
* @param item A reference to a remote server object.
* @param interfaces The list of interface classes for the dynamic proxy
* to implement. Typically, these are provided thus; <tt>new Class[] {
* Interface1.class, Interface2.class, ... }</tt>
* @return A reference to the server item, wrapped in the local object,
* created at runtime. It can then be typecast into any of the interfaces,
* as needed by the client.
*/
public static Object getItem(Object item, Class interfaces[]) {
return Proxy.newProxyInstance(
interfaces[0].getClassLoader(), interfaces,
new TransparentItemProxy(item)
);
}
/**
* This method fetches a server item reference, generates a class
* definition for it at runtime, and returns a local object instance.
* The resulting dynamic proxy object will implement all the interfaces
* provided. Technically, it invokes the other getItem method, after
* fetching the object reference from the remote JVM specified.
* @param url The URL where to get the object: //[host][:port]/[name].
* The host, port, and name, are all optional. If missing the host is
* presumed local, the port 1099, and the name "main". If the URL is
* null, it will be assumed to be ///.
* @param interfaces The list of interface classes for the dynamic proxy
* to implement. Typically, these are provided thus; <tt>new Class[] {
* Interface1.class, Interface2.class, ... }</tt>
* @return A reference to the server item, wrapped in the object created
* at runtime, implementing all of the interfaces provided. It can then
* be typecast into any of the interfaces, as needed by the client.
* @throws RemoteException if the remote registry could not be reached.
* @throws NotBoundException if the requested name is not in the registry.
* @throws IOException if the zedmob format is invalid.
* @throws ClassNotFoundException if a proxy was sent to the VM, and
* proxy hosting was not enabled.
* @throws InstantiationException when the URL specifies a class name
* which cannot be instantiated at runtime.
* @throws IllegalAccessException when the url specifies a class name
* and it does not support a no-arg constructor.
* @throws MalformedURLException if the URL is not in the format explained
*/
public static Object getItem(String url, Class interfaces[])
throws RemoteException, NotBoundException, IOException,
ClassNotFoundException, InstantiationException, IllegalAccessException,
MalformedURLException {
return getItem(Remote.getItem(url), interfaces);
}
}
| true | true | public Object invoke(Object proxy, Method method, Object args[])
throws Throwable {
try {
String name = method.getName();
if (name.equals("equals")) { // perform shallow equals...
return args[0] != null && args[0].equals(this) ?
Boolean.TRUE : Boolean.FALSE;
} else if (name.equals("hashCode")) // shallow hashCode too...
return new Integer(this.hashCode());
else if (name.equals("toString")) // shallow toString too...
return name;
else return Remote.invoke(item, name, args);
} catch(InvocationTargetException x) { throw x.getTargetException(); }
}
| public Object invoke(Object proxy, Method method, Object args[])
throws Throwable {
try {
String name = method.getName();
if (name.equals("equals")) { // perform shallow equals...
return args[0] != null && args[0].equals(this) ?
Boolean.TRUE : Boolean.FALSE;
} else if (name.equals("hashCode")) // shallow hashCode too...
return new Integer(this.hashCode());
else if (name.equals("toString")) // shallow toString too...
return this.name;
else return Remote.invoke(item, name, args);
} catch(InvocationTargetException x) { throw x.getTargetException(); }
}
|
diff --git a/src/game/Driver.java b/src/game/Driver.java
index 15d2b2b..4dfdaf8 100644
--- a/src/game/Driver.java
+++ b/src/game/Driver.java
@@ -1,69 +1,69 @@
package game;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
/////////// Makes new Person with name a ///////////
Scanner s = new Scanner(System.in);
System.out.println("Welcome to Decisions");
System.out.println("What is your name?");
String a = s.nextLine();
Person p = new Person(a);
/////////// Makes new ChoiceStorage object cs ///////////
ChoiceStorage cs = new ChoiceStorage();
/////////// Makes new Choice object c ///////////
- Choice c = new Choice(p);
+ Choice c = cs.getNextChoice(p);
/////////// Makes new Outcome object o ///////////
Outcome o = new Outcome(true, c.getCharismaReq(), c.getIntelligenceReq(), c.getStrengthReq(), c.getWealthReq(), c.getConfindenceReq(), c.getAgeReq());
/////////// Outputs stats generated randomly upon creation of Person p ///////////
System.out.println("These are your stats:");
System.out.println(p.getName() + ":");
System.out.println("You are male");
System.out.println("You are currently a child");
System.out.println("Charisma = " + p.getCharisma());
System.out.println("Intelligence = " + p.getIntelligence());
System.out.println("Strength = " + p.getStrength());
System.out.println("Wealth = " + p.getWealth());
System.out.println("Confidence = " + p.getConfidence());
/////////// Runs the Game ///////////
while (p.isAlive() == true){
c.print(); // Outputs the choice to the user
int x = s.nextInt(); // Takes in the user's input and stores it in x
c.execute(x); // Makes decision with x
o.updateAttributes(p);
c = cs.getNextChoice(p); // Makes c the next choice
}
/////////// Prints Final stats ///////////
System.out.println("You Died.");
System.out.println("These are your final stats:");
System.out.println(p.getName() + ":");
System.out.println("Charisma = " + p.getCharisma());
System.out.println("Intelligence = " + p.getIntelligence());
System.out.println("Strength = " + p.getStrength());
System.out.println("Wealth = " + p.getWealth());
System.out.println("Confidence = " + p.getConfidence());
}
}
| true | true | public static void main(String[] args) {
/////////// Makes new Person with name a ///////////
Scanner s = new Scanner(System.in);
System.out.println("Welcome to Decisions");
System.out.println("What is your name?");
String a = s.nextLine();
Person p = new Person(a);
/////////// Makes new ChoiceStorage object cs ///////////
ChoiceStorage cs = new ChoiceStorage();
/////////// Makes new Choice object c ///////////
Choice c = new Choice(p);
/////////// Makes new Outcome object o ///////////
Outcome o = new Outcome(true, c.getCharismaReq(), c.getIntelligenceReq(), c.getStrengthReq(), c.getWealthReq(), c.getConfindenceReq(), c.getAgeReq());
/////////// Outputs stats generated randomly upon creation of Person p ///////////
System.out.println("These are your stats:");
System.out.println(p.getName() + ":");
System.out.println("You are male");
System.out.println("You are currently a child");
System.out.println("Charisma = " + p.getCharisma());
System.out.println("Intelligence = " + p.getIntelligence());
System.out.println("Strength = " + p.getStrength());
System.out.println("Wealth = " + p.getWealth());
System.out.println("Confidence = " + p.getConfidence());
/////////// Runs the Game ///////////
while (p.isAlive() == true){
c.print(); // Outputs the choice to the user
int x = s.nextInt(); // Takes in the user's input and stores it in x
c.execute(x); // Makes decision with x
o.updateAttributes(p);
c = cs.getNextChoice(p); // Makes c the next choice
}
/////////// Prints Final stats ///////////
System.out.println("You Died.");
System.out.println("These are your final stats:");
System.out.println(p.getName() + ":");
System.out.println("Charisma = " + p.getCharisma());
System.out.println("Intelligence = " + p.getIntelligence());
System.out.println("Strength = " + p.getStrength());
System.out.println("Wealth = " + p.getWealth());
System.out.println("Confidence = " + p.getConfidence());
}
| public static void main(String[] args) {
/////////// Makes new Person with name a ///////////
Scanner s = new Scanner(System.in);
System.out.println("Welcome to Decisions");
System.out.println("What is your name?");
String a = s.nextLine();
Person p = new Person(a);
/////////// Makes new ChoiceStorage object cs ///////////
ChoiceStorage cs = new ChoiceStorage();
/////////// Makes new Choice object c ///////////
Choice c = cs.getNextChoice(p);
/////////// Makes new Outcome object o ///////////
Outcome o = new Outcome(true, c.getCharismaReq(), c.getIntelligenceReq(), c.getStrengthReq(), c.getWealthReq(), c.getConfindenceReq(), c.getAgeReq());
/////////// Outputs stats generated randomly upon creation of Person p ///////////
System.out.println("These are your stats:");
System.out.println(p.getName() + ":");
System.out.println("You are male");
System.out.println("You are currently a child");
System.out.println("Charisma = " + p.getCharisma());
System.out.println("Intelligence = " + p.getIntelligence());
System.out.println("Strength = " + p.getStrength());
System.out.println("Wealth = " + p.getWealth());
System.out.println("Confidence = " + p.getConfidence());
/////////// Runs the Game ///////////
while (p.isAlive() == true){
c.print(); // Outputs the choice to the user
int x = s.nextInt(); // Takes in the user's input and stores it in x
c.execute(x); // Makes decision with x
o.updateAttributes(p);
c = cs.getNextChoice(p); // Makes c the next choice
}
/////////// Prints Final stats ///////////
System.out.println("You Died.");
System.out.println("These are your final stats:");
System.out.println(p.getName() + ":");
System.out.println("Charisma = " + p.getCharisma());
System.out.println("Intelligence = " + p.getIntelligence());
System.out.println("Strength = " + p.getStrength());
System.out.println("Wealth = " + p.getWealth());
System.out.println("Confidence = " + p.getConfidence());
}
|
diff --git a/src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/java/ConvertPPTXToXPS.java b/src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/java/ConvertPPTXToXPS.java
index 634c1b3..fda7cb5 100644
--- a/src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/java/ConvertPPTXToXPS.java
+++ b/src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/java/ConvertPPTXToXPS.java
@@ -1,47 +1,47 @@
/*
* Copyright 2001-2013 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Slides. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package programmersguide.powerpoint2007.workingwithpresentationex.convertpptxtoxps.java;
import com.aspose.slides.*;
public class ConvertPPTXToXPS
{
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = "src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/data/";
//Instantiate a PresentationEx object that represents a PPTX file
PresentationEx pres = new PresentationEx(dataDir + "demo.pptx");
// 1.
//Saving the presentation to TIFF document
pres.save(dataDir + "output.xps", com.aspose.slides.SaveFormat.Xps);
// 2.
// Save with XpsOptions
//Instantiate the XpsOptions class
com.aspose.slides.XpsOptions opts = new com.aspose.slides.XpsOptions();
//Save MetaFiles as PNG
opts.setSaveMetafilesAsPng(true);
- //Save the prsentation to XPS document
- pres.save(dataDir + "outputXPSOptions.xps", com.aspose.slides.SaveFormat.Xps,opts);
+ //Save the presentation to XPS document
+ pres.save(dataDir + "outputWithXPSOptions.xps", com.aspose.slides.SaveFormat.Xps, opts);
// Status
System.out.println("PPTX to XPS conversion has been performed successfully.");
}
}
| true | true | public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = "src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/data/";
//Instantiate a PresentationEx object that represents a PPTX file
PresentationEx pres = new PresentationEx(dataDir + "demo.pptx");
// 1.
//Saving the presentation to TIFF document
pres.save(dataDir + "output.xps", com.aspose.slides.SaveFormat.Xps);
// 2.
// Save with XpsOptions
//Instantiate the XpsOptions class
com.aspose.slides.XpsOptions opts = new com.aspose.slides.XpsOptions();
//Save MetaFiles as PNG
opts.setSaveMetafilesAsPng(true);
//Save the prsentation to XPS document
pres.save(dataDir + "outputXPSOptions.xps", com.aspose.slides.SaveFormat.Xps,opts);
// Status
System.out.println("PPTX to XPS conversion has been performed successfully.");
}
| public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = "src/programmersguide/powerpoint2007/workingwithpresentationex/convertpptxtoxps/data/";
//Instantiate a PresentationEx object that represents a PPTX file
PresentationEx pres = new PresentationEx(dataDir + "demo.pptx");
// 1.
//Saving the presentation to TIFF document
pres.save(dataDir + "output.xps", com.aspose.slides.SaveFormat.Xps);
// 2.
// Save with XpsOptions
//Instantiate the XpsOptions class
com.aspose.slides.XpsOptions opts = new com.aspose.slides.XpsOptions();
//Save MetaFiles as PNG
opts.setSaveMetafilesAsPng(true);
//Save the presentation to XPS document
pres.save(dataDir + "outputWithXPSOptions.xps", com.aspose.slides.SaveFormat.Xps, opts);
// Status
System.out.println("PPTX to XPS conversion has been performed successfully.");
}
|
diff --git a/configuration/src/main/java/com/proofpoint/configuration/ConfigurationFactory.java b/configuration/src/main/java/com/proofpoint/configuration/ConfigurationFactory.java
index 95e18d027..cfd21b693 100644
--- a/configuration/src/main/java/com/proofpoint/configuration/ConfigurationFactory.java
+++ b/configuration/src/main/java/com/proofpoint/configuration/ConfigurationFactory.java
@@ -1,647 +1,647 @@
/*
* Copyright 2010 Proofpoint, 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.proofpoint.configuration;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.inject.Binding;
import com.google.inject.ConfigurationException;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.spi.DefaultElementVisitor;
import com.google.inject.spi.Element;
import com.google.inject.spi.Message;
import com.google.inject.spi.ProviderInstanceBinding;
import com.proofpoint.configuration.ConfigurationMetadata.AttributeMetadata;
import com.proofpoint.configuration.ConfigurationMetadata.InjectionPointMetaData;
import com.proofpoint.configuration.Problems.Monitor;
import org.apache.bval.jsr303.ApacheValidationProvider;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.proofpoint.configuration.ConfigurationMetadata.isConfigClass;
import static com.proofpoint.configuration.Problems.exceptionFor;
import static java.lang.String.format;
public final class ConfigurationFactory
{
private static final Validator VALIDATOR = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory().getValidator();
private final Map<String, String> properties;
private final Map<String, String> applicationDefaults;
private final Problems.Monitor monitor;
private final Set<String> unusedProperties = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Collection<String> initialErrors;
private final LoadingCache<Class<?>, ConfigurationMetadata<?>> metadataCache;
private final ConcurrentMap<ConfigurationProvider<?>, Object> instanceCache = new ConcurrentHashMap<>();
private final Set<String> usedProperties = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Set<ConfigurationProvider<?>> registeredProviders = Collections.newSetFromMap(new ConcurrentHashMap<ConfigurationProvider<?>, Boolean>());
public ConfigurationFactory(Map<String, String> properties)
{
this(properties, ImmutableMap.<String, String>of(), properties.keySet(), ImmutableList.<String>of(), Problems.NULL_MONITOR);
}
ConfigurationFactory(Map<String, String> properties, Map<String, String> applicationDefaults, Set<String> expectToUse, Collection<String> errors, final Monitor monitor)
{
this.monitor = monitor;
this.properties = ImmutableMap.copyOf(properties);
this.applicationDefaults = ImmutableMap.copyOf(applicationDefaults);
unusedProperties.addAll(expectToUse);
initialErrors = ImmutableList.copyOf(errors);
metadataCache = CacheBuilder.newBuilder().weakKeys().weakValues()
.build(new CacheLoader<Class<?>, ConfigurationMetadata<?>>()
{
@Override
public ConfigurationMetadata<?> load(Class<?> configClass)
{
return ConfigurationMetadata.getConfigurationMetadata(configClass, monitor);
}
});
}
public Map<String, String> getProperties()
{
return properties;
}
/**
* Marks the specified property as consumed.
*/
@Beta
public void consumeProperty(String property)
{
Preconditions.checkNotNull(property, "property is null");
usedProperties.add(property);
unusedProperties.remove(property);
}
@Deprecated
public Set<String> getUsedProperties()
{
return ImmutableSortedSet.copyOf(usedProperties);
}
Set<String> getUnusedProperties()
{
return ImmutableSortedSet.copyOf(unusedProperties);
}
Monitor getMonitor()
{
return monitor;
}
Collection<String> getInitialErrors()
{
return initialErrors;
}
/**
* Registers all configuration classes in the module so they can be part of configuration inspection.
*/
@Beta
public void registerConfigurationClasses(Module module)
{
registeredProviders.addAll(getAllProviders(module));
}
Iterable<ConfigurationProvider<?>> getConfigurationProviders()
{
return ImmutableList.copyOf(registeredProviders);
}
public <T> T build(Class<T> configClass)
{
return build(configClass, null).instance;
}
/**
* This is used by the configuration provider
*/
<T> T build(ConfigurationProvider<T> configurationProvider, WarningsMonitor warningsMonitor)
{
Preconditions.checkNotNull(configurationProvider, "configurationProvider");
registeredProviders.add(configurationProvider);
// check for a prebuilt instance
@SuppressWarnings("unchecked") T instance = (T) instanceCache.get(configurationProvider);
if (instance != null) {
return instance;
}
ConfigurationHolder<T> holder = build(configurationProvider.getConfigClass(), configurationProvider.getPrefix());
instance = holder.instance;
// inform caller about warnings
if (warningsMonitor != null) {
for (Message message : holder.problems.getWarnings()) {
warningsMonitor.onWarning(message.toString());
}
}
// add to instance cache
@SuppressWarnings("unchecked") T existingValue = (T) instanceCache.putIfAbsent(configurationProvider, instance);
// if key was already associated with a value, there was a
// creation race and we lost. Just use the winners' instance;
if (existingValue != null) {
return existingValue;
}
return instance;
}
<T> T buildDefaults(ConfigurationProvider<T> configurationProvider)
{
return build(configurationProvider.getConfigClass(), configurationProvider.getPrefix(), true, new Problems());
}
private <T> ConfigurationHolder<T> build(Class<T> configClass, String prefix)
{
Problems problems = new Problems(monitor);
final T instance = build(configClass, prefix, false, problems);
problems.throwIfHasErrors();
return new ConfigurationHolder<>(instance, problems);
}
private <T> T build(Class<T> configClass, String prefix, boolean isDefault, Problems problems)
{
if (configClass == null) {
throw new NullPointerException("configClass is null");
}
if (prefix == null) {
prefix = "";
} else if (!prefix.isEmpty()) {
prefix += ".";
}
@SuppressWarnings("unchecked") ConfigurationMetadata<T> configurationMetadata = (ConfigurationMetadata<T>) metadataCache.getUnchecked(configClass);
configurationMetadata.getProblems().throwIfHasErrors();
T instance = newInstance(configurationMetadata);
for (AttributeMetadata attribute : configurationMetadata.getAttributes().values()) {
try {
setConfigProperty(instance, attribute, prefix, isDefault, problems);
} catch (InvalidConfigurationException e) {
problems.addError(e.getCause(), e.getMessage());
}
}
if (isDefault) {
return instance;
}
// Check that none of the defunct properties are still in use
if (configClass.isAnnotationPresent(DefunctConfig.class)) {
for (String value : configClass.getAnnotation(DefunctConfig.class).value()) {
String key = prefix + value;
if (!value.isEmpty() && properties.get(key) != null) {
problems.addError("Defunct property '%s' (class [%s]) cannot be configured.", key, configClass.toString());
}
if (!value.isEmpty() && applicationDefaults.get(key) != null) {
problems.addError("Defunct property '%s' (class [%s]) cannot have an application default.", key, configClass.toString());
}
}
}
for (ConstraintViolation<?> violation : VALIDATOR.validate(instance)) {
AttributeMetadata attributeMetadata = configurationMetadata.getAttributes()
.get(LOWER_CAMEL.to(UPPER_CAMEL, violation.getPropertyPath().toString()));
if (attributeMetadata != null) {
problems.addError("Constraint violation for property '%s': %s (for class %s)",
prefix + attributeMetadata.getInjectionPoint().getProperty(), violation.getMessage(), configClass.getName());
}
else {
problems.addError("Constraint violation with property prefix '%s': %s %s (for class %s)",
prefix, violation.getPropertyPath(), violation.getMessage(), configClass.getName());
}
}
return instance;
}
private static <T> T newInstance(ConfigurationMetadata<T> configurationMetadata)
{
try {
return configurationMetadata.getConstructor().newInstance();
} catch (Throwable e) {
if (e instanceof InvocationTargetException && e.getCause() != null) {
e = e.getCause();
}
throw exceptionFor(e, "Error creating instance of configuration class [%s]", configurationMetadata.getConfigClass().getName());
}
}
private <T> void setConfigProperty(T instance, AttributeMetadata attribute, String prefix, boolean isDefault, Problems problems)
throws InvalidConfigurationException
{
// Get property value
ConfigurationMetadata.InjectionPointMetaData injectionPoint = findOperativeInjectionPoint(attribute, prefix, isDefault, problems);
// If we did not get an injection point, do not call the setter
if (injectionPoint == null) {
return;
}
Object value = getInjectedValue(attribute, injectionPoint, prefix, isDefault, problems);
try {
injectionPoint.getSetter().invoke(instance, value);
} catch (Throwable e) {
if (e instanceof InvocationTargetException && e.getCause() != null) {
e = e.getCause();
}
throw new InvalidConfigurationException(e, "Error invoking configuration method [%s]", injectionPoint.getSetter().toGenericString());
}
}
private ConfigurationMetadata.InjectionPointMetaData findOperativeInjectionPoint(AttributeMetadata attribute, String prefix, boolean isDefault, Problems problems)
throws ConfigurationException
{
OperativeInjectionData operativeInjectionData = new OperativeInjectionData(attribute, prefix, problems);
operativeInjectionData.consider(attribute.getInjectionPoint(), false);
for (ConfigurationMetadata.InjectionPointMetaData injectionPoint : attribute.getLegacyInjectionPoints()) {
operativeInjectionData.consider(injectionPoint, true);
}
if (!isDefault) {
problems.throwIfHasErrors();
InjectionPointMetaData injectionPoint = operativeInjectionData.operativeInjectionPoint;
if (injectionPoint != null) {
if (injectionPoint.getSetter().isAnnotationPresent(Deprecated.class)) {
problems.addWarning("Configuration property '%s' is deprecated and should not be used", prefix + injectionPoint.getProperty());
}
return injectionPoint;
}
}
return operativeInjectionData.defaultInjectionPoint;
}
private class OperativeInjectionData
{
private AttributeMetadata attribute;
private String prefix;
private Problems problems;
private String operativeDescription = null;
InjectionPointMetaData operativeInjectionPoint = null;
InjectionPointMetaData defaultInjectionPoint = null;
public OperativeInjectionData(AttributeMetadata attribute, String prefix, Problems problems)
{
this.attribute = attribute;
this.prefix = prefix;
this.problems = problems;
}
public void consider(InjectionPointMetaData injectionPoint, boolean isLegacy)
{
if (injectionPoint == null) {
return;
}
String fullName = prefix + injectionPoint.getProperty();
if (injectionPoint.isConfigMap()) {
final String mapPrefix = fullName + ".";
for (String key : properties.keySet()) {
if (key.startsWith(mapPrefix)) {
if (isLegacy) {
warnLegacy(fullName);
}
if (operativeDescription == null) {
operativeInjectionPoint = injectionPoint;
operativeDescription = format("map property prefix '%s'", fullName);
}
else {
problems.addError("Map property prefix '%s' conflicts with %s", fullName, operativeDescription);
}
break;
}
}
for (String key : applicationDefaults.keySet()) {
if (key.startsWith(mapPrefix)) {
problems.addError("Cannot have application default property '%s' for a configuration map '%s'", key, fullName);
}
}
}
else {
if (applicationDefaults.get(fullName) != null) {
if (isLegacy) {
defaultLegacy(fullName);
}
else {
defaultInjectionPoint = injectionPoint;
}
}
String value = properties.get(fullName);
if (value != null) {
if (isLegacy) {
warnLegacy(fullName);
}
if (operativeDescription == null) {
operativeInjectionPoint = injectionPoint;
final StringBuilder stringBuilder = new StringBuilder("property '").append(fullName).append("'");
if (!attribute.isSecuritySensitive()) {
stringBuilder.append(" (=").append(value).append(")");
}
operativeDescription = stringBuilder.toString();
}
else {
final StringBuilder stringBuilder = new StringBuilder("Configuration property '").append(fullName).append("'");
if (!attribute.isSecuritySensitive()) {
stringBuilder.append(" (=").append(value).append(")");
}
stringBuilder.append(" conflicts with ").append(operativeDescription);
problems.addError(stringBuilder.toString());
}
}
}
}
private void warnLegacy(String fullName)
{
problems.addWarning("Configuration %s", getLegacyDescription(fullName));
}
private void defaultLegacy(String fullName)
{
problems.addError("Application default %s", getLegacyDescription(fullName));
}
private String getLegacyDescription(String fullName)
{
String replacement = "deprecated.";
if (attribute.getInjectionPoint() != null) {
replacement = format("replaced. Use '%s' instead.", prefix + attribute.getInjectionPoint().getProperty());
}
return format("property '%s' has been %s", fullName, replacement);
}
}
private Object getInjectedValue(AttributeMetadata attribute, InjectionPointMetaData injectionPoint, String prefix, boolean isDefault, Problems problems)
throws InvalidConfigurationException
{
// Get the property value
String name = prefix + injectionPoint.getProperty();
final ConfigMap configMap = injectionPoint.getConfigMap();
if (configMap != null) {
return getInjectedMap(attribute, injectionPoint, name + ".", problems, configMap.key(), configMap.value());
}
String value = properties.get(name);
if (isDefault || value == null) {
value = applicationDefaults.get(name);
}
if (value == null) {
return null;
}
// coerce the property value to the final type
Class<?> propertyType = injectionPoint.getSetter().getParameterTypes()[0];
Object finalValue = coerce(propertyType, value);
final String valueDescription;
if (attribute.isSecuritySensitive()) {
valueDescription = "";
}
else {
valueDescription = " '" + value + "'";
}
if (finalValue == null) {
throw new InvalidConfigurationException(format("Could not coerce value%s to %s (property '%s') in order to call [%s]",
valueDescription,
propertyType.getName(),
name,
injectionPoint.getSetter().toGenericString()));
}
usedProperties.add(name);
unusedProperties.remove(name);
return finalValue;
}
private <K,V> Map<K, V> getInjectedMap(AttributeMetadata attribute, InjectionPointMetaData injectionPoint, String name, Problems problems, Class<K> keyClass, Class<V> valueClass)
{
final boolean valueIsConfigClass = isConfigClass(valueClass);
final HashSet<String> keySet = new HashSet<>();
for (String key : properties.keySet()) {
if (key.startsWith(name)) {
final String keySuffix = key.substring(name.length());
if (valueIsConfigClass) {
keySet.add(keySuffix.split("\\.", 2)[0]);
}
else if (keySuffix.contains(".")) {
problems.addError("Configuration map has non-configuration value class %s, so key '%s' cannot be followed by '.' (property '%s') for call [%s]",
valueClass.getName(),
keySuffix.split("\\.", 2)[0],
key,
injectionPoint.getSetter().toGenericString());
}
else {
keySet.add(keySuffix);
}
}
}
final Map<K, String> coercedKeyMap = new HashMap<>();
final Builder<K, V> builder = ImmutableMap.builder();
for (String keyString : keySet) {
K key = (K) coerce(keyClass, keyString);
if (key == null) {
problems.addError("Could not coerce map key '%s' to %s (property%s '%s') in order to call [%s]",
keyString,
keyClass.getName(),
valueIsConfigClass ? " prefix" : "",
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
final String oldkeyString = coercedKeyMap.put(key, keyString);
if (oldkeyString != null) {
problems.addError("Configuration property prefixes ('%s' and '%s') convert to the same map key, preventing creation of map for call [%s]",
name + oldkeyString,
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
final V value;
if (valueIsConfigClass) {
try {
value = build(valueClass, name + keyString, false, problems);
}
catch (ConfigurationException ignored) {
continue;
}
}
else {
value = (V) coerce(valueClass, properties.get(name + keyString));
if (value == null) {
final String valueDescription;
if (attribute.isSecuritySensitive()) {
valueDescription = "";
}
else {
- valueDescription = " '" + value + "'";
+ valueDescription = " '" + properties.get(name + keyString) + "'";
}
problems.addError("Could not coerce value%s to %s (property '%s') in order to call [%s]",
valueDescription,
valueClass.getName(),
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
usedProperties.add(name + keyString);
unusedProperties.remove(name + keyString);
}
builder.put(key, value);
}
return builder.build();
}
private static Object coerce(Class<?> type, String value)
{
if (type.isPrimitive() && value == null) {
return null;
}
try {
if (String.class.isAssignableFrom(type)) {
return value;
} else if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type)) {
return Boolean.valueOf(value);
} else if (Byte.class.isAssignableFrom(type) || Byte.TYPE.isAssignableFrom(type)) {
return Byte.valueOf(value);
} else if (Short.class.isAssignableFrom(type) || Short.TYPE.isAssignableFrom(type)) {
return Short.valueOf(value);
} else if (Integer.class.isAssignableFrom(type) || Integer.TYPE.isAssignableFrom(type)) {
return Integer.valueOf(value);
} else if (Long.class.isAssignableFrom(type) || Long.TYPE.isAssignableFrom(type)) {
return Long.valueOf(value);
} else if (Float.class.isAssignableFrom(type) || Float.TYPE.isAssignableFrom(type)) {
return Float.valueOf(value);
} else if (Double.class.isAssignableFrom(type) || Double.TYPE.isAssignableFrom(type)) {
return Double.valueOf(value);
}
} catch (Exception ignored) {
// ignore the random exceptions from the built in types
return null;
}
// Look for a static fromString(String) method
try {
Method fromString = type.getMethod("fromString", String.class);
if (fromString.getReturnType().isAssignableFrom(type)) {
return fromString.invoke(null, value);
}
} catch (Throwable ignored) {
}
// Look for a static valueOf(String) method
try {
Method valueOf = type.getMethod("valueOf", String.class);
if (valueOf.getReturnType().isAssignableFrom(type)) {
return valueOf.invoke(null, value);
}
} catch (Throwable ignored) {
}
// Look for a constructor taking a string
try {
Constructor<?> constructor = type.getConstructor(String.class);
return constructor.newInstance(value);
} catch (Throwable ignored) {
}
return null;
}
private static class ConfigurationHolder<T>
{
private final T instance;
private final Problems problems;
private ConfigurationHolder(T instance, Problems problems)
{
this.instance = instance;
this.problems = problems;
}
}
private static List<ConfigurationProvider<?>> getAllProviders(Module... modules)
{
final List<ConfigurationProvider<?>> providers = Lists.newArrayList();
ElementsIterator elementsIterator = new ElementsIterator(modules);
for (final Element element : elementsIterator) {
element.acceptVisitor(new DefaultElementVisitor<Void>()
{
@Override
public <T> Void visit(Binding<T> binding)
{
// look for ConfigurationProviders...
if (binding instanceof ProviderInstanceBinding) {
ProviderInstanceBinding<?> providerInstanceBinding = (ProviderInstanceBinding<?>) binding;
Provider<?> provider = providerInstanceBinding.getProviderInstance();
if (provider instanceof ConfigurationProvider) {
ConfigurationProvider<?> configurationProvider = (ConfigurationProvider<?>) provider;
providers.add(configurationProvider);
}
}
return null;
}
});
}
return providers;
}
}
| true | true | private <K,V> Map<K, V> getInjectedMap(AttributeMetadata attribute, InjectionPointMetaData injectionPoint, String name, Problems problems, Class<K> keyClass, Class<V> valueClass)
{
final boolean valueIsConfigClass = isConfigClass(valueClass);
final HashSet<String> keySet = new HashSet<>();
for (String key : properties.keySet()) {
if (key.startsWith(name)) {
final String keySuffix = key.substring(name.length());
if (valueIsConfigClass) {
keySet.add(keySuffix.split("\\.", 2)[0]);
}
else if (keySuffix.contains(".")) {
problems.addError("Configuration map has non-configuration value class %s, so key '%s' cannot be followed by '.' (property '%s') for call [%s]",
valueClass.getName(),
keySuffix.split("\\.", 2)[0],
key,
injectionPoint.getSetter().toGenericString());
}
else {
keySet.add(keySuffix);
}
}
}
final Map<K, String> coercedKeyMap = new HashMap<>();
final Builder<K, V> builder = ImmutableMap.builder();
for (String keyString : keySet) {
K key = (K) coerce(keyClass, keyString);
if (key == null) {
problems.addError("Could not coerce map key '%s' to %s (property%s '%s') in order to call [%s]",
keyString,
keyClass.getName(),
valueIsConfigClass ? " prefix" : "",
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
final String oldkeyString = coercedKeyMap.put(key, keyString);
if (oldkeyString != null) {
problems.addError("Configuration property prefixes ('%s' and '%s') convert to the same map key, preventing creation of map for call [%s]",
name + oldkeyString,
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
final V value;
if (valueIsConfigClass) {
try {
value = build(valueClass, name + keyString, false, problems);
}
catch (ConfigurationException ignored) {
continue;
}
}
else {
value = (V) coerce(valueClass, properties.get(name + keyString));
if (value == null) {
final String valueDescription;
if (attribute.isSecuritySensitive()) {
valueDescription = "";
}
else {
valueDescription = " '" + value + "'";
}
problems.addError("Could not coerce value%s to %s (property '%s') in order to call [%s]",
valueDescription,
valueClass.getName(),
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
usedProperties.add(name + keyString);
unusedProperties.remove(name + keyString);
}
builder.put(key, value);
}
return builder.build();
}
| private <K,V> Map<K, V> getInjectedMap(AttributeMetadata attribute, InjectionPointMetaData injectionPoint, String name, Problems problems, Class<K> keyClass, Class<V> valueClass)
{
final boolean valueIsConfigClass = isConfigClass(valueClass);
final HashSet<String> keySet = new HashSet<>();
for (String key : properties.keySet()) {
if (key.startsWith(name)) {
final String keySuffix = key.substring(name.length());
if (valueIsConfigClass) {
keySet.add(keySuffix.split("\\.", 2)[0]);
}
else if (keySuffix.contains(".")) {
problems.addError("Configuration map has non-configuration value class %s, so key '%s' cannot be followed by '.' (property '%s') for call [%s]",
valueClass.getName(),
keySuffix.split("\\.", 2)[0],
key,
injectionPoint.getSetter().toGenericString());
}
else {
keySet.add(keySuffix);
}
}
}
final Map<K, String> coercedKeyMap = new HashMap<>();
final Builder<K, V> builder = ImmutableMap.builder();
for (String keyString : keySet) {
K key = (K) coerce(keyClass, keyString);
if (key == null) {
problems.addError("Could not coerce map key '%s' to %s (property%s '%s') in order to call [%s]",
keyString,
keyClass.getName(),
valueIsConfigClass ? " prefix" : "",
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
final String oldkeyString = coercedKeyMap.put(key, keyString);
if (oldkeyString != null) {
problems.addError("Configuration property prefixes ('%s' and '%s') convert to the same map key, preventing creation of map for call [%s]",
name + oldkeyString,
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
final V value;
if (valueIsConfigClass) {
try {
value = build(valueClass, name + keyString, false, problems);
}
catch (ConfigurationException ignored) {
continue;
}
}
else {
value = (V) coerce(valueClass, properties.get(name + keyString));
if (value == null) {
final String valueDescription;
if (attribute.isSecuritySensitive()) {
valueDescription = "";
}
else {
valueDescription = " '" + properties.get(name + keyString) + "'";
}
problems.addError("Could not coerce value%s to %s (property '%s') in order to call [%s]",
valueDescription,
valueClass.getName(),
name + keyString,
injectionPoint.getSetter().toGenericString());
continue;
}
usedProperties.add(name + keyString);
unusedProperties.remove(name + keyString);
}
builder.put(key, value);
}
return builder.build();
}
|
diff --git a/table/src/main/uk/ac/starlink/table/jdbc/StarResultSet.java b/table/src/main/uk/ac/starlink/table/jdbc/StarResultSet.java
index c4d5eeb88..f2d4f96a3 100644
--- a/table/src/main/uk/ac/starlink/table/jdbc/StarResultSet.java
+++ b/table/src/main/uk/ac/starlink/table/jdbc/StarResultSet.java
@@ -1,323 +1,329 @@
package uk.ac.starlink.table.jdbc;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.logging.Logger;
import uk.ac.starlink.table.ColumnInfo;
import uk.ac.starlink.table.DefaultValueInfo;
import uk.ac.starlink.table.DescribedValue;
import uk.ac.starlink.table.DescribedValue;
import uk.ac.starlink.table.RowSequence;
import uk.ac.starlink.table.Tables;
import uk.ac.starlink.table.ValueInfo;
/**
* Wraps the {@link java.sql.ResultSet} class to provide the functions which
* are required to provide {@link uk.ac.starlink.table.StarTable}
* functionality.
*
* @author Mark Taylor
* @since 23 Jul 2007
*/
class StarResultSet {
private final ResultSet rset_;
private final ColumnInfo[] colInfos_;
private final boolean isRandom_;
private long nrow_ = -1L;
private static final Logger logger_ =
Logger.getLogger( "uk.ac.starlink.table.jdbc" );
private final static ValueInfo LABEL_INFO =
new DefaultValueInfo( "Label", String.class );
private final static List AUX_DATA_INFOS =
Collections.unmodifiableList( Arrays.asList( new ValueInfo[] {
LABEL_INFO,
} ) );
/**
* Constructor.
*
* @param rset result set
*/
public StarResultSet( ResultSet rset ) throws SQLException {
rset_ = rset;
/* Assemble metadata for each column. */
ResultSetMetaData meta = rset.getMetaData();
int ncol = meta.getColumnCount();
colInfos_ = new ColumnInfo[ ncol ];
for ( int icol = 0; icol < ncol; icol++ ) {
/* SQL columns are based at 1 not 0. */
int jcol = icol + 1;
/* Set up the name and metadata for this column. */
String name = meta.getColumnName( jcol );
colInfos_[ icol ] = new ColumnInfo( name );
ColumnInfo col = colInfos_[ icol ];
/* Find out what class objects will have. If the class hasn't
* been loaded yet, just call it an Object (could try obtaining
* an object from that column and using its class, but then it
* might be null...). */
String className = meta.getColumnClassName( jcol );
- try {
- Class clazz = getClass().forName( className );
- col.setContentClass( clazz );
+ if ( className != null ) {
+ try {
+ Class clazz = getClass().forName( className );
+ col.setContentClass( clazz );
+ }
+ catch ( ClassNotFoundException e ) {
+ logger_.warning( "Cannot determine class " + className
+ + " for column " + name );
+ col.setContentClass( Object.class );
+ }
}
- catch ( ClassNotFoundException e ) {
- logger_.warning( "Cannot determine class " + className
- + " for column " + name );
+ else {
+ logger_.warning( "No column class given for column " + name );
col.setContentClass( Object.class );
}
if ( meta.isNullable( jcol ) == ResultSetMetaData.columnNoNulls ) {
col.setNullable( false );
}
List auxdata = col.getAuxData();
String label = meta.getColumnLabel( jcol );
if ( label != null &&
label.trim().length() > 0 &&
! label.equalsIgnoreCase( name ) ) {
auxdata.add( new DescribedValue( LABEL_INFO, label.trim() ) );
}
}
/* Work out whether we have random access. */
switch ( rset_.getType() ) {
case ResultSet.TYPE_FORWARD_ONLY:
isRandom_ = false;
break;
case ResultSet.TYPE_SCROLL_INSENSITIVE:
case ResultSet.TYPE_SCROLL_SENSITIVE:
isRandom_ = true;
break;
default:
assert false : "Unknown ResultSet type";
isRandom_ = false;
}
}
/**
* Returns the result set on which this table is based.
*
* @return result set
*/
public ResultSet getResultSet() {
return rset_;
}
/**
* Returns the array of column metadata objects corresponding to the
* columns in this result set.
*
* @return column info array (not a copy)
*/
public ColumnInfo[] getColumnInfos() {
return colInfos_;
}
/**
* Indicates whether this result set can be used for random access.
*
* @return true iff random access is possible
*/
public boolean isRandom() {
return isRandom_;
}
/**
* Lazily counts the number of rows in this result set, if it has random
* access. Otherwise, returns -1 (unknown), since a count may be
* very expensive. If the count cannot be calculated for a random access
* table for some reason, zero is returned and a warning is logged.
*
* @return row count
*/
public long getRowCount() {
/* If we have random access, get the number of rows by going to the
* end and finding what row number it is. This may not be cheap,
* but random access tables are obliged to know how many rows
* they have. Unfortunately this is capable of throwing an
* SQLException, but this method is not declared to throw anything,
* (since the methods it is called from will not be)
* so deal with it best we can. */
if ( isRandom_ ) {
if ( nrow_ < 0 ) {
try {
synchronized ( this ) {
rset_.afterLast();
rset_.previous();
nrow_ = rset_.getRow();
}
}
catch ( SQLException e ) {
logger_.warning( "Failed to get table length: " + e );
nrow_ = 0L;
}
}
return nrow_;
}
else {
return -1L;
}
}
/**
* Returns an ordered list of {@link uk.ac.starlink.table.ValueInfo}
* objects representing the auxilliary metadata returned by
* this object's ColumnInfo objects.
*
* @see uk.ac.starlink.table.StarTable#getColumnAuxDataInfos
* @return an unmodifiable ordered set of known metadata keys
*/
public static List getColumnAuxDataInfos() {
return AUX_DATA_INFOS;
}
/**
* Sets the row index from which subsequent {@link #getCell}
* and {@link #getRow} calls will read.
* Callers may need to worry about synchronization.
*
* @param lrow row index (0-based)
* @throws UnsupportedOperationExcepion for non-random result sets
*/
public void setRowIndex( long lrow ) throws IOException {
if ( isRandom_ ) {
try {
rset_.absolute( Tables.checkedLongToInt( lrow ) + 1 );
}
catch ( SQLException e ) {
throw (IOException)
new IOException( "Error setting to row " + lrow )
.initCause( e );
}
}
else {
throw new UnsupportedOperationException( "No random access" );
}
}
/**
* Returns the object at a given column in the current row of this
* result set in a form suitable for use as the content of a
* StarTable cell.
* Callers may need to worry about synchronization.
*
* @param icol the column to use (first column is 0)
* @return the cell value
*/
public Object getCell( int icol ) throws IOException {
Object base;
try {
base = rset_.getObject( icol + 1 );
}
catch ( SQLException e ) {
throw (IOException) new IOException( "SQL read error" + e )
.initCause( e );
}
Class colclass = colInfos_[ icol ].getContentClass();
if ( base instanceof byte[] && ! colclass.equals( byte[].class ) ) {
return new String( (byte[]) base );
}
else if ( base instanceof char[] &&
! colclass.equals( char[].class ) ) {
return new String( (char[]) base );
}
return base;
}
/**
* Returns the current row of this result set in a form suitable for use
* as the content of a StarTable.
* Callers may need to worry about synchronization.
*
* @return array of cell values in current row
*/
public Object[] getRow() throws IOException {
int ncol = colInfos_.length;
Object[] row = new Object[ ncol ];
for ( int icol = 0; icol < ncol; icol++ ) {
row[ icol ] = getCell( icol );
}
return row;
}
/**
* Returns a sequential RowSequence based on this object.
* This assumes that the cursor is currently at the beginning of the
* result set - no checking is performed here.
*
* @return row sequence
*/
public RowSequence createRowSequence() throws IOException {
return new ResultSetRowSequence();
}
/**
* Row sequence based on this result set. Assumes that the cursor starts
* off positioned at the top of the results, and that no other access
* is being done concurrently on the data.
*/
private class ResultSetRowSequence implements RowSequence {
public boolean next() throws IOException {
try {
return rset_.next();
}
catch ( SQLException e ) {
throw (IOException) new IOException( e.getMessage() )
.initCause( e );
}
}
public Object getCell( int icol ) throws IOException {
checkHasCurrentRow();
return StarResultSet.this.getCell( icol );
}
public Object[] getRow() throws IOException {
checkHasCurrentRow();
return StarResultSet.this.getRow();
}
public void close() throws IOException {
try {
rset_.close();
}
catch ( SQLException e ) {
throw (IOException) new IOException( e.getMessage() )
.initCause( e );
}
}
/**
* Ensure that there is a current row.
*
* @throws NoSuchElementException if there is no current row
*/
private void checkHasCurrentRow() {
try {
if ( rset_.isBeforeFirst() ) {
throw new NoSuchElementException( "No current row" );
}
}
/* SQL Server driver is known to fail here reporting an unsupported
* operation when isBeforeFirst is called. Just assume it's OK
* in that case. */
catch ( SQLException e ) {
}
}
}
}
| false | true | public StarResultSet( ResultSet rset ) throws SQLException {
rset_ = rset;
/* Assemble metadata for each column. */
ResultSetMetaData meta = rset.getMetaData();
int ncol = meta.getColumnCount();
colInfos_ = new ColumnInfo[ ncol ];
for ( int icol = 0; icol < ncol; icol++ ) {
/* SQL columns are based at 1 not 0. */
int jcol = icol + 1;
/* Set up the name and metadata for this column. */
String name = meta.getColumnName( jcol );
colInfos_[ icol ] = new ColumnInfo( name );
ColumnInfo col = colInfos_[ icol ];
/* Find out what class objects will have. If the class hasn't
* been loaded yet, just call it an Object (could try obtaining
* an object from that column and using its class, but then it
* might be null...). */
String className = meta.getColumnClassName( jcol );
try {
Class clazz = getClass().forName( className );
col.setContentClass( clazz );
}
catch ( ClassNotFoundException e ) {
logger_.warning( "Cannot determine class " + className
+ " for column " + name );
col.setContentClass( Object.class );
}
if ( meta.isNullable( jcol ) == ResultSetMetaData.columnNoNulls ) {
col.setNullable( false );
}
List auxdata = col.getAuxData();
String label = meta.getColumnLabel( jcol );
if ( label != null &&
label.trim().length() > 0 &&
! label.equalsIgnoreCase( name ) ) {
auxdata.add( new DescribedValue( LABEL_INFO, label.trim() ) );
}
}
/* Work out whether we have random access. */
switch ( rset_.getType() ) {
case ResultSet.TYPE_FORWARD_ONLY:
isRandom_ = false;
break;
case ResultSet.TYPE_SCROLL_INSENSITIVE:
case ResultSet.TYPE_SCROLL_SENSITIVE:
isRandom_ = true;
break;
default:
assert false : "Unknown ResultSet type";
isRandom_ = false;
}
}
| public StarResultSet( ResultSet rset ) throws SQLException {
rset_ = rset;
/* Assemble metadata for each column. */
ResultSetMetaData meta = rset.getMetaData();
int ncol = meta.getColumnCount();
colInfos_ = new ColumnInfo[ ncol ];
for ( int icol = 0; icol < ncol; icol++ ) {
/* SQL columns are based at 1 not 0. */
int jcol = icol + 1;
/* Set up the name and metadata for this column. */
String name = meta.getColumnName( jcol );
colInfos_[ icol ] = new ColumnInfo( name );
ColumnInfo col = colInfos_[ icol ];
/* Find out what class objects will have. If the class hasn't
* been loaded yet, just call it an Object (could try obtaining
* an object from that column and using its class, but then it
* might be null...). */
String className = meta.getColumnClassName( jcol );
if ( className != null ) {
try {
Class clazz = getClass().forName( className );
col.setContentClass( clazz );
}
catch ( ClassNotFoundException e ) {
logger_.warning( "Cannot determine class " + className
+ " for column " + name );
col.setContentClass( Object.class );
}
}
else {
logger_.warning( "No column class given for column " + name );
col.setContentClass( Object.class );
}
if ( meta.isNullable( jcol ) == ResultSetMetaData.columnNoNulls ) {
col.setNullable( false );
}
List auxdata = col.getAuxData();
String label = meta.getColumnLabel( jcol );
if ( label != null &&
label.trim().length() > 0 &&
! label.equalsIgnoreCase( name ) ) {
auxdata.add( new DescribedValue( LABEL_INFO, label.trim() ) );
}
}
/* Work out whether we have random access. */
switch ( rset_.getType() ) {
case ResultSet.TYPE_FORWARD_ONLY:
isRandom_ = false;
break;
case ResultSet.TYPE_SCROLL_INSENSITIVE:
case ResultSet.TYPE_SCROLL_SENSITIVE:
isRandom_ = true;
break;
default:
assert false : "Unknown ResultSet type";
isRandom_ = false;
}
}
|
diff --git a/src/nu/validator/servlet/CharsetEmitter.java b/src/nu/validator/servlet/CharsetEmitter.java
index 28f6f6bd..b254b145 100644
--- a/src/nu/validator/servlet/CharsetEmitter.java
+++ b/src/nu/validator/servlet/CharsetEmitter.java
@@ -1,38 +1,38 @@
/* This code was generated by nu.validator.tools.SaxCompiler. Please regenerate instead of editing. */
package nu.validator.servlet;
public final class CharsetEmitter {
private CharsetEmitter() {}
public static void emit(org.xml.sax.ContentHandler contentHandler, nu.validator.servlet.VerifierServletTransaction t) throws org.xml.sax.SAXException {
org.xml.sax.helpers.AttributesImpl __attrs__ = new org.xml.sax.helpers.AttributesImpl();
contentHandler.startPrefixMapping("", "http://www.w3.org/1999/xhtml");
__attrs__.clear();
-__attrs__.addAttribute("", "title", "title", "CDATA", "Selecting a preset overrides the schema field above.");
+__attrs__.addAttribute("", "title", "title", "CDATA", "Override for transfer protocol character encoding declaration.");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "tr", "tr", __attrs__);
__attrs__.clear();
contentHandler.startElement("http://www.w3.org/1999/xhtml", "th", "th", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "for", "for", "CDATA", "charset");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "label", "label", __attrs__);
contentHandler.characters(__chars__, 0, 8);
contentHandler.endElement("http://www.w3.org/1999/xhtml", "label", "label");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "th", "th");
__attrs__.clear();
contentHandler.startElement("http://www.w3.org/1999/xhtml", "td", "td", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "id", "id", "CDATA", "charset");
__attrs__.addAttribute("", "name", "name", "CDATA", "charset");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "select", "select", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "value", "value", "CDATA", "");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "option", "option", __attrs__);
contentHandler.characters(__chars__, 8, 14);
contentHandler.endElement("http://www.w3.org/1999/xhtml", "option", "option");
t.emitCharsetOptions();
contentHandler.endElement("http://www.w3.org/1999/xhtml", "select", "select");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "td", "td");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "tr", "tr");
contentHandler.endPrefixMapping("");
}
private static final char[] __chars__ = { 'E', 'n', 'c', 'o', 'd', 'i', 'n', 'g', 'D', 'o', 'n', '\u2019', 't', ' ', 'o', 'v', 'e', 'r', 'r', 'i', 'd', 'e' };
}
| true | true | public static void emit(org.xml.sax.ContentHandler contentHandler, nu.validator.servlet.VerifierServletTransaction t) throws org.xml.sax.SAXException {
org.xml.sax.helpers.AttributesImpl __attrs__ = new org.xml.sax.helpers.AttributesImpl();
contentHandler.startPrefixMapping("", "http://www.w3.org/1999/xhtml");
__attrs__.clear();
__attrs__.addAttribute("", "title", "title", "CDATA", "Selecting a preset overrides the schema field above.");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "tr", "tr", __attrs__);
__attrs__.clear();
contentHandler.startElement("http://www.w3.org/1999/xhtml", "th", "th", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "for", "for", "CDATA", "charset");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "label", "label", __attrs__);
contentHandler.characters(__chars__, 0, 8);
contentHandler.endElement("http://www.w3.org/1999/xhtml", "label", "label");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "th", "th");
__attrs__.clear();
contentHandler.startElement("http://www.w3.org/1999/xhtml", "td", "td", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "id", "id", "CDATA", "charset");
__attrs__.addAttribute("", "name", "name", "CDATA", "charset");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "select", "select", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "value", "value", "CDATA", "");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "option", "option", __attrs__);
contentHandler.characters(__chars__, 8, 14);
contentHandler.endElement("http://www.w3.org/1999/xhtml", "option", "option");
t.emitCharsetOptions();
contentHandler.endElement("http://www.w3.org/1999/xhtml", "select", "select");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "td", "td");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "tr", "tr");
contentHandler.endPrefixMapping("");
}
| public static void emit(org.xml.sax.ContentHandler contentHandler, nu.validator.servlet.VerifierServletTransaction t) throws org.xml.sax.SAXException {
org.xml.sax.helpers.AttributesImpl __attrs__ = new org.xml.sax.helpers.AttributesImpl();
contentHandler.startPrefixMapping("", "http://www.w3.org/1999/xhtml");
__attrs__.clear();
__attrs__.addAttribute("", "title", "title", "CDATA", "Override for transfer protocol character encoding declaration.");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "tr", "tr", __attrs__);
__attrs__.clear();
contentHandler.startElement("http://www.w3.org/1999/xhtml", "th", "th", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "for", "for", "CDATA", "charset");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "label", "label", __attrs__);
contentHandler.characters(__chars__, 0, 8);
contentHandler.endElement("http://www.w3.org/1999/xhtml", "label", "label");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "th", "th");
__attrs__.clear();
contentHandler.startElement("http://www.w3.org/1999/xhtml", "td", "td", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "id", "id", "CDATA", "charset");
__attrs__.addAttribute("", "name", "name", "CDATA", "charset");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "select", "select", __attrs__);
__attrs__.clear();
__attrs__.addAttribute("", "value", "value", "CDATA", "");
contentHandler.startElement("http://www.w3.org/1999/xhtml", "option", "option", __attrs__);
contentHandler.characters(__chars__, 8, 14);
contentHandler.endElement("http://www.w3.org/1999/xhtml", "option", "option");
t.emitCharsetOptions();
contentHandler.endElement("http://www.w3.org/1999/xhtml", "select", "select");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "td", "td");
contentHandler.endElement("http://www.w3.org/1999/xhtml", "tr", "tr");
contentHandler.endPrefixMapping("");
}
|
diff --git a/core/src/visad/data/text/TextAdapter.java b/core/src/visad/data/text/TextAdapter.java
index 9c6528c52..ba03f4eb2 100644
--- a/core/src/visad/data/text/TextAdapter.java
+++ b/core/src/visad/data/text/TextAdapter.java
@@ -1,1814 +1,1837 @@
//
// TextAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2009 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad.data.text;
import java.io.IOException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import visad.Set;
import java.net.URL;
import visad.*;
import visad.VisADException;
import visad.data.in.ArithProg;
import visad.util.DataUtility;
import java.util.regex.*;
/** this is an VisAD file adapter for comma-, tab- and blank-separated
* ASCII text file data. It will attempt to create a FlatField from
* the data and descriptions given in the file and/or the constructor.
*
* The text files contained delimited data. The delimiter is
* determined as follows: if the file has a well-known extension
* (.csv, .tsv, .bsv) then the delimiter is implied by the extension.
* In all other cases, the delimiter for the data (and for the
* "column labels") is determined by reading the first line and
* looking, in order, for a tab, comma, or blank. Which ever one
* is found first is taken as the delimiter.
*
* Two extra pieces of information are needed: the VisAD "MathType"
* which is specified as a string (e.g., (x,y)->(temperature))
* and may either be the first line of the file or passed in through
* one of the constructors.
*
* The second item are the "column labels" which contain the names
* of each field in the data. The names of all range components
* specified in the "MathType" must appear. The names of domain
* components are optional. The values in this string are separated
* by the delimiter, as defined above.
*
* See visad.data.text.README.text for more details.
*
* @author Tom Whittaker
*
*/
public class TextAdapter {
private static final String ATTR_COLSPAN = "colspan";
private static final String ATTR_VALUE = "value";
private static final String ATTR_OFFSET = "off";
private static final String ATTR_ERROR = "err";
private static final String ATTR_SCALE = "sca";
private static final String ATTR_POSITION ="pos";
private static final String ATTR_FORMAT = "fmt";
private static final String ATTR_TIMEZONE = "tz";
private static final String ATTR_UNIT= "unit";
private static final String ATTR_MISSING = "mis";
private static final String ATTR_INTERVAL = "int";
private static final String COMMA = ",";
private static final String SEMICOLON = ";";
private static final String TAB = "\t";
private static final String BLANK = " ";
private static final String BLANK_DELIM = "\\s+";
private FlatField ff = null;
private Field field = null;
private boolean debug = false;
private String DELIM;
private boolean DOQUOTE = true;
private boolean GOTTIME = false;
HeaderInfo []infos;
double[] rangeErrorEstimates;
Unit[] rangeUnits;
Set[] rangeSets;
double[] domainErrorEstimates;
Unit[] domainUnits;
int[][] hdrColumns;
int[][] values_to_index;
private Hashtable properties;
private boolean onlyReadOneLine = false;
private Pattern skipPattern;
/**If this is defined then when processing each tuple pass the processor the tuple
and do not try to create the field */
private StreamProcessor streamProcessor;
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename) throws IOException, VisADException {
this(filename, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename, String map, String params)
throws IOException, VisADException {
InputStream is = new FileInputStream(filename);
DELIM = getDelimiter(filename);
readit(is, map, params);
}
/** Create a VisAD FlatField from a remote Text (comma-, tab- or
* blank-separated values) ASCII file
*
* @param url File URL.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url) throws IOException, VisADException {
this(url, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param url File URL.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url, String map, String params)
throws IOException, VisADException {
DELIM = getDelimiter(url.getFile());
InputStream is = url.openStream();
readit(is, map, params);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params)
throws IOException, VisADException {
this(inputStream, delimiter, map,params,false);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,boolean onlyReadOneLine)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, null, onlyReadOneLine);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param properties properties
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, properties, onlyReadOneLine, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param properties properties
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @param skipPatternString if non-null then skip any line that matches this pattern
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine,String skipPatternString)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, properties, onlyReadOneLine, skipPatternString,null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param properties properties
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @param skipPatternString if non-null then skip any line that matches this pattern
* @param streamProcessor Optional processor of the Tuple stream for point obs
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine,String skipPatternString,StreamProcessor streamProcessor)
throws IOException, VisADException {
this.onlyReadOneLine = onlyReadOneLine;
this.streamProcessor = streamProcessor;
DELIM = delimiter;
this.properties = properties;
if(skipPatternString!=null && skipPatternString.length()>0) {
skipPattern = Pattern.compile(skipPatternString);
}
readit(inputStream, map, params);
}
public static String getDelimiter(String filename) {
if(filename == null) return null;
filename = filename.trim().toLowerCase();
if (filename.endsWith(".csv")) return COMMA;
if (filename.endsWith(".tsv")) return TAB;
if (filename.endsWith(".bsv")) return BLANK;
return null;
}
/**
* Is the given text line a comment
*
* @return is it a comment line
*/
public static boolean isComment(String line) {
return (line.startsWith("#") ||
line.startsWith("!") ||
line.startsWith("%") ||
line.length() < 1);
}
public static String readLine(BufferedReader bis)
throws IOException {
while (true) {
String line = bis.readLine();
if (line == null) return null;
if (!isText(line)) return null;
if (isComment(line)) continue;
return line.trim();
}
}
void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
List<String[]>nameChanges = new ArrayList<String[]>();
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
String[] sthdr = hdr.split(hdrDelim);
+ // since blanks separate the metadata, if we have a blank
+ // delimiter, we run into problems. Loop through the header and
+ // put humpty dumpty back together again
+ if (hdrDelim.equals(BLANK_DELIM) || hdrDelim.equals(BLANK)) {
+ List<String> chunks = new ArrayList<String>();
+ for (int i = 0; i < sthdr.length; i++) {
+ String subchunk = sthdr[i].trim();
+ int m = subchunk.indexOf("[");
+ if (m == -1) {
+ chunks.add(subchunk);
+ continue;
+ }
+ // have "[", find "]"
+ int m2 = subchunk.indexOf("]");
+ while (m2 < 0 && i < sthdr.length) {
+ i++;
+ subchunk += " " +sthdr[i].trim();
+ m2 = subchunk.indexOf("]");
+ }
+ chunks.add(subchunk);
+ }
+ sthdr = (String[]) chunks.toArray(new String[chunks.size()]);
+ }
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 0. Remove any spaces around the "=" signs
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
// 0. Remove any spaces around the "=" signs
String cl = name.substring(m+1,m2).trim();
cl = cl.replaceAll(" +=","=");
cl = cl.replaceAll("= +","=");
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit hdrUnit = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
hdrUnitString = hdrUnitString.trim();
try {
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue) {
try {
hdrUnitString = hdrUnitString.replace(' ','_');
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
hdrUnit = null;
}
}
if(hdrUnit!=null) {
//We clone this unit so it has the original unit string, not the SI unit we get from the parser
try {
hdrUnit = hdrUnit.clone(hdrUnitString);
} catch(Exception ignoreThis) {}
}
}
if (debug) System.out.println("#### assigned Unit as u="+hdrUnit);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, hdrUnit, null, infos[i].isInterval);
// System.err.println("rtname:" + rtname + " " + rt);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (debug && hdrUnit != null)
System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
//Make the realType with just the name
rt = RealType.getRealType(rtname);
//Check if the realtype unit works with the unit from the header
if(rt.getDefaultUnit()!=null && hdrUnit!=null) {
if(!Unit.canConvert(rt.getDefaultUnit(), hdrUnit)) {
rt = null;
}
} else if(hdrUnit!=null) {
rt = null;
}
//If the realtype is bad then we make a new one with the unitsuffix and add
//a name change entry so later we change the mathtype string to have the new name
if(rt == null) {
rt = DataUtility.getUniqueRealType(rtname,hdrUnit, null, infos[i].isInterval);
if (rt != null) {
String newName = rt.getName();
nameChanges.add(new String[]{rtname, newName});
infos[i].name = newName;
if(debug)
System.out.println("made new realtype:" + rt + " unit:" + rt.getDefaultUnit());
}
}
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (hdrUnit == null) hdrUnit = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+hdrUnit);
}
infos[i].unit = hdrUnit;
}
for(String[] tuple: nameChanges) {
if(debug) System.err.println ("changing mathtype component from:" + tuple[0] +" to:" + tuple[1]);
maps = maps.replaceAll("(,|\\() *" + tuple[0]+" *(,|\\))", "$1" + tuple[1]+"$2");
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
mte.printStackTrace();
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
//Note, we need to have a reference to the realTypes list somewhere
//after the above call to stringToType so that the list doesn't get gc'ed
//and the realtypes it contains don't get gc'ed
if(realTypes.size()==0) {
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rangeType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
// debug =true;
rangeType = (TupleType) ((FunctionType)mt).getRange();
numRng = rangeType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rangeType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
Real[] prototypeReals = new Real[nhdr];
TupleType tupleType = null;
int index;
int lineCnt = 0;
while (true) {
String line = readLine(bis);
if (debug) System.out.println("read:"+line);
if (line == null) break;
if(skipPattern!=null && skipPattern.matcher(line).find()) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
// squeeze out extra blank spaces
if (dataDelim.equals(BLANK) || dataDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
line = line.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] tokens = line.split(dataDelim);
int n = tokens.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = null;
double [] rValues = null;
Data [] dataArray= null;
if (streamProcessor==null) {
dValues = new double[numDom];
}
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = tokens[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
dataArray = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
if (streamProcessor==null) {
rValues = new double[numRng];
}
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int tokenIdx = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (tokenIdx >= tokens.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = tokens[tokenIdx++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + tokens[tokenIdx++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
if(dValues!=null)
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
int tupleIndex = values_to_index[1][i];
thisMT = rangeType.getComponent(tupleIndex);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=tokenIdx; q < tokens.length; q++) {
String saTmp = tokens[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
tokenIdx++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//tokens[tokenIdx] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
dataArray[tupleIndex] =
new Text((TextType)thisMT, sThisText);
if (debug) System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
// if(true) continue;
double value = getVal(sa,i);
if(rValues!=null)
rValues[tupleIndex] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, value, infos[i].unit);
}
dataArray[tupleIndex] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
e.printStackTrace();
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (dataArray != null) {
if (streamProcessor!=null) {
streamProcessor.processValues(dataArray);
} else {
if(tupleType == null) {
tuple = new Tuple(dataArray);
tupleType = (TupleType)tuple.getType();
} else {
tuple = new Tuple(tupleType, dataArray, false, false);
}
}
}
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(dataArray);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<dataArray.length;i++) {
if(dataArray[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
if (streamProcessor==null) {
if(dValues!=null)
domainValues.add(dValues);
if(rValues!=null)
rangeValues.add(rValues);
if (tuple != null)
tupleValues.add(tuple);
}
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
if (streamProcessor!=null) {
bis.close();
return;
}
int numSamples = rangeValues.size(); // # lines of data
if (numSamples == 0) {
throw new VisADException("No data available to read");
}
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
// munges a pseudo MathType string into something legal
private String makeMT(String s) {
int k = s.indexOf("->");
if (k < 0) {
// System.out.println("TextAdapter: invalid MathType form; -> required");
return null;
}
StringBuffer sb = new StringBuffer("");
for (int i=0; i<s.length(); i++) {
String r = s.substring(i,i+1);
if (!r.equals(" ") && !r.equals("\t") && !r.equals("\n")) {
sb.append(r);
}
}
String t = sb.toString();
k = t.indexOf("->");
if (t.charAt(k-1) != ')' ) {
if (t.charAt(k+2) != '(' ) {
String t2 = "("+t.substring(0,k) + ")->("+t.substring(k+2)+")";
t = t2;
} else {
String t2 = "("+t.substring(0,k) + ")"+t.substring(k);
t = t2;
}
} else if (t.charAt(k+2) != '(' ) {
String t2 = t.substring(0,k+2)+"("+t.substring(k+2)+")";
t = t2;
}
if (!t.startsWith("((") ) {
String t2= "("+t+")";
t = t2;
}
return t;
}
private static final boolean isText(String s)
{
final int len = (s == null ? -1 : s.length());
if (len <= 0) {
// well, it's not really *binary*, so pretend it's text
return true;
}
for (int i = 0; i < len; i++) {
final char ch = s.charAt(i);
if (Character.isISOControl(ch) && !Character.isWhitespace(ch)) {
// we might want to special-case formfeed/linefeed/newline here...
return false;
}
}
return true;
}
/**
* generate a DateTime from a string
* @param string - Formatted date/time string
*
* @return - the equivalent VisAD DateTime for the string
*
* (lifted from au.gov.bom.aifs.common.ada.VisADXMLAdapter.java)
*/
private static visad.DateTime makeDateTimeFromString(String string,
String format, String tz)
throws java.text.ParseException
{
visad.DateTime dt = null;
// try to parse the string using the supplied DateTime format
try {
if(dateParsers!=null) {
for(int i=0;i<dateParsers.size();i++) {
DateParser dateParser = (DateParser) dateParsers.get(i);
dt = dateParser.createDateTime(string, format, TimeZone.getTimeZone(tz));
if(dt !=null) {
return dt;
}
}
}
String key = format+"__" + tz;
SimpleDateFormat sdf = (SimpleDateFormat) formats.get(key);
if(sdf == null) {
sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone(tz));
sdf.applyPattern(format);
formats.put(key,sdf);
}
Date d = sdf.parse(string);
dt = new DateTime(d);
// dt = visad.DateTime.createDateTime(string, format, TimeZone.getTimeZone(tz));
} catch (VisADException e) {}
if (dt==null) {
throw new java.text.ParseException("Couldn't parse visad.DateTime from \""
+string+"\"", -1);
} else {
return dt;
}
}
/** A set of cached simpledateformats */
private static Hashtable formats = new Hashtable();
/** This list of DateFormatter-s will be checked when we are making a DateTime wiht a given format */
private static List dateParsers;
/** used to allow applications to define their own date parsing */
public static interface DateParser {
/** If this particular DateParser does not know how to handle the give format then this method should return null */
public DateTime createDateTime(String value, String format, TimeZone timezone) throws VisADException;
}
/** used to allow applications to define their own date parsing */
public static void addDateParser(DateParser dateParser) {
if(dateParsers==null) {
dateParsers = new ArrayList();
}
dateParsers.add(dateParser);
}
double getVal(String s, int k) {
int i = values_to_index[2][k];
if (i < 0 || s == null || s.length()<1 || (infos[i].missingString!=null && s.equals(infos[i].missingString))) {
return Double.NaN;
}
HeaderInfo info = infos[i];
// try parsing as a double first
if (info.formatString == null) {
// no format provided : parse as a double
try {
double v;
try {
v = Double.parseDouble(s);
} catch (java.lang.NumberFormatException nfe1) {
//If units are degrees then try to decode this as a lat/lon
// We should probably not rely on throwing an exception to handle this but...
if(info.unit !=null && Unit.canConvert(info.unit, visad.CommonUnit.degree)) {
v=decodeLatLon(s);
} else {
throw nfe1;
}
if(v!=v) throw new java.lang.NumberFormatException(s);
}
if (v == info.missingValue) {
return Double.NaN;
}
v = v * info.scale + info.offset;
return v;
} catch (java.lang.NumberFormatException ne) {
System.out.println("Invalid number format for "+s);
}
} else {
// a format was specified: only support DateTime format
// so try to parse as a DateTime
try{
visad.DateTime dt = makeDateTimeFromString(s, info.formatString, info.tzString);
return dt.getReal().getValue();
} catch (java.text.ParseException pe) {
System.out.println("Invalid number/time format for "+s);
}
}
return Double.NaN;
}
// get the samples from the ArrayList.
float[][] getDomSamples(int comp, int numDomValues, ArrayList domValues) {
float [][] a = new float[1][numDomValues];
for (int i=0; i<numDomValues; i++) {
double[] d = (double[])(domValues.get(i));
a[0][i] = (float)d[comp];
}
return a;
}
/** get the data
* @return a Field of the data read from the file
*
*/
public Field getData() {
return field;
}
/**
* Returns an appropriate 1D domain.
*
* @param type the math-type of the domain
* @param numSamples the number of samples in the domain
* @param domValues domain values are extracted from this array list.
*
* @return a Linear1DSet if the domain samples form an arithmetic
* progression, a Gridded1DDoubleSet if the domain samples are ordered
* but do not form an arithmetic progression, otherwise an Irregular1DSet.
*
* @throws VisADException there was a problem creating the domain set.
*/
private Set createAppropriate1DDomain(MathType type, int numSamples,
ArrayList domValues)
throws VisADException {
if (0 == numSamples) {
// Can't create a domain set with zero samples.
return null;
}
// Extract the first element from each element of the array list.
double[][] values = new double[1][numSamples];
for (int i=0; i<numSamples; ++i) {
double[] d = (double []) domValues.get(i);
values[0][i] = d[0];
}
// This implementation for testing that the values are ordered
// is based on visad.Gridded1DDoubleSet.java
boolean ordered = true;
boolean ascending = values[0][numSamples -1] > values[0][0];
if (ascending) {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] < values[0][i - 1]) {
ordered = false;
break;
}
}
} else {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] > values[0][i - 1]) {
ordered = false;
break;
}
}
}
Set set = null;
if (ordered) {
ArithProg arithProg = new ArithProg();
if (arithProg.accumulate(values[0])) {
// The domain values form an arithmetic progression (ordered and
// equally spaced) so use a linear set.
set = new Linear1DSet(type, values[0][0], values[0][numSamples - 1],
numSamples);
} else {
// The samples are ordered, so use a gridded set.
set = new Gridded1DDoubleSet(type, values, numSamples);
}
} else {
set = new Irregular1DSet(type, Set.doubleToFloat(values));
}
return set;
}
private static class HeaderInfo {
String name;
Unit unit;
double missingValue = Double.NaN;
String missingString;
String formatString;
String tzString = "GMT";
int isInterval = 0;
double errorEstimate=0;
double scale=1.0;
double offset=0.0;
String fixedValue;
int colspan = 1;
boolean isText = false;
public boolean isParam(String param) {
return name.equals(param) || name.equals(param+"(Text)");
}
public String toString() {
return name;
}
}
/**
* Read in the given file and return the processed data
*
* @param file The file to read in
* @return the data
*/
public static Data processFile(String file) throws Exception {
TextAdapter ta = new TextAdapter(file);
System.out.println(ta.getData().getType());
return ta.getData();
}
// uncomment to test
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Must supply a filename");
System.exit(1);
}
TextAdapter ta = new TextAdapter(args[0]);
System.out.println(ta.getData().getType());
new visad.jmet.DumpType().dumpMathType(ta.getData().getType(),System.out);
new visad.jmet.DumpType().dumpDataType(ta.getData(),System.out);
System.out.println("#### Data = "+ta.getData());
System.out.println("EOF... ");
}
/**
* A cut-and-paste from the IDV Misc method
* Decodes a string representation of a latitude or longitude and
* returns a double version (in degrees). Acceptible formats are:
* <pre>
* +/- ddd:mm, ddd:mm:, ddd:mm:ss, ddd::ss, ddd.fffff ===> [+/-] ddd.fffff
* +/- ddd, ddd:, ddd:: ===> [+/-] ddd
* +/- :mm, :mm:, :mm:ss, ::ss, .fffff ===> [+/-] .fffff
* +/- :, :: ===> 0.0
* Any of the above with N,S,E,W appended
* </pre>
*
* @param latlon string representation of lat or lon
* @return the decoded value in degrees
*/
public static double decodeLatLon(String latlon) {
// first check to see if there is a N,S,E,or W on this
latlon = latlon.trim();
int dirIndex = -1;
int southOrWest = 1;
double value = Double.NaN;
if (latlon.indexOf("S") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("S");
} else if (latlon.indexOf("W") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("W");
} else if (latlon.indexOf("N") > 0) {
dirIndex = latlon.indexOf("N");
} else if (latlon.indexOf("E") > 0) {
dirIndex = latlon.indexOf("E");
}
if (dirIndex > 0) {
latlon = latlon.substring(0, dirIndex).trim();
}
// now see if this is a negative value
if (latlon.indexOf("-") == 0) {
southOrWest *= -1;
latlon = latlon.substring(latlon.indexOf("-") + 1).trim();
}
if (latlon.indexOf(":") >= 0) { //have something like DD:MM:SS, DD::, DD:MM:, etc
int firstIdx = latlon.indexOf(":");
String hours = latlon.substring(0, firstIdx);
String minutes = latlon.substring(firstIdx + 1);
String seconds = "";
if (minutes.indexOf(":") >= 0) {
firstIdx = minutes.indexOf(":");
String temp = minutes.substring(0, firstIdx);
seconds = minutes.substring(firstIdx + 1);
minutes = temp;
}
try {
value = (hours.equals("") == true)
? 0
: Double.parseDouble(hours);
if ( !minutes.equals("")) {
value += Double.parseDouble(minutes) / 60.;
}
if ( !seconds.equals("")) {
value += Double.parseDouble(seconds) / 3600.;
}
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
} else { //have something like DD.ddd
try {
value = Double.parseDouble(latlon);
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
}
return value * southOrWest;
}
public interface StreamProcessor {
public void processValues(Data[] tuple) throws VisADException ;
}
}
| true | true | void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
List<String[]>nameChanges = new ArrayList<String[]>();
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 0. Remove any spaces around the "=" signs
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
// 0. Remove any spaces around the "=" signs
String cl = name.substring(m+1,m2).trim();
cl = cl.replaceAll(" +=","=");
cl = cl.replaceAll("= +","=");
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit hdrUnit = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
hdrUnitString = hdrUnitString.trim();
try {
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue) {
try {
hdrUnitString = hdrUnitString.replace(' ','_');
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
hdrUnit = null;
}
}
if(hdrUnit!=null) {
//We clone this unit so it has the original unit string, not the SI unit we get from the parser
try {
hdrUnit = hdrUnit.clone(hdrUnitString);
} catch(Exception ignoreThis) {}
}
}
if (debug) System.out.println("#### assigned Unit as u="+hdrUnit);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, hdrUnit, null, infos[i].isInterval);
// System.err.println("rtname:" + rtname + " " + rt);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (debug && hdrUnit != null)
System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
//Make the realType with just the name
rt = RealType.getRealType(rtname);
//Check if the realtype unit works with the unit from the header
if(rt.getDefaultUnit()!=null && hdrUnit!=null) {
if(!Unit.canConvert(rt.getDefaultUnit(), hdrUnit)) {
rt = null;
}
} else if(hdrUnit!=null) {
rt = null;
}
//If the realtype is bad then we make a new one with the unitsuffix and add
//a name change entry so later we change the mathtype string to have the new name
if(rt == null) {
rt = DataUtility.getUniqueRealType(rtname,hdrUnit, null, infos[i].isInterval);
if (rt != null) {
String newName = rt.getName();
nameChanges.add(new String[]{rtname, newName});
infos[i].name = newName;
if(debug)
System.out.println("made new realtype:" + rt + " unit:" + rt.getDefaultUnit());
}
}
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (hdrUnit == null) hdrUnit = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+hdrUnit);
}
infos[i].unit = hdrUnit;
}
for(String[] tuple: nameChanges) {
if(debug) System.err.println ("changing mathtype component from:" + tuple[0] +" to:" + tuple[1]);
maps = maps.replaceAll("(,|\\() *" + tuple[0]+" *(,|\\))", "$1" + tuple[1]+"$2");
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
mte.printStackTrace();
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
//Note, we need to have a reference to the realTypes list somewhere
//after the above call to stringToType so that the list doesn't get gc'ed
//and the realtypes it contains don't get gc'ed
if(realTypes.size()==0) {
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rangeType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
// debug =true;
rangeType = (TupleType) ((FunctionType)mt).getRange();
numRng = rangeType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rangeType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
Real[] prototypeReals = new Real[nhdr];
TupleType tupleType = null;
int index;
int lineCnt = 0;
while (true) {
String line = readLine(bis);
if (debug) System.out.println("read:"+line);
if (line == null) break;
if(skipPattern!=null && skipPattern.matcher(line).find()) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
// squeeze out extra blank spaces
if (dataDelim.equals(BLANK) || dataDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
line = line.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] tokens = line.split(dataDelim);
int n = tokens.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = null;
double [] rValues = null;
Data [] dataArray= null;
if (streamProcessor==null) {
dValues = new double[numDom];
}
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = tokens[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
dataArray = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
if (streamProcessor==null) {
rValues = new double[numRng];
}
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int tokenIdx = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (tokenIdx >= tokens.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = tokens[tokenIdx++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + tokens[tokenIdx++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
if(dValues!=null)
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
int tupleIndex = values_to_index[1][i];
thisMT = rangeType.getComponent(tupleIndex);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=tokenIdx; q < tokens.length; q++) {
String saTmp = tokens[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
tokenIdx++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//tokens[tokenIdx] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
dataArray[tupleIndex] =
new Text((TextType)thisMT, sThisText);
if (debug) System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
// if(true) continue;
double value = getVal(sa,i);
if(rValues!=null)
rValues[tupleIndex] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, value, infos[i].unit);
}
dataArray[tupleIndex] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
e.printStackTrace();
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (dataArray != null) {
if (streamProcessor!=null) {
streamProcessor.processValues(dataArray);
} else {
if(tupleType == null) {
tuple = new Tuple(dataArray);
tupleType = (TupleType)tuple.getType();
} else {
tuple = new Tuple(tupleType, dataArray, false, false);
}
}
}
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(dataArray);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<dataArray.length;i++) {
if(dataArray[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
if (streamProcessor==null) {
if(dValues!=null)
domainValues.add(dValues);
if(rValues!=null)
rangeValues.add(rValues);
if (tuple != null)
tupleValues.add(tuple);
}
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
if (streamProcessor!=null) {
bis.close();
return;
}
int numSamples = rangeValues.size(); // # lines of data
if (numSamples == 0) {
throw new VisADException("No data available to read");
}
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
| void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
List<String[]>nameChanges = new ArrayList<String[]>();
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
String[] sthdr = hdr.split(hdrDelim);
// since blanks separate the metadata, if we have a blank
// delimiter, we run into problems. Loop through the header and
// put humpty dumpty back together again
if (hdrDelim.equals(BLANK_DELIM) || hdrDelim.equals(BLANK)) {
List<String> chunks = new ArrayList<String>();
for (int i = 0; i < sthdr.length; i++) {
String subchunk = sthdr[i].trim();
int m = subchunk.indexOf("[");
if (m == -1) {
chunks.add(subchunk);
continue;
}
// have "[", find "]"
int m2 = subchunk.indexOf("]");
while (m2 < 0 && i < sthdr.length) {
i++;
subchunk += " " +sthdr[i].trim();
m2 = subchunk.indexOf("]");
}
chunks.add(subchunk);
}
sthdr = (String[]) chunks.toArray(new String[chunks.size()]);
}
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 0. Remove any spaces around the "=" signs
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
// 0. Remove any spaces around the "=" signs
String cl = name.substring(m+1,m2).trim();
cl = cl.replaceAll(" +=","=");
cl = cl.replaceAll("= +","=");
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit hdrUnit = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
hdrUnitString = hdrUnitString.trim();
try {
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue) {
try {
hdrUnitString = hdrUnitString.replace(' ','_');
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
hdrUnit = null;
}
}
if(hdrUnit!=null) {
//We clone this unit so it has the original unit string, not the SI unit we get from the parser
try {
hdrUnit = hdrUnit.clone(hdrUnitString);
} catch(Exception ignoreThis) {}
}
}
if (debug) System.out.println("#### assigned Unit as u="+hdrUnit);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, hdrUnit, null, infos[i].isInterval);
// System.err.println("rtname:" + rtname + " " + rt);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (debug && hdrUnit != null)
System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
//Make the realType with just the name
rt = RealType.getRealType(rtname);
//Check if the realtype unit works with the unit from the header
if(rt.getDefaultUnit()!=null && hdrUnit!=null) {
if(!Unit.canConvert(rt.getDefaultUnit(), hdrUnit)) {
rt = null;
}
} else if(hdrUnit!=null) {
rt = null;
}
//If the realtype is bad then we make a new one with the unitsuffix and add
//a name change entry so later we change the mathtype string to have the new name
if(rt == null) {
rt = DataUtility.getUniqueRealType(rtname,hdrUnit, null, infos[i].isInterval);
if (rt != null) {
String newName = rt.getName();
nameChanges.add(new String[]{rtname, newName});
infos[i].name = newName;
if(debug)
System.out.println("made new realtype:" + rt + " unit:" + rt.getDefaultUnit());
}
}
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (hdrUnit == null) hdrUnit = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+hdrUnit);
}
infos[i].unit = hdrUnit;
}
for(String[] tuple: nameChanges) {
if(debug) System.err.println ("changing mathtype component from:" + tuple[0] +" to:" + tuple[1]);
maps = maps.replaceAll("(,|\\() *" + tuple[0]+" *(,|\\))", "$1" + tuple[1]+"$2");
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
mte.printStackTrace();
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
//Note, we need to have a reference to the realTypes list somewhere
//after the above call to stringToType so that the list doesn't get gc'ed
//and the realtypes it contains don't get gc'ed
if(realTypes.size()==0) {
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rangeType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
// debug =true;
rangeType = (TupleType) ((FunctionType)mt).getRange();
numRng = rangeType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rangeType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
Real[] prototypeReals = new Real[nhdr];
TupleType tupleType = null;
int index;
int lineCnt = 0;
while (true) {
String line = readLine(bis);
if (debug) System.out.println("read:"+line);
if (line == null) break;
if(skipPattern!=null && skipPattern.matcher(line).find()) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
// squeeze out extra blank spaces
if (dataDelim.equals(BLANK) || dataDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
line = line.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] tokens = line.split(dataDelim);
int n = tokens.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = null;
double [] rValues = null;
Data [] dataArray= null;
if (streamProcessor==null) {
dValues = new double[numDom];
}
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = tokens[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
dataArray = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
if (streamProcessor==null) {
rValues = new double[numRng];
}
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int tokenIdx = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (tokenIdx >= tokens.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = tokens[tokenIdx++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + tokens[tokenIdx++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
if(dValues!=null)
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
int tupleIndex = values_to_index[1][i];
thisMT = rangeType.getComponent(tupleIndex);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=tokenIdx; q < tokens.length; q++) {
String saTmp = tokens[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
tokenIdx++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//tokens[tokenIdx] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
dataArray[tupleIndex] =
new Text((TextType)thisMT, sThisText);
if (debug) System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
// if(true) continue;
double value = getVal(sa,i);
if(rValues!=null)
rValues[tupleIndex] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, value, infos[i].unit);
}
dataArray[tupleIndex] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
e.printStackTrace();
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (dataArray != null) {
if (streamProcessor!=null) {
streamProcessor.processValues(dataArray);
} else {
if(tupleType == null) {
tuple = new Tuple(dataArray);
tupleType = (TupleType)tuple.getType();
} else {
tuple = new Tuple(tupleType, dataArray, false, false);
}
}
}
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(dataArray);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<dataArray.length;i++) {
if(dataArray[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
if (streamProcessor==null) {
if(dValues!=null)
domainValues.add(dValues);
if(rValues!=null)
rangeValues.add(rValues);
if (tuple != null)
tupleValues.add(tuple);
}
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
if (streamProcessor!=null) {
bis.close();
return;
}
int numSamples = rangeValues.size(); // # lines of data
if (numSamples == 0) {
throw new VisADException("No data available to read");
}
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
|
diff --git a/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/resolver/P2TargetPlatformResolver.java b/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/resolver/P2TargetPlatformResolver.java
index bb70b3d..64787de 100644
--- a/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/resolver/P2TargetPlatformResolver.java
+++ b/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/resolver/P2TargetPlatformResolver.java
@@ -1,448 +1,449 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Sonatype Inc. and others.
* 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
*
* Contributors:
* Sonatype Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.tycho.p2.resolver;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.maven.ProjectDependenciesResolver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
import org.apache.maven.artifact.repository.Authentication;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException;
import org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.Mirror;
import org.apache.maven.settings.Server;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.eclipse.tycho.ArtifactKey;
import org.eclipse.tycho.ReactorProject;
import org.eclipse.tycho.core.TargetEnvironment;
import org.eclipse.tycho.core.TargetPlatform;
import org.eclipse.tycho.core.TargetPlatformConfiguration;
import org.eclipse.tycho.core.TargetPlatformResolver;
import org.eclipse.tycho.core.TychoConstants;
import org.eclipse.tycho.core.facade.MavenLogger;
import org.eclipse.tycho.core.maven.MavenDependencyInjector;
import org.eclipse.tycho.core.osgitools.AbstractTychoProject;
import org.eclipse.tycho.core.osgitools.BundleReader;
import org.eclipse.tycho.core.osgitools.DebugUtils;
import org.eclipse.tycho.core.osgitools.DefaultArtifactKey;
import org.eclipse.tycho.core.osgitools.targetplatform.AbstractTargetPlatformResolver;
import org.eclipse.tycho.core.osgitools.targetplatform.DefaultTargetPlatform;
import org.eclipse.tycho.core.osgitools.targetplatform.MultiEnvironmentTargetPlatform;
import org.eclipse.tycho.core.p2.P2ArtifactRepositoryLayout;
import org.eclipse.tycho.core.utils.ExecutionEnvironmentUtils;
import org.eclipse.tycho.core.utils.PlatformPropertiesUtils;
import org.eclipse.tycho.equinox.EquinoxServiceFactory;
import org.eclipse.tycho.model.Target;
import org.eclipse.tycho.osgi.adapters.MavenLoggerAdapter;
import org.eclipse.tycho.p2.facade.internal.ReactorArtifactFacade;
import org.eclipse.tycho.p2.metadata.DependencyMetadataGenerator;
import org.eclipse.tycho.p2.resolver.facade.P2ResolutionResult;
import org.eclipse.tycho.p2.resolver.facade.P2Resolver;
import org.eclipse.tycho.p2.resolver.facade.P2ResolverFactory;
import org.eclipse.tycho.p2.resolver.facade.ResolutionContext;
@Component(role = TargetPlatformResolver.class, hint = P2TargetPlatformResolver.ROLE_HINT, instantiationStrategy = "per-lookup")
public class P2TargetPlatformResolver extends AbstractTargetPlatformResolver implements TargetPlatformResolver,
Initializable {
public static final String ROLE_HINT = "p2";
@Requirement
private EquinoxServiceFactory equinox;
@Requirement
private BundleReader bundleReader;
@Requirement
private RepositorySystem repositorySystem;
@Requirement(hint = "p2")
private ArtifactRepositoryLayout p2layout;
@Requirement
private ProjectDependenciesResolver projectDependenciesResolver;
private P2ResolverFactory resolverFactory;
private DependencyMetadataGenerator generator;
private DependencyMetadataGenerator sourcesGenerator;
private static final ArtifactRepositoryPolicy P2_REPOSITORY_POLICY = new ArtifactRepositoryPolicy(true,
ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER, ArtifactRepositoryPolicy.CHECKSUM_POLICY_IGNORE);
public void setupProjects(MavenSession session, MavenProject project, ReactorProject reactorProject) {
TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
.getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);
List<Map<String, String>> environments = getEnvironments(configuration);
Set<Object> metadata = generator
.generateMetadata(new ReactorArtifactFacade(reactorProject, null), environments);
reactorProject.setDependencyMetadata(null, metadata);
// TODO this should be moved to osgi-sources-plugin somehow
if (isBundleProject(project) && hasSourceBundle(project)) {
ReactorArtifactFacade sourcesArtifact = new ReactorArtifactFacade(reactorProject, "sources");
Set<Object> sourcesMetadata = sourcesGenerator.generateMetadata(sourcesArtifact, environments);
reactorProject.setDependencyMetadata(sourcesArtifact.getClassidier(), sourcesMetadata);
}
}
private static boolean isBundleProject(MavenProject project) {
String type = project.getPackaging();
return ArtifactKey.TYPE_ECLIPSE_PLUGIN.equals(type) || ArtifactKey.TYPE_ECLIPSE_TEST_PLUGIN.equals(type);
}
private static boolean hasSourceBundle(MavenProject project) {
// TODO this is a fragile way of checking whether we generate a source bundle
// should we rather use MavenSession to get the actual configured mojo instance?
for (Plugin plugin : project.getBuildPlugins()) {
if ("org.eclipse.tycho:tycho-source-plugin".equals(plugin.getKey())) {
return true;
}
}
return false;
}
public TargetPlatform resolvePlatform(final MavenSession session, final MavenProject project,
List<ReactorProject> reactorProjects, List<Dependency> dependencies) {
MavenLogger loggerForOsgiImpl = new MavenLoggerAdapter(getLogger(), DebugUtils.isDebugEnabled(session, project));
File localRepositoryRoot = new File(session.getLocalRepository().getBasedir());
ResolutionContext resolutionContext = resolverFactory.createResolutionContext(localRepositoryRoot,
session.isOffline(), loggerForOsgiImpl);
P2Resolver osgiResolverImpl = resolverFactory.createResolver(loggerForOsgiImpl);
try {
return doResolvePlatform(session, project, reactorProjects, dependencies, resolutionContext,
osgiResolverImpl);
} finally {
resolutionContext.stop();
}
}
protected TargetPlatform doResolvePlatform(final MavenSession session, final MavenProject project,
List<ReactorProject> reactorProjects, List<Dependency> dependencies, ResolutionContext resolutionContext,
P2Resolver resolver) {
TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
.getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);
Map<File, ReactorProject> projects = new HashMap<File, ReactorProject>();
resolver.setEnvironments(getEnvironments(configuration));
for (ReactorProject otherProject : reactorProjects) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("P2resolver.addMavenProject " + otherProject.getId());
}
projects.put(otherProject.getBasedir(), otherProject);
resolutionContext.addReactorArtifact(new ReactorArtifactFacade(otherProject, null));
Map<String, Set<Object>> dependencyMetadata = otherProject.getDependencyMetadata();
if (dependencyMetadata != null) {
for (String classifier : dependencyMetadata.keySet()) {
resolutionContext.addReactorArtifact(new ReactorArtifactFacade(otherProject, classifier));
}
}
}
if (dependencies != null) {
for (Dependency dependency : dependencies) {
resolver.addDependency(dependency.getType(), dependency.getArtifactId(), dependency.getVersion());
}
}
if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(configuration.getPomDependencies())) {
Set<String> projectIds = new HashSet<String>();
for (ReactorProject p : reactorProjects) {
String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
projectIds.add(key);
}
ArrayList<String> scopes = new ArrayList<String>();
scopes.add(Artifact.SCOPE_COMPILE);
Collection<Artifact> artifacts;
try {
artifacts = projectDependenciesResolver.resolve(project, scopes, session);
} catch (MultipleArtifactsNotFoundException e) {
Collection<Artifact> missing = new HashSet<Artifact>(e.getMissingArtifacts());
for (Iterator<Artifact> it = missing.iterator(); it.hasNext();) {
Artifact a = it.next();
String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
if (projectIds.contains(key)) {
it.remove();
}
}
if (!missing.isEmpty()) {
throw new RuntimeException("Could not resolve project dependencies", e);
}
artifacts = e.getResolvedArtifacts();
artifacts.removeAll(e.getMissingArtifacts());
} catch (AbstractArtifactResolutionException e) {
throw new RuntimeException("Could not resolve project dependencies", e);
}
List<Artifact> externalArtifacts = new ArrayList<Artifact>(artifacts.size());
for (Artifact artifact : artifacts) {
String key = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
artifact.getBaseVersion());
if (projectIds.contains(key)) {
// resolved to an older snapshot from the repo, we only want the current project in the reactor
continue;
}
externalArtifacts.add(artifact);
}
List<Artifact> explicitArtifacts = MavenDependencyInjector.filterInjectedDependencies(externalArtifacts); // needed when the resolution is done again for the test runtime
PomDependencyProcessor pomDependencyProcessor = new PomDependencyProcessor(session, repositorySystem,
getLogger());
pomDependencyProcessor.addPomDependenciesToResolutionContext(project, explicitArtifacts, resolutionContext);
}
for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
try {
URI uri = new URL(repository.getUrl()).toURI();
if (repository.getLayout() instanceof P2ArtifactRepositoryLayout) {
if (session.isOffline()) {
getLogger().debug(
"Offline mode, using local cache only for repository " + repository.getId() + " ("
+ repository.getUrl() + ")");
}
try {
Authentication auth = repository.getAuthentication();
if (auth != null) {
resolutionContext.setCredentials(uri, auth.getUsername(), auth.getPassword());
}
resolutionContext.addP2Repository(uri);
getLogger().debug(
"Added p2 repository " + repository.getId() + " (" + repository.getUrl() + ")");
} catch (Exception e) {
String msg = "Failed to access p2 repository " + repository.getId() + " ("
+ repository.getUrl() + "), will try to use local cache. Reason: " + e.getMessage();
if (getLogger().isDebugEnabled()) {
getLogger().warn(msg, e);
} else {
getLogger().warn(msg);
}
}
}
} catch (MalformedURLException e) {
getLogger().warn("Could not parse repository URL", e);
} catch (URISyntaxException e) {
getLogger().warn("Could not parse repository URL", e);
}
}
Target target = configuration.getTarget();
if (target != null) {
Set<URI> uris = new HashSet<URI>();
for (Target.Location location : target.getLocations()) {
String type = location.getType();
if (!"InstallableUnit".equalsIgnoreCase(type)) {
getLogger().warn("Target location type: " + type + " is not supported");
continue;
}
for (Target.Repository repository : location.getRepositories()) {
try {
URI uri = new URI(getMirror(repository, session.getRequest().getMirrors()));
if (uris.add(uri)) {
if (session.isOffline()) {
getLogger().debug("Ignored repository " + uri + " while in offline mode");
} else {
String id = repository.getId();
if (id != null) {
Server server = session.getSettings().getServer(id);
if (server != null) {
resolutionContext.setCredentials(uri, server.getUsername(),
server.getPassword());
} else {
getLogger().info(
"Unknown server id=" + id + " for repository location="
+ repository.getLocation());
}
}
try {
resolutionContext.addP2Repository(uri);
} catch (Exception e) {
String msg = "Failed to access p2 repository " + uri
+ ", will try to use local cache. Reason: " + e.getMessage();
if (getLogger().isDebugEnabled()) {
getLogger().warn(msg, e);
} else {
getLogger().warn(msg);
}
}
}
}
} catch (URISyntaxException e) {
getLogger().debug("Could not parse repository URL", e);
}
}
- for (Target.Unit unit : location.getUnits()) {
- String versionRange;
- if ("0.0.0".equals(unit.getVersion())) {
- versionRange = unit.getVersion();
- } else {
- // perfect version match
- versionRange = "[" + unit.getVersion() + "," + unit.getVersion() + "]";
- }
- resolver.addDependency(P2Resolver.TYPE_INSTALLABLE_UNIT, unit.getId(), versionRange);
- }
+ // TODO the target platform needs to be resolved separately and not treated as additional dependencies (bug 342808)
+// for (Target.Unit unit : location.getUnits()) {
+// String versionRange;
+// if ("0.0.0".equals(unit.getVersion())) {
+// versionRange = unit.getVersion();
+// } else {
+// // perfect version match
+// versionRange = "[" + unit.getVersion() + "," + unit.getVersion() + "]";
+// }
+// resolver.addDependency(P2Resolver.TYPE_INSTALLABLE_UNIT, unit.getId(), versionRange);
+// }
}
}
if (!isAllowConflictingDependencies(project, configuration)) {
List<P2ResolutionResult> results = resolver.resolveProject(resolutionContext, project.getBasedir());
MultiEnvironmentTargetPlatform multiPlatform = new MultiEnvironmentTargetPlatform();
// FIXME this is just wrong
for (int i = 0; i < configuration.getEnvironments().size(); i++) {
TargetEnvironment environment = configuration.getEnvironments().get(i);
P2ResolutionResult result = results.get(i);
DefaultTargetPlatform platform = newDefaultTargetPlatform(session, projects, result);
// addProjects( session, platform );
multiPlatform.addPlatform(environment, platform);
}
return multiPlatform;
} else {
P2ResolutionResult result = resolver.collectProjectDependencies(resolutionContext, project.getBasedir());
return newDefaultTargetPlatform(session, projects, result);
}
}
private boolean isAllowConflictingDependencies(MavenProject project, TargetPlatformConfiguration configuration) {
String packaging = project.getPackaging();
if (org.eclipse.tycho.ArtifactKey.TYPE_ECLIPSE_UPDATE_SITE.equals(packaging)
|| org.eclipse.tycho.ArtifactKey.TYPE_ECLIPSE_FEATURE.equals(packaging)) {
Boolean allow = configuration.getAllowConflictingDependencies();
if (allow != null) {
return allow.booleanValue();
}
}
// conflicting dependencies do not make sense for products and bundles
return false;
}
protected DefaultTargetPlatform newDefaultTargetPlatform(MavenSession session, Map<File, ReactorProject> projects,
P2ResolutionResult result) {
DefaultTargetPlatform platform = new DefaultTargetPlatform();
platform.addSite(new File(session.getLocalRepository().getBasedir()));
platform.addNonReactorUnits(result.getNonReactorUnits());
for (P2ResolutionResult.Entry entry : result.getArtifacts()) {
ArtifactKey key = new DefaultArtifactKey(entry.getType(), entry.getId(), entry.getVersion());
ReactorProject otherProject = projects.get(entry.getLocation());
if (otherProject != null) {
platform.addReactorArtifact(key, otherProject, entry.getClassifier(), entry.getInstallableUnits());
} else {
platform.addArtifactFile(key, entry.getLocation(), entry.getInstallableUnits());
}
}
return platform;
}
private List<Map<String, String>> getEnvironments(TargetPlatformConfiguration configuration) {
ArrayList<Map<String, String>> environments = new ArrayList<Map<String, String>>();
for (TargetEnvironment environment : configuration.getEnvironments()) {
Properties properties = new Properties();
properties.put(PlatformPropertiesUtils.OSGI_OS, environment.getOs());
properties.put(PlatformPropertiesUtils.OSGI_WS, environment.getWs());
properties.put(PlatformPropertiesUtils.OSGI_ARCH, environment.getArch());
ExecutionEnvironmentUtils.loadVMProfile(properties);
// TODO does not belong here
properties.put("org.eclipse.update.install.features", "true");
Map<String, String> map = new LinkedHashMap<String, String>();
for (Object key : properties.keySet()) {
map.put(key.toString(), properties.getProperty(key.toString()));
}
environments.add(map);
}
return environments;
}
private String getMirror(Target.Repository location, List<Mirror> mirrors) {
String url = location.getLocation();
String id = location.getId();
if (id == null) {
id = url;
}
ArtifactRepository repository = repositorySystem.createArtifactRepository(id, url, p2layout,
P2_REPOSITORY_POLICY, P2_REPOSITORY_POLICY);
Mirror mirror = repositorySystem.getMirror(repository, mirrors);
return mirror != null ? mirror.getUrl() : url;
}
public void initialize() throws InitializationException {
this.resolverFactory = equinox.getService(P2ResolverFactory.class);
this.generator = equinox.getService(DependencyMetadataGenerator.class, "(role-hint=dependency-only)");
this.sourcesGenerator = equinox.getService(DependencyMetadataGenerator.class, "(role-hint=source-bundle)");
}
public void injectDependenciesIntoMavenModel(MavenProject project, AbstractTychoProject projectType,
TargetPlatform targetPlatform, Logger logger) {
MavenDependencyInjector.injectMavenDependencies(project, targetPlatform, bundleReader, logger);
}
}
| true | true | protected TargetPlatform doResolvePlatform(final MavenSession session, final MavenProject project,
List<ReactorProject> reactorProjects, List<Dependency> dependencies, ResolutionContext resolutionContext,
P2Resolver resolver) {
TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
.getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);
Map<File, ReactorProject> projects = new HashMap<File, ReactorProject>();
resolver.setEnvironments(getEnvironments(configuration));
for (ReactorProject otherProject : reactorProjects) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("P2resolver.addMavenProject " + otherProject.getId());
}
projects.put(otherProject.getBasedir(), otherProject);
resolutionContext.addReactorArtifact(new ReactorArtifactFacade(otherProject, null));
Map<String, Set<Object>> dependencyMetadata = otherProject.getDependencyMetadata();
if (dependencyMetadata != null) {
for (String classifier : dependencyMetadata.keySet()) {
resolutionContext.addReactorArtifact(new ReactorArtifactFacade(otherProject, classifier));
}
}
}
if (dependencies != null) {
for (Dependency dependency : dependencies) {
resolver.addDependency(dependency.getType(), dependency.getArtifactId(), dependency.getVersion());
}
}
if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(configuration.getPomDependencies())) {
Set<String> projectIds = new HashSet<String>();
for (ReactorProject p : reactorProjects) {
String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
projectIds.add(key);
}
ArrayList<String> scopes = new ArrayList<String>();
scopes.add(Artifact.SCOPE_COMPILE);
Collection<Artifact> artifacts;
try {
artifacts = projectDependenciesResolver.resolve(project, scopes, session);
} catch (MultipleArtifactsNotFoundException e) {
Collection<Artifact> missing = new HashSet<Artifact>(e.getMissingArtifacts());
for (Iterator<Artifact> it = missing.iterator(); it.hasNext();) {
Artifact a = it.next();
String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
if (projectIds.contains(key)) {
it.remove();
}
}
if (!missing.isEmpty()) {
throw new RuntimeException("Could not resolve project dependencies", e);
}
artifacts = e.getResolvedArtifacts();
artifacts.removeAll(e.getMissingArtifacts());
} catch (AbstractArtifactResolutionException e) {
throw new RuntimeException("Could not resolve project dependencies", e);
}
List<Artifact> externalArtifacts = new ArrayList<Artifact>(artifacts.size());
for (Artifact artifact : artifacts) {
String key = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
artifact.getBaseVersion());
if (projectIds.contains(key)) {
// resolved to an older snapshot from the repo, we only want the current project in the reactor
continue;
}
externalArtifacts.add(artifact);
}
List<Artifact> explicitArtifacts = MavenDependencyInjector.filterInjectedDependencies(externalArtifacts); // needed when the resolution is done again for the test runtime
PomDependencyProcessor pomDependencyProcessor = new PomDependencyProcessor(session, repositorySystem,
getLogger());
pomDependencyProcessor.addPomDependenciesToResolutionContext(project, explicitArtifacts, resolutionContext);
}
for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
try {
URI uri = new URL(repository.getUrl()).toURI();
if (repository.getLayout() instanceof P2ArtifactRepositoryLayout) {
if (session.isOffline()) {
getLogger().debug(
"Offline mode, using local cache only for repository " + repository.getId() + " ("
+ repository.getUrl() + ")");
}
try {
Authentication auth = repository.getAuthentication();
if (auth != null) {
resolutionContext.setCredentials(uri, auth.getUsername(), auth.getPassword());
}
resolutionContext.addP2Repository(uri);
getLogger().debug(
"Added p2 repository " + repository.getId() + " (" + repository.getUrl() + ")");
} catch (Exception e) {
String msg = "Failed to access p2 repository " + repository.getId() + " ("
+ repository.getUrl() + "), will try to use local cache. Reason: " + e.getMessage();
if (getLogger().isDebugEnabled()) {
getLogger().warn(msg, e);
} else {
getLogger().warn(msg);
}
}
}
} catch (MalformedURLException e) {
getLogger().warn("Could not parse repository URL", e);
} catch (URISyntaxException e) {
getLogger().warn("Could not parse repository URL", e);
}
}
Target target = configuration.getTarget();
if (target != null) {
Set<URI> uris = new HashSet<URI>();
for (Target.Location location : target.getLocations()) {
String type = location.getType();
if (!"InstallableUnit".equalsIgnoreCase(type)) {
getLogger().warn("Target location type: " + type + " is not supported");
continue;
}
for (Target.Repository repository : location.getRepositories()) {
try {
URI uri = new URI(getMirror(repository, session.getRequest().getMirrors()));
if (uris.add(uri)) {
if (session.isOffline()) {
getLogger().debug("Ignored repository " + uri + " while in offline mode");
} else {
String id = repository.getId();
if (id != null) {
Server server = session.getSettings().getServer(id);
if (server != null) {
resolutionContext.setCredentials(uri, server.getUsername(),
server.getPassword());
} else {
getLogger().info(
"Unknown server id=" + id + " for repository location="
+ repository.getLocation());
}
}
try {
resolutionContext.addP2Repository(uri);
} catch (Exception e) {
String msg = "Failed to access p2 repository " + uri
+ ", will try to use local cache. Reason: " + e.getMessage();
if (getLogger().isDebugEnabled()) {
getLogger().warn(msg, e);
} else {
getLogger().warn(msg);
}
}
}
}
} catch (URISyntaxException e) {
getLogger().debug("Could not parse repository URL", e);
}
}
for (Target.Unit unit : location.getUnits()) {
String versionRange;
if ("0.0.0".equals(unit.getVersion())) {
versionRange = unit.getVersion();
} else {
// perfect version match
versionRange = "[" + unit.getVersion() + "," + unit.getVersion() + "]";
}
resolver.addDependency(P2Resolver.TYPE_INSTALLABLE_UNIT, unit.getId(), versionRange);
}
}
}
if (!isAllowConflictingDependencies(project, configuration)) {
List<P2ResolutionResult> results = resolver.resolveProject(resolutionContext, project.getBasedir());
MultiEnvironmentTargetPlatform multiPlatform = new MultiEnvironmentTargetPlatform();
// FIXME this is just wrong
for (int i = 0; i < configuration.getEnvironments().size(); i++) {
TargetEnvironment environment = configuration.getEnvironments().get(i);
P2ResolutionResult result = results.get(i);
DefaultTargetPlatform platform = newDefaultTargetPlatform(session, projects, result);
// addProjects( session, platform );
multiPlatform.addPlatform(environment, platform);
}
return multiPlatform;
} else {
P2ResolutionResult result = resolver.collectProjectDependencies(resolutionContext, project.getBasedir());
return newDefaultTargetPlatform(session, projects, result);
}
}
| protected TargetPlatform doResolvePlatform(final MavenSession session, final MavenProject project,
List<ReactorProject> reactorProjects, List<Dependency> dependencies, ResolutionContext resolutionContext,
P2Resolver resolver) {
TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
.getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);
Map<File, ReactorProject> projects = new HashMap<File, ReactorProject>();
resolver.setEnvironments(getEnvironments(configuration));
for (ReactorProject otherProject : reactorProjects) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("P2resolver.addMavenProject " + otherProject.getId());
}
projects.put(otherProject.getBasedir(), otherProject);
resolutionContext.addReactorArtifact(new ReactorArtifactFacade(otherProject, null));
Map<String, Set<Object>> dependencyMetadata = otherProject.getDependencyMetadata();
if (dependencyMetadata != null) {
for (String classifier : dependencyMetadata.keySet()) {
resolutionContext.addReactorArtifact(new ReactorArtifactFacade(otherProject, classifier));
}
}
}
if (dependencies != null) {
for (Dependency dependency : dependencies) {
resolver.addDependency(dependency.getType(), dependency.getArtifactId(), dependency.getVersion());
}
}
if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(configuration.getPomDependencies())) {
Set<String> projectIds = new HashSet<String>();
for (ReactorProject p : reactorProjects) {
String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
projectIds.add(key);
}
ArrayList<String> scopes = new ArrayList<String>();
scopes.add(Artifact.SCOPE_COMPILE);
Collection<Artifact> artifacts;
try {
artifacts = projectDependenciesResolver.resolve(project, scopes, session);
} catch (MultipleArtifactsNotFoundException e) {
Collection<Artifact> missing = new HashSet<Artifact>(e.getMissingArtifacts());
for (Iterator<Artifact> it = missing.iterator(); it.hasNext();) {
Artifact a = it.next();
String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
if (projectIds.contains(key)) {
it.remove();
}
}
if (!missing.isEmpty()) {
throw new RuntimeException("Could not resolve project dependencies", e);
}
artifacts = e.getResolvedArtifacts();
artifacts.removeAll(e.getMissingArtifacts());
} catch (AbstractArtifactResolutionException e) {
throw new RuntimeException("Could not resolve project dependencies", e);
}
List<Artifact> externalArtifacts = new ArrayList<Artifact>(artifacts.size());
for (Artifact artifact : artifacts) {
String key = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
artifact.getBaseVersion());
if (projectIds.contains(key)) {
// resolved to an older snapshot from the repo, we only want the current project in the reactor
continue;
}
externalArtifacts.add(artifact);
}
List<Artifact> explicitArtifacts = MavenDependencyInjector.filterInjectedDependencies(externalArtifacts); // needed when the resolution is done again for the test runtime
PomDependencyProcessor pomDependencyProcessor = new PomDependencyProcessor(session, repositorySystem,
getLogger());
pomDependencyProcessor.addPomDependenciesToResolutionContext(project, explicitArtifacts, resolutionContext);
}
for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
try {
URI uri = new URL(repository.getUrl()).toURI();
if (repository.getLayout() instanceof P2ArtifactRepositoryLayout) {
if (session.isOffline()) {
getLogger().debug(
"Offline mode, using local cache only for repository " + repository.getId() + " ("
+ repository.getUrl() + ")");
}
try {
Authentication auth = repository.getAuthentication();
if (auth != null) {
resolutionContext.setCredentials(uri, auth.getUsername(), auth.getPassword());
}
resolutionContext.addP2Repository(uri);
getLogger().debug(
"Added p2 repository " + repository.getId() + " (" + repository.getUrl() + ")");
} catch (Exception e) {
String msg = "Failed to access p2 repository " + repository.getId() + " ("
+ repository.getUrl() + "), will try to use local cache. Reason: " + e.getMessage();
if (getLogger().isDebugEnabled()) {
getLogger().warn(msg, e);
} else {
getLogger().warn(msg);
}
}
}
} catch (MalformedURLException e) {
getLogger().warn("Could not parse repository URL", e);
} catch (URISyntaxException e) {
getLogger().warn("Could not parse repository URL", e);
}
}
Target target = configuration.getTarget();
if (target != null) {
Set<URI> uris = new HashSet<URI>();
for (Target.Location location : target.getLocations()) {
String type = location.getType();
if (!"InstallableUnit".equalsIgnoreCase(type)) {
getLogger().warn("Target location type: " + type + " is not supported");
continue;
}
for (Target.Repository repository : location.getRepositories()) {
try {
URI uri = new URI(getMirror(repository, session.getRequest().getMirrors()));
if (uris.add(uri)) {
if (session.isOffline()) {
getLogger().debug("Ignored repository " + uri + " while in offline mode");
} else {
String id = repository.getId();
if (id != null) {
Server server = session.getSettings().getServer(id);
if (server != null) {
resolutionContext.setCredentials(uri, server.getUsername(),
server.getPassword());
} else {
getLogger().info(
"Unknown server id=" + id + " for repository location="
+ repository.getLocation());
}
}
try {
resolutionContext.addP2Repository(uri);
} catch (Exception e) {
String msg = "Failed to access p2 repository " + uri
+ ", will try to use local cache. Reason: " + e.getMessage();
if (getLogger().isDebugEnabled()) {
getLogger().warn(msg, e);
} else {
getLogger().warn(msg);
}
}
}
}
} catch (URISyntaxException e) {
getLogger().debug("Could not parse repository URL", e);
}
}
// TODO the target platform needs to be resolved separately and not treated as additional dependencies (bug 342808)
// for (Target.Unit unit : location.getUnits()) {
// String versionRange;
// if ("0.0.0".equals(unit.getVersion())) {
// versionRange = unit.getVersion();
// } else {
// // perfect version match
// versionRange = "[" + unit.getVersion() + "," + unit.getVersion() + "]";
// }
// resolver.addDependency(P2Resolver.TYPE_INSTALLABLE_UNIT, unit.getId(), versionRange);
// }
}
}
if (!isAllowConflictingDependencies(project, configuration)) {
List<P2ResolutionResult> results = resolver.resolveProject(resolutionContext, project.getBasedir());
MultiEnvironmentTargetPlatform multiPlatform = new MultiEnvironmentTargetPlatform();
// FIXME this is just wrong
for (int i = 0; i < configuration.getEnvironments().size(); i++) {
TargetEnvironment environment = configuration.getEnvironments().get(i);
P2ResolutionResult result = results.get(i);
DefaultTargetPlatform platform = newDefaultTargetPlatform(session, projects, result);
// addProjects( session, platform );
multiPlatform.addPlatform(environment, platform);
}
return multiPlatform;
} else {
P2ResolutionResult result = resolver.collectProjectDependencies(resolutionContext, project.getBasedir());
return newDefaultTargetPlatform(session, projects, result);
}
}
|
diff --git a/src/java/org/jdesktop/swingx/geom/Star2D.java b/src/java/org/jdesktop/swingx/geom/Star2D.java
index f0020692..ab29d01b 100644
--- a/src/java/org/jdesktop/swingx/geom/Star2D.java
+++ b/src/java/org/jdesktop/swingx/geom/Star2D.java
@@ -1,338 +1,338 @@
/*
* $Id$
*
* Dual-licensed under LGPL (Sun and Romain Guy) and BSD (Romain Guy).
*
* Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* Copyright (c) 2006 Romain Guy <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jdesktop.swingx.geom;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* <p>This class provides a star shape. A star is defined by two radii and a
* number of branches. Each branch spans between the two radii. The inner
* radius is the distance between the center of the star and the origin of the
* branches. The outer radius is the distance between the center of the star
* and the tips of the branches.</p>
*
* @author Romain Guy <[email protected]>
*/
public class Star2D implements Shape {
private Shape starShape;
private double x;
private double y;
private double innerRadius;
private double outerRadius;
private int branchesCount;
/**
* <p>Creates a new star whose center is located at the specified
* <code>x</code> and <code>y</code> coordinates. The number of branches
* and their length can be specified.</p>
*
* @param x the location of the star center
* @param y the location of the star center
* @param innerRadius the distance between the center of the star and the
* origin of the branches
* @param outerRadius the distance between the center of the star and the
* tip of the branches
* @param branchesCount the number of branches in this star; must be >= 3
* @throws IllegalArgumentException if <code>branchesCount<code> is < 3 or
* if <code>innerRadius</code> is >= <code>outerRadius</code>
*/
public Star2D(double x, double y,
double innerRadius, double outerRadius,
int branchesCount) {
if (branchesCount <= 2) {
throw new IllegalArgumentException("The number of branches must" +
" be >= 3.");
} else if (innerRadius >= outerRadius) {
throw new IllegalArgumentException("The inner radius must be < " +
"outer radius.");
}
this.x = x;
this.y = y;
this.innerRadius = innerRadius;
this.outerRadius = outerRadius;
this.branchesCount = branchesCount;
starShape = generateStar(x, y, innerRadius, outerRadius, branchesCount);
}
private static Shape generateStar(double x, double y,
double innerRadius, double outerRadius,
int branchesCount) {
GeneralPath path = new GeneralPath();
double outerAngleIncrement = 2 * Math.PI / branchesCount;
- double outerAngle = 0.0;
- double innerAngle = outerAngleIncrement / 2.0;
+ double outerAngle = branchesCount % 2 == 0 ? 0.0 : -(Math.PI / 2.0);
+ double innerAngle = (outerAngleIncrement / 2.0) + outerAngle;
x += outerRadius;
y += outerRadius;
float x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
float y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
float x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
float y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
path.moveTo(x1, y1);
path.lineTo(x2, y2);
outerAngle += outerAngleIncrement;
innerAngle += outerAngleIncrement;
for (int i = 1; i < branchesCount; i++) {
x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
path.lineTo(x1, y1);
x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
path.lineTo(x2, y2);
outerAngle += outerAngleIncrement;
innerAngle += outerAngleIncrement;
}
path.closePath();
return path;
}
/**
* <p>Sets the inner radius of the star, that is the distance between its
* center and the origin of the branches. The inner radius must always be
* lower than the outer radius.</p>
*
* @param innerRadius the distance between the center of the star and the
* origin of the branches
* @throws IllegalArgumentException if the inner radius is >= outer radius
*/
public void setInnerRadius(double innerRadius) {
if (innerRadius >= outerRadius) {
throw new IllegalArgumentException("The inner radius must be <" +
" outer radius.");
}
this.innerRadius = innerRadius;
starShape = generateStar(getX(), getY(), innerRadius, getOuterRadius(),
getBranchesCount());
}
/**
* <p>Sets location of the center of the star.</p>
*
* @param x the x location of the center of the star
*/
public void setX(double x) {
this.x = x;
starShape = generateStar(x, getY(), getInnerRadius(), getOuterRadius(),
getBranchesCount());
}
/**
* <p>Sets the location of the center of the star.</p>
*
* @param y the x location of the center of the star
*/
public void setY(double y) {
this.y = y;
starShape = generateStar(getX(), y, getInnerRadius(), getOuterRadius(),
getBranchesCount());
}
/**
* <p>Sets the outer radius of the star, that is the distance between its
* center and the tips of the branches. The outer radius must always be
* greater than the inner radius.</p>
*
* @param outerRadius the distance between the center of the star and the
* tips of the branches
* @throws IllegalArgumentException if the inner radius is >= outer radius
*/
public void setOuterRadius(double outerRadius) {
if (innerRadius >= outerRadius) {
throw new IllegalArgumentException("The outer radius must be > " +
"inner radius.");
}
this.outerRadius = outerRadius;
starShape = generateStar(getX(), getY(), getInnerRadius(), outerRadius,
getBranchesCount());
}
/**
* <p>Sets the number branches of the star. A star must always have at least
* 3 branches.</p>
*
* @param branchesCount the number of branches
* @throws IllegalArgumentException if <code>branchesCount</code> is <=2
*/
public void setBranchesCount(int branchesCount) {
if (branchesCount <= 2) {
throw new IllegalArgumentException("The number of branches must" +
" be >= 3.");
}
this.branchesCount = branchesCount;
starShape = generateStar(getX(), getY(), getInnerRadius(),
getOuterRadius(), branchesCount);
}
/**
* <p>Returns the location of the center of star.</p>
*
* @return the x coordinate of the center of the star
*/
public double getX() {
return x;
}
/**
* <p>Returns the location of the center of star.</p>
*
* @return the y coordinate of the center of the star
*/
public double getY() {
return y;
}
/**
* <p>Returns the distance between the center of the star and the origin
* of the branches.</p>
*
* @return the inner radius of the star
*/
public double getInnerRadius() {
return innerRadius;
}
/**
* <p>Returns the distance between the center of the star and the tips
* of the branches.</p>
*
* @return the outer radius of the star
*/
public double getOuterRadius() {
return outerRadius;
}
/**
* <p>Returns the number of branches of the star.</p>
*
* @return the number of branches, always >= 3
*/
public int getBranchesCount() {
return branchesCount;
}
/**
* {@inheritDoc}
*/
public Rectangle getBounds() {
return starShape.getBounds();
}
/**
* {@inheritDoc}
*/
public Rectangle2D getBounds2D() {
return starShape.getBounds2D();
}
/**
* {@inheritDoc}
*/
public boolean contains(double x, double y) {
return starShape.contains(x, y);
}
/**
* {@inheritDoc}
*/
public boolean contains(Point2D p) {
return starShape.contains(p);
}
/**
* {@inheritDoc}
*/
public boolean intersects(double x, double y, double w, double h) {
return starShape.intersects(x, y, w, h);
}
/**
* {@inheritDoc}
*/
public boolean intersects(Rectangle2D r) {
return starShape.intersects(r);
}
/**
* {@inheritDoc}
*/
public boolean contains(double x, double y, double w, double h) {
return starShape.contains(x, y, w, h);
}
/**
* {@inheritDoc}
*/
public boolean contains(Rectangle2D r) {
return starShape.contains(r);
}
/**
* {@inheritDoc}
*/
public PathIterator getPathIterator(AffineTransform at) {
return starShape.getPathIterator(at);
}
/**
* {@inheritDoc}
*/
public PathIterator getPathIterator(AffineTransform at, double flatness) {
return starShape.getPathIterator(at, flatness);
}
}
| true | true | private static Shape generateStar(double x, double y,
double innerRadius, double outerRadius,
int branchesCount) {
GeneralPath path = new GeneralPath();
double outerAngleIncrement = 2 * Math.PI / branchesCount;
double outerAngle = 0.0;
double innerAngle = outerAngleIncrement / 2.0;
x += outerRadius;
y += outerRadius;
float x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
float y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
float x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
float y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
path.moveTo(x1, y1);
path.lineTo(x2, y2);
outerAngle += outerAngleIncrement;
innerAngle += outerAngleIncrement;
for (int i = 1; i < branchesCount; i++) {
x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
path.lineTo(x1, y1);
x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
path.lineTo(x2, y2);
outerAngle += outerAngleIncrement;
innerAngle += outerAngleIncrement;
}
path.closePath();
return path;
}
| private static Shape generateStar(double x, double y,
double innerRadius, double outerRadius,
int branchesCount) {
GeneralPath path = new GeneralPath();
double outerAngleIncrement = 2 * Math.PI / branchesCount;
double outerAngle = branchesCount % 2 == 0 ? 0.0 : -(Math.PI / 2.0);
double innerAngle = (outerAngleIncrement / 2.0) + outerAngle;
x += outerRadius;
y += outerRadius;
float x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
float y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
float x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
float y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
path.moveTo(x1, y1);
path.lineTo(x2, y2);
outerAngle += outerAngleIncrement;
innerAngle += outerAngleIncrement;
for (int i = 1; i < branchesCount; i++) {
x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
path.lineTo(x1, y1);
x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
path.lineTo(x2, y2);
outerAngle += outerAngleIncrement;
innerAngle += outerAngleIncrement;
}
path.closePath();
return path;
}
|
diff --git a/src/java/is/idega/block/family/business/impl/FamilyHelperImpl.java b/src/java/is/idega/block/family/business/impl/FamilyHelperImpl.java
index 7b8921f..ac7567b 100644
--- a/src/java/is/idega/block/family/business/impl/FamilyHelperImpl.java
+++ b/src/java/is/idega/block/family/business/impl/FamilyHelperImpl.java
@@ -1,1017 +1,1017 @@
package is.idega.block.family.business.impl;
import is.idega.block.family.business.FamilyConstants;
import is.idega.block.family.business.FamilyHelper;
import is.idega.block.family.business.FamilyLogic;
import is.idega.block.family.business.FamilyRelationsHelper;
import is.idega.block.family.business.NoChildrenFound;
import is.idega.block.family.business.NoParentFound;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.idega.builder.bean.AdvancedProperty;
import com.idega.core.business.DefaultSpringBean;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.localisation.business.ICLocaleBusiness;
import com.idega.core.localisation.data.ICLanguage;
import com.idega.core.localisation.data.ICLanguageHome;
import com.idega.core.location.data.Address;
import com.idega.core.location.data.Country;
import com.idega.core.location.data.CountryHome;
import com.idega.core.location.data.PostalCode;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.data.IDORelationshipException;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.ArrayUtil;
import com.idega.util.CoreConstants;
import com.idega.util.ListUtil;
import com.idega.util.StringUtil;
import com.idega.util.expression.ELUtil;
/**
* Implementation for {@link FamilyHelper}
*
* @author <a href="mailto:[email protected]">Valdas Žemaitis</a>
* @version $Revision: 1.0 $
*
* Last modified: $Date: 2009.09.30 18:43:56 $ by: $Author: valdas $
*/
@Scope(BeanDefinition.SCOPE_SINGLETON)
@Service(FamilyHelper.BEAN_IDENTIFIER)
public class FamilyHelperImpl extends DefaultSpringBean implements FamilyHelper {
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getTeenagesOfCurrentUser()
*/
@Override
public Map<Locale, Map<String, String>> getTeenagersOfCurrentUser() {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null)
return Collections.emptyMap();
Map<Locale, Map<String, String>> teenagers = new HashMap<Locale, Map<String, String>>();
Map<String, String> childrenInfo = new LinkedHashMap<String, String>();
childrenInfo.put(CoreConstants.EMPTY, iwrb.getLocalizedString("select_your_child", "Select your child"));
Locale locale = getCurrentLocale();
teenagers.put(locale, childrenInfo);
User currentUser = getCurrentUser();
if (currentUser == null) {
getLogger().info("User must be logged in!");
return teenagers;
}
FamilyLogic familyLogic = getServiceInstance(FamilyLogic.class);
if (familyLogic == null)
return teenagers;
int maxAge = Integer.valueOf(getApplication().getSettings().getProperty("max_music_student_age", String.valueOf(16)));
Collection<User> teenagersOfCurrentUser = null;
try {
teenagersOfCurrentUser = familyLogic.getChildrenForUserUnderAge(currentUser, maxAge);
} catch (NoChildrenFound e) {
getLogger().info(currentUser + " doesn't have children younger than " + maxAge + " years");
return teenagers;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Some error occurred while getting teenagers for: " + currentUser, e);
return teenagers;
} catch (Exception e) {
getLogger().log(Level.WARNING, "Some error occurred while getting teenagers for: " + currentUser, e);
return teenagers;
}
if (ListUtil.isEmpty(teenagersOfCurrentUser)) {
getLogger().warning(currentUser + " doesn't have children younger than " + maxAge + " years");
return teenagers;
}
List<AdvancedProperty> children = new ArrayList<AdvancedProperty>();
for (User teenage : teenagersOfCurrentUser)
children.add(new AdvancedProperty(teenage.getId(), teenage.getName()));
doSortValues(children, childrenInfo, locale);
return teenagers;
}
@Override
public String getSpouseEmail() {
try {
return getApplicantServices().getSpouseEmail();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error getting spouse email", e);
}
return CoreConstants.EMPTY;
}
@Override
public String getSpouseMobile() {
try {
return getApplicantServices().getSpouseMobile();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error getting spouse mobile", e);
}
return CoreConstants.EMPTY;
}
@Override
public String getSpouseName() {
try {
return getApplicantServices().getSpouseName();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error getting a name of spouse", e);
}
return CoreConstants.EMPTY;
}
@Override
public String getSpousePersonalId() {
try {
return getApplicantServices().getSpousePersonalId();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error getting spouse personal id",
e);
}
return CoreConstants.EMPTY;
}
@Override
public String getSpouseTelephone() {
try {
return getApplicantServices().getSpouseTelephone();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error getting spouse telephone", e);
}
return CoreConstants.EMPTY;
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getNameOfChild(
* java.lang.String)
*/
@Override
public String getName(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
return user.getName();
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getSocialCodeOfChild(
* java.lang.String)
*/
@Override
public String getSocialSecurityCode(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
return user.getPersonalID();
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getMainAddressOfChild(
* java.lang.String)
*/
@Override
public String getAddress(String userId) {
Address address = getAddressByUserId(userId);
if (address == null) {
return CoreConstants.EMPTY;
}
String tmpString = null;
String addressString = null;
tmpString = address.getName();
if (tmpString != null) {
addressString = tmpString + CoreConstants.COMMA + CoreConstants.SPACE;
tmpString = null;
}
PostalCode postalCode = address.getPostalCode();
if (postalCode != null) {
tmpString = postalCode.getPostalCode();
}
if (tmpString != null) {
addressString = addressString + tmpString + CoreConstants.SPACE;
}
return addressString;
}
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getAddressByUserId(java.lang.String)
*/
@Override
public Address getAddressByUserId(String userId) {
User user = getUser(userId);
if (user == null) {
return null;
}
Address address = null;
try {
address = user.getUsersMainAddress();
} catch (EJBException e) {
getLogger().log(Level.WARNING, "Adress not found.");
return null;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Adress not found.", e);
return null;
}
return address;
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getPostalCodeOfChild(
* java.lang.String)
*/
@Override
public String getPostalCode(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
Address address = null;
try {
address = user.getUsersMainAddress();
} catch (EJBException e) {
getLogger().log(Level.WARNING, "Postal code not found");
return CoreConstants.EMPTY;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Postal code not found", e);
return CoreConstants.EMPTY;
}
if (address == null) {
return CoreConstants.EMPTY;
}
PostalCode postalCode = address.getPostalCode();
if (postalCode == null) {
return CoreConstants.EMPTY;
}
return postalCode.getPostalCode();
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getHomeTelephoneOfChild(
* java.lang.String)
*/
@Override
public String getHomePhoneNumber(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
try {
Phone phone = user.getUsersHomePhone();
if (phone == null) {
return CoreConstants.EMPTY;
}
return phone.getNumber();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Phone number not found.", e);
return CoreConstants.EMPTY;
}
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getMobileTelephoneOfChild(java.lang.String)
*/
@Override
public String getCellPhoneNumber(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
try {
Phone phone = user.getUsersMobilePhone();
if (phone == null) {
return CoreConstants.EMPTY;
}
return phone.getNumber();
} catch (EJBException e) {
getLogger().log(Level.WARNING, "Phone number not found.");
return CoreConstants.EMPTY;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Phone number not found.", e);
return CoreConstants.EMPTY;
}
}
/*
* (non-Javadoc)
*
* @see
* is.idega.block.family.business.FamilyHelper#getWorkPhoneNumber(java.lang
* .String)
*/
@Override
public String getWorkPhoneNumber(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
try {
Phone phone = user.getUsersWorkPhone();
if (phone == null) {
return CoreConstants.EMPTY;
}
return phone.getNumber();
} catch (EJBException e) {
getLogger().log(Level.WARNING, "Phone number not found.");
return CoreConstants.EMPTY;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Phone number not found.", e);
return CoreConstants.EMPTY;
}
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getEMailOfChild(
* java.lang.String)
*/
@Override
public String getEMailAddress(String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
try {
Email email = user.getUsersEmail();
if (email == null) {
return CoreConstants.EMPTY;
}
return email.getEmailAddress();
} catch (EJBException e) {
getLogger().log(Level.WARNING, "e-mail address not found.");
return CoreConstants.EMPTY;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "e-mail address not found.", e);
return CoreConstants.EMPTY;
}
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getLanguageSelectionMapOfCurrentUser()
*/
@Override
public Map<Locale, Map<String, String>> getLanguages() {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null)
return Collections.emptyMap();
Map<String, String> languagesMap = new LinkedHashMap<String, String>();
Map<Locale, Map<String, String>> languageSelection = new HashMap<Locale, Map<String, String>>();
languagesMap.put(CoreConstants.EMPTY, iwrb.getLocalizedString("select_your_language", "Select your language"));
Locale currentLocale = getCurrentLocale();
languageSelection.put(currentLocale, languagesMap);
Locale[] locales = Locale.getAvailableLocales();
if (ArrayUtil.isEmpty(locales))
return languageSelection;
List<AdvancedProperty> languages = new ArrayList<AdvancedProperty>();
for (Locale locale: locales)
languages.add(new AdvancedProperty(locale.getLanguage(), locale.getDisplayLanguage(locale)));
doSortValues(languages, languagesMap, currentLocale);
return languageSelection;
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getLanguageOfCurrentUser(int)
*/
@Override
public String getLanguage(int numberOfLanguage, String userId) {
User user = getUser(userId);
if (user == null) {
return CoreConstants.EMPTY;
}
List<ICLanguage> languageList = null;
try {
languageList = new ArrayList<ICLanguage>(user.getLanguages());
} catch (IDORelationshipException e) {
return CoreConstants.EMPTY;
}
if (ListUtil.isEmpty(languageList))
return CoreConstants.EMPTY;
ICLanguage icl = languageList.get(numberOfLanguage);
if (icl == null)
return CoreConstants.EMPTY;
return icl.getIsoAbbreviation();
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getMotherLanguageSelectionMapOfCurrentUser()
*/
@Override
public String getMotherLanguage(String userId) {
User user = getUser(userId);
if (user == null)
return CoreConstants.EMPTY;
String prefferedLocale = user.getPreferredLocale();
if (StringUtil.isEmpty(prefferedLocale))
return getLanguage(0, userId);
Locale locale = ICLocaleBusiness.getLocaleFromLocaleString(prefferedLocale);
if (locale == null)
return CoreConstants.EMPTY;
ICLanguage icl = null;
try {
ICLanguageHome icLanguageHome = (ICLanguageHome) IDOLookup.getHome(ICLanguage.class);
icl = icLanguageHome.findByISOAbbreviation(locale.getLanguage());
} catch (IDOLookupException e) {
getLogger().log(Level.WARNING, "Unable to get languages service.");
return CoreConstants.EMPTY;
} catch (FinderException e) {
getLogger().log(Level.WARNING, "Language not found.");
return CoreConstants.EMPTY;
}
if (icl == null)
return CoreConstants.EMPTY;
return icl.getIsoAbbreviation();
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getSecondLanguageOfCurrentUser()
*/
@Override
public String getSecondLanguage(String userId) {
return getLanguage(1, userId);
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getThirdLanguageOfCurrentUser()
*/
@Override
public String getThirdLanguage(String userId) {
return getLanguage(2, userId);
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getFourthLanguageOfCurrentUser()
*/
@Override
public String getFourthLanguage(String userId) {
return getLanguage(3, userId);
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getCountrySelectionMapOfCurrentUser()
*/
@Override
public Map<Locale, Map<String, String>> getCountries() {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null)
return Collections.emptyMap();
Map<String, String> countryMap = new LinkedHashMap<String, String>();
countryMap.put(CoreConstants.EMPTY, iwrb.getLocalizedString("select_your_country", "Select your country"));
Map<Locale, Map<String, String>> countrySelection = new HashMap<Locale, Map<String, String>>();
Locale currentLocale = getCurrentLocale();
countrySelection.put(currentLocale, countryMap);
Locale[] locales = Locale.getAvailableLocales();
if (ArrayUtil.isEmpty(locales))
return countrySelection;
List<AdvancedProperty> countries = new ArrayList<AdvancedProperty>();
for (Locale locale: locales) {
String country = locale.getCountry();
if (StringUtil.isEmpty(country))
continue;
countries.add(new AdvancedProperty(country, locale.getDisplayCountry(locale)));
}
doSortValues(countries, countryMap, currentLocale);
return countrySelection;
}
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getCountriesList()
*/
@SuppressWarnings("unchecked")
@Override
public Collection<Country> getCountriesList() {
Collection<Country> countryCollection = null;
try {
CountryHome countryHome = (CountryHome) IDOLookup.getHome(Country.class);
countryCollection = countryHome.findAll();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Unable to get list of countries.", e);
return null;
}
return countryCollection;
}
/*
* (non-Javadoc)
*
* @see
* is.idega.block.family.business.FamilyHelper#getCountry(java.lang.String)
*/
@Override
public Country getCountry(String userId) {
try {
Address address = getAddressByUserId(userId);
if (address == null) {
return null;
}
return address.getCountry();
} catch (EJBException e) {
getLogger().log(Level.WARNING, "Unable to get country of user");
return null;
}
}
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getCountryName(java.lang.String)
*/
@Override
public String getCountryName(String userId) {
Country country = getCountry(userId);
if (country == null) {
return CoreConstants.EMPTY;
}
return country.getName();
}
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getCountryISOgetIsoAbbreviation(java.lang.String)
*/
@Override
public String getCountryISOgetIsoAbbreviation(String userId) {
Country country = getCountry(userId);
if (country == null) {
return CoreConstants.EMPTY;
}
return country.getIsoAbbreviation();
}
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getCity(java.lang.String)
*/
@Override
public String getCity(String userId) {
Address address = getAddressByUserId(userId);
if (address == null) {
return CoreConstants.EMPTY;
}
return address.getCity();
}
/*
* (non-Javadoc)
* @see is.idega.block.family.business.FamilyHelper#getRelation(java.lang.String, java.lang.String)
*/
@Override
public String getRelation(String childId, String relatedUserId) {
User user = getUser(childId);
User userRelation = getUser(relatedUserId);
if (user == null || userRelation == null) {
return CoreConstants.EMPTY;
}
FamilyLogic familyLogic = getServiceInstance(FamilyLogic.class);
if (familyLogic == null) {
return CoreConstants.EMPTY;
}
com.idega.user.data.Gender gender = userRelation.getGender();
try {
if (familyLogic.isChildOf(user, userRelation)) {
if (gender == null) {
return CoreConstants.EMPTY;
} else if (gender.isMaleGender()) {
return FamilyConstants.RELATION_FATHER;
} else if (gender.isFemaleGender()) {
return FamilyConstants.RELATION_MOTHER;
}
}
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Relation not found.", e);
return CoreConstants.EMPTY;
}
try {
if (familyLogic.isCustodianOf(userRelation, user)) {
if (gender == null) {
return FamilyConstants.RELATION_GUARDIAN;
} else if (gender.isMaleGender()) {
return FamilyConstants.RELATION_STEPFATHER;
} else if (gender.isFemaleGender()) {
return FamilyConstants.RELATION_STEPMOTHER;
}
}
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Relation not found.", e);
return CoreConstants.EMPTY;
}
try {
if (familyLogic.isSiblingOf(userRelation, user)) {
return FamilyConstants.RELATION_SIBLING;
}
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Relation not found.", e);
return CoreConstants.EMPTY;
}
return CoreConstants.EMPTY;
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#
* getRelationOfCurrentUser()
*/
@Override
public Map<Locale, Map<String, String>> getRelationNames() {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null)
return Collections.emptyMap();
Map<String, String> availableRelations = new LinkedHashMap<String, String>();
availableRelations.put(CoreConstants.EMPTY, iwrb.getLocalizedString("select_your_relation", "Select your relation"));
List<AdvancedProperty> relations = new ArrayList<AdvancedProperty>();
relations.add(new AdvancedProperty(FamilyConstants.RELATION_MOTHER, iwrb.getLocalizedString("mother", "Mother")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_FATHER, iwrb.getLocalizedString("father", "Father")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_STEPMOTHER, iwrb.getLocalizedString("stepmother", "Stepmother")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_STEPFATHER, iwrb.getLocalizedString("stepfather", "Stepfather")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_GRANDMOTHER, iwrb.getLocalizedString("grandmother", "Grandmother")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_GRANDFATHER, iwrb.getLocalizedString("grandfather", "Grandfather")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_SIBLING, iwrb.getLocalizedString("sibling", "Sibling")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_GUARDIAN, iwrb.getLocalizedString("guardian", "Guardian")));
relations.add(new AdvancedProperty(FamilyConstants.RELATION_OTHER, iwrb.getLocalizedString("other", "Other")));
Map<Locale, Map<String, String>> relationsWithLocale = new HashMap<Locale, Map<String,String>>();
Locale locale = getCurrentLocale();
relationsWithLocale.put(locale, availableRelations);
doSortValues(relations, availableRelations, locale);
return relationsWithLocale;
}
/*
* (non-Javadoc)
*
* @see
* is.idega.block.family.business.FamilyHelper#getMaritalStatusOfCurrentUser
* ()
*/
@SuppressWarnings("unchecked")
@Override
public String getMaritalStatus(String userId) {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null) {
return CoreConstants.EMPTY;
}
FamilyLogic familyLogic = getServiceInstance(FamilyLogic.class);
User user = getUser(userId);
boolean childHasOtherParent = false;
if (familyLogic == null) {
return CoreConstants.EMPTY;
}
if (user == null) {
return CoreConstants.EMPTY;
}
Collection<User> childrenOfCurrentUser = null;
Collection<User> parentsOfChild = null;
try {
if (familyLogic.hasPersonGotSpouse(user)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_MARRIED, "Married");
}
if (familyLogic.hasPersonGotCohabitant(user)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_COHABITANT, "Cohabitant");
}
childrenOfCurrentUser = familyLogic.getChildrenFor(user);
if (ListUtil.isEmpty(childrenOfCurrentUser)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
List<User> childList = new ArrayList<User>(childrenOfCurrentUser);
parentsOfChild = familyLogic.getParentsFor(childList.get(0));
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Unable to get info about spouse.",
e);
return CoreConstants.EMPTY;
} catch (NoParentFound e) {
getLogger().log(Level.SEVERE, "Something went very wrong.", e);
return CoreConstants.EMPTY;
} catch (NoChildrenFound e) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
for (User parent : parentsOfChild) {
if (!parent.equals(user)) {
childHasOtherParent = true;
}
}
if (childHasOtherParent) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_DIVORCED, "Divorced");
} else {
- return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_WIDOWED, "Widowed");
+ return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
}
/*
* (non-Javadoc)
*
* @see is.idega.block.family.business.FamilyHelper#getCurrentParent()
*/
@Override
public String getCurrentParent(String childId) {
if (isWrongId(childId)) {
return CoreConstants.EMPTY;
}
User currentUser = getCurrentUser();
if (currentUser == null) {
currentUser = getCurrentUser();
}
if (currentUser == null) {
return CoreConstants.EMPTY;
}
Collection<User> parents = getParents(childId);
for (User parent : parents) {
if (currentUser.equals(parent)) {
return currentUser.getId();
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see
* is.idega.block.family.business.FamilyHelper#getAnotherParent(java.lang
* .String)
*/
@Override
public String getAnotherParent(String childId) {
User user = getUser(childId);
if (user == null) {
return CoreConstants.EMPTY;
}
Collection<User> parents = getParents(childId);
if (parents == null) {
return CoreConstants.EMPTY;
}
User currentParent = getUser(getCurrentParent(childId));
if (currentParent == null) {
return CoreConstants.EMPTY;
}
for (User parent : parents) {
if (!currentParent.equals(parent)) {
return parent.getId();
}
}
return CoreConstants.EMPTY;
}
private FamilyRelationsHelper getApplicantServices() {
FamilyRelationsHelper applicantServices = null;
try {
applicantServices = ELUtil.getInstance().getBean(
FamilyRelationsHelperImpl.BEAN_IDENTIFIER);
} catch (Exception e) {
getLogger().log(Level.WARNING,
"Error getting bean " + FamilyRelationsHelper.class, e);
}
return applicantServices;
}
/**
* <p>Parents of user.</p>
* @param userId some {@link User#getPrimaryKey()}, who's parents yout want to get.
* @return parents in {@link User} form.
*/
@SuppressWarnings("unchecked")
private Collection<User> getParents(String userId) {
FamilyLogic familyLogic = getServiceInstance(FamilyLogic.class);
User user = getUser(userId);
Collection<User> parents = null;
if (user == null) {
return null;
}
try {
parents = familyLogic.getParentsFor(user);
return parents;
} catch (NoParentFound e) {
getLogger().log(Level.WARNING, "Parent not found");
return null;
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Unable to get parents of user.", e);
return null;
}
}
/**
* @return {@link com.idega.user.business.UserBusinessBean}
*/
private UserBusiness getUserBusiness() {
return getServiceInstance(UserBusiness.class);
}
/**
* @param id {@link String} of {@link User#getPrimaryKey()}
* @return {@link User} by id.
*/
private User getUser(String id) {
if (isWrongId(id)) {
return null;
}
try {
return getUserBusiness().getUser(Integer.valueOf(id));
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Unable to get user by ID: " + id);
return null;
} catch (NumberFormatException e) {
getLogger().log(Level.WARNING, "No such user. ID: " + id);
return null;
}
}
/**
* <p>Helping method, checks for wrong id.</p>
* @param id of something.
* @return <code>true</code> if id does not contain {, }, CoreConstants#EMPTY, -1.
* <code>false</code> otherwise.
* @author <a href="mailto:[email protected]">Martynas Stakė</a>
*/
private boolean isWrongId(String id){
if (StringUtil.isEmpty(id)) {
return Boolean.TRUE;
}
if (id.contains(CoreConstants.CURLY_BRACKET_LEFT)
|| id.contains(CoreConstants.CURLY_BRACKET_RIGHT)) {
return Boolean.TRUE;
}
if (id.equals("-1")) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
| true | true | public String getMaritalStatus(String userId) {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null) {
return CoreConstants.EMPTY;
}
FamilyLogic familyLogic = getServiceInstance(FamilyLogic.class);
User user = getUser(userId);
boolean childHasOtherParent = false;
if (familyLogic == null) {
return CoreConstants.EMPTY;
}
if (user == null) {
return CoreConstants.EMPTY;
}
Collection<User> childrenOfCurrentUser = null;
Collection<User> parentsOfChild = null;
try {
if (familyLogic.hasPersonGotSpouse(user)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_MARRIED, "Married");
}
if (familyLogic.hasPersonGotCohabitant(user)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_COHABITANT, "Cohabitant");
}
childrenOfCurrentUser = familyLogic.getChildrenFor(user);
if (ListUtil.isEmpty(childrenOfCurrentUser)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
List<User> childList = new ArrayList<User>(childrenOfCurrentUser);
parentsOfChild = familyLogic.getParentsFor(childList.get(0));
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Unable to get info about spouse.",
e);
return CoreConstants.EMPTY;
} catch (NoParentFound e) {
getLogger().log(Level.SEVERE, "Something went very wrong.", e);
return CoreConstants.EMPTY;
} catch (NoChildrenFound e) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
for (User parent : parentsOfChild) {
if (!parent.equals(user)) {
childHasOtherParent = true;
}
}
if (childHasOtherParent) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_DIVORCED, "Divorced");
} else {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_WIDOWED, "Widowed");
}
}
| public String getMaritalStatus(String userId) {
IWResourceBundle iwrb = getResourceBundle(getBundle(FamilyConstants.IW_BUNDLE_IDENTIFIER));
if (iwrb == null) {
return CoreConstants.EMPTY;
}
FamilyLogic familyLogic = getServiceInstance(FamilyLogic.class);
User user = getUser(userId);
boolean childHasOtherParent = false;
if (familyLogic == null) {
return CoreConstants.EMPTY;
}
if (user == null) {
return CoreConstants.EMPTY;
}
Collection<User> childrenOfCurrentUser = null;
Collection<User> parentsOfChild = null;
try {
if (familyLogic.hasPersonGotSpouse(user)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_MARRIED, "Married");
}
if (familyLogic.hasPersonGotCohabitant(user)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_COHABITANT, "Cohabitant");
}
childrenOfCurrentUser = familyLogic.getChildrenFor(user);
if (ListUtil.isEmpty(childrenOfCurrentUser)) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
List<User> childList = new ArrayList<User>(childrenOfCurrentUser);
parentsOfChild = familyLogic.getParentsFor(childList.get(0));
} catch (RemoteException e) {
getLogger().log(Level.WARNING, "Unable to get info about spouse.",
e);
return CoreConstants.EMPTY;
} catch (NoParentFound e) {
getLogger().log(Level.SEVERE, "Something went very wrong.", e);
return CoreConstants.EMPTY;
} catch (NoChildrenFound e) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
for (User parent : parentsOfChild) {
if (!parent.equals(user)) {
childHasOtherParent = true;
}
}
if (childHasOtherParent) {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_DIVORCED, "Divorced");
} else {
return iwrb.getLocalizedString(FamilyConstants.MARITAL_STATUS_SINGLE, "Single");
}
}
|
diff --git a/melati/src/main/java/org/melati/test/ConfigServletTest.java b/melati/src/main/java/org/melati/test/ConfigServletTest.java
index 27444051d..147784b65 100644
--- a/melati/src/main/java/org/melati/test/ConfigServletTest.java
+++ b/melati/src/main/java/org/melati/test/ConfigServletTest.java
@@ -1,179 +1,181 @@
/*
* $Source$
* $Revision$
*
* Copyright (C) 2000 Tim Joyce
*
* Part of Melati (http://melati.org), a framework for the rapid
* development of clean, maintainable web applications.
*
* Melati is free software; Permission is granted to copy, distribute
* and/or modify this software under the terms either:
*
* a) 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,
*
* or
*
* b) any version of the Melati Software License, as published
* at http://melati.org
*
* You should have received a copy of the GNU General Public License and
* the Melati Software License along with this program;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
* GNU General Public License and visit http://melati.org to obtain the
* Melati Software License.
*
* Feel free to contact the Developers of Melati (http://melati.org),
* if you would like to work out a different arrangement than the options
* outlined here. It is our intention to allow Melati to be used by as
* wide an audience as possible.
*
* 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.
*
* Contact details for copyright holder:
*
* Tim Joyce <[email protected]>
* http://paneris.org/
* 68 Sandbanks Rd, Poole, Dorset. BH14 8BY. UK
*/
package org.melati.test;
import java.io.*;
import java.util.Hashtable;
import javax.servlet.ServletException;
import org.melati.servlet.*;
import org.melati.Melati;
import org.melati.MelatiConfig;
import org.melati.util.MelatiBugMelatiException;
import org.melati.util.MelatiWriter;
import org.melati.util.MelatiException;
import org.melati.util.ExceptionUtils;
public class ConfigServletTest extends ConfigServlet {
protected void doConfiguredRequest(Melati melati)
throws ServletException, IOException {
String method = melati.getMethod();
if (method != null) {
if (method.equals("Upload")) {
Hashtable fields = null;
try {
InputStream in = melati.getRequest().getInputStream();
MultipartDataDecoder decoder=
new MultipartDataDecoder(melati,
in,
melati.getRequest().getContentType(),
melati.getConfig().getFormDataAdaptorFactory());
fields = decoder.parseData();
}
catch (IOException e) {
melati.getWriter().write(
"There was some error uploading your file:" +
ExceptionUtils.stackTrace(e));
return;
}
MultipartFormField field = (MultipartFormField)fields.get("file");
if (field == null) {
melati.getWriter().write("No file was uploaded");
return;
}
byte[] data = field.getData();
melati.getResponse().setContentType(field.getContentType());
OutputStream output = melati.getResponse().getOutputStream();
output.write(data);
output.close();
return;
}
}
MelatiConfig config = melati.getConfig();
melati.getResponse().setContentType("text/html");
MelatiWriter output = melati.getWriter();
output.write(
"<html><head><title>ConfigServlet Test</title></head><body><h2> " +
"ConfigServlet Test</h2><p>This servlet tests your basic melati " +
"configuration. If you can read this message, it means that you have " +
"successfully created a Melati and a Melati, using the configuration " +
"given in org.melati.MelatiServlet.properties. Please note that this " +
"servlet does not construct a POEM session or initialise a template " +
"engine.</p><h4>Your Melati is configured with the following parameters: " +
"</h4><table><tr><td>TemplateEngine</td><td>" +
config.getTemplateEngine().getClass().getName() +
"</td></tr><tr><td>AccessHandler</td><td>" +
config.getAccessHandler().getClass().getName() +
"</td></tr><tr><td>FormDataAdaptorFactory</td><td>" +
config.getFormDataAdaptorFactory().getClass().getName() +
"</td></tr><tr><td>Locale</td><td>" +
config.getLocale().getClass().getName() +
"</td></tr><tr><td>TempletLoader</td><td>" +
config.getTempletLoader().getClass().getName() +
"</td></tr><tr><td>JavascriptLibraryURL</td><td>" +
config.getJavascriptLibraryURL() +
"</td></tr><tr><td>StaticURL</td><td>" +
config.getStaticURL() + "</td></tr></table>" +
"<h4>This servlet was called with the following Method (taken from " +
"melati.getMethod()): " +
melati.getMethod() +
"</h4><h4>Further Testing:</h4>You can test melati Exception handling by " +
"clicking <a href=" +
melati.getSameURL() +
"/Exception>Exception</a><br>You can test melati Redirect " +
"handling by clicking <a href=" +
melati.getSameURL() +
"/Redirect>Redirect</a><br>You can test your " +
"POEM setup (connecting to logical database <tt>melatitest</tt>) by " +
"clicking <a href=" +
melati.getZoneURL() +
"/org.melati.test.PoemServletTest/melatitest/>" +
"org.melati.test.PoemServletTest/melatitest/</a><br>" +
- "<form method=\"post\" action=\"Upload\" enctype=\"multipart/form-data\" target=_blank>" +
+ "<form method=\"post\" action=\"" +
+ melati.getSameURL() +
+ "/Upload\" enctype=\"multipart/form-data\" target=_blank>" +
"You can upload a file here:<br>" +
"<input type=hidden name=upload value=yes>" +
"<input type=\"file\" name=\"file\" enctype=\"multipart/form-data\">" +
"<input type=\"submit\" name=\"Submit\" value=\"Upload file\"><br>" +
getUploadMessage(melati) +
"</form>");
if (method != null) {
if (method.equals("Exception"))
throw new MelatiBugMelatiException("It got caught!");
if (method.equals("Redirect")) {
melati.getResponse().sendRedirect("http://www.melati.org");
return;
}
}
}
/**
* this simply demonstrates how to use a different melati configuration
*/
protected MelatiConfig melatiConfig() throws MelatiException {
MelatiConfig config = super.melatiConfig();
config.setFormDataAdaptorFactory(new MemoryDataAdaptorFactory());
return config;
}
protected String getUploadMessage(Melati melati) {
return "This will save your file in memory. Try saving a file in your " +
"/tmp directory <a href='" + melati.getZoneURL() +
"/org.melati.test.ConfigServletTestOverride/'>here</a>.";
}
}
| true | true | protected void doConfiguredRequest(Melati melati)
throws ServletException, IOException {
String method = melati.getMethod();
if (method != null) {
if (method.equals("Upload")) {
Hashtable fields = null;
try {
InputStream in = melati.getRequest().getInputStream();
MultipartDataDecoder decoder=
new MultipartDataDecoder(melati,
in,
melati.getRequest().getContentType(),
melati.getConfig().getFormDataAdaptorFactory());
fields = decoder.parseData();
}
catch (IOException e) {
melati.getWriter().write(
"There was some error uploading your file:" +
ExceptionUtils.stackTrace(e));
return;
}
MultipartFormField field = (MultipartFormField)fields.get("file");
if (field == null) {
melati.getWriter().write("No file was uploaded");
return;
}
byte[] data = field.getData();
melati.getResponse().setContentType(field.getContentType());
OutputStream output = melati.getResponse().getOutputStream();
output.write(data);
output.close();
return;
}
}
MelatiConfig config = melati.getConfig();
melati.getResponse().setContentType("text/html");
MelatiWriter output = melati.getWriter();
output.write(
"<html><head><title>ConfigServlet Test</title></head><body><h2> " +
"ConfigServlet Test</h2><p>This servlet tests your basic melati " +
"configuration. If you can read this message, it means that you have " +
"successfully created a Melati and a Melati, using the configuration " +
"given in org.melati.MelatiServlet.properties. Please note that this " +
"servlet does not construct a POEM session or initialise a template " +
"engine.</p><h4>Your Melati is configured with the following parameters: " +
"</h4><table><tr><td>TemplateEngine</td><td>" +
config.getTemplateEngine().getClass().getName() +
"</td></tr><tr><td>AccessHandler</td><td>" +
config.getAccessHandler().getClass().getName() +
"</td></tr><tr><td>FormDataAdaptorFactory</td><td>" +
config.getFormDataAdaptorFactory().getClass().getName() +
"</td></tr><tr><td>Locale</td><td>" +
config.getLocale().getClass().getName() +
"</td></tr><tr><td>TempletLoader</td><td>" +
config.getTempletLoader().getClass().getName() +
"</td></tr><tr><td>JavascriptLibraryURL</td><td>" +
config.getJavascriptLibraryURL() +
"</td></tr><tr><td>StaticURL</td><td>" +
config.getStaticURL() + "</td></tr></table>" +
"<h4>This servlet was called with the following Method (taken from " +
"melati.getMethod()): " +
melati.getMethod() +
"</h4><h4>Further Testing:</h4>You can test melati Exception handling by " +
"clicking <a href=" +
melati.getSameURL() +
"/Exception>Exception</a><br>You can test melati Redirect " +
"handling by clicking <a href=" +
melati.getSameURL() +
"/Redirect>Redirect</a><br>You can test your " +
"POEM setup (connecting to logical database <tt>melatitest</tt>) by " +
"clicking <a href=" +
melati.getZoneURL() +
"/org.melati.test.PoemServletTest/melatitest/>" +
"org.melati.test.PoemServletTest/melatitest/</a><br>" +
"<form method=\"post\" action=\"Upload\" enctype=\"multipart/form-data\" target=_blank>" +
"You can upload a file here:<br>" +
"<input type=hidden name=upload value=yes>" +
"<input type=\"file\" name=\"file\" enctype=\"multipart/form-data\">" +
"<input type=\"submit\" name=\"Submit\" value=\"Upload file\"><br>" +
getUploadMessage(melati) +
"</form>");
if (method != null) {
if (method.equals("Exception"))
throw new MelatiBugMelatiException("It got caught!");
if (method.equals("Redirect")) {
melati.getResponse().sendRedirect("http://www.melati.org");
return;
}
}
}
| protected void doConfiguredRequest(Melati melati)
throws ServletException, IOException {
String method = melati.getMethod();
if (method != null) {
if (method.equals("Upload")) {
Hashtable fields = null;
try {
InputStream in = melati.getRequest().getInputStream();
MultipartDataDecoder decoder=
new MultipartDataDecoder(melati,
in,
melati.getRequest().getContentType(),
melati.getConfig().getFormDataAdaptorFactory());
fields = decoder.parseData();
}
catch (IOException e) {
melati.getWriter().write(
"There was some error uploading your file:" +
ExceptionUtils.stackTrace(e));
return;
}
MultipartFormField field = (MultipartFormField)fields.get("file");
if (field == null) {
melati.getWriter().write("No file was uploaded");
return;
}
byte[] data = field.getData();
melati.getResponse().setContentType(field.getContentType());
OutputStream output = melati.getResponse().getOutputStream();
output.write(data);
output.close();
return;
}
}
MelatiConfig config = melati.getConfig();
melati.getResponse().setContentType("text/html");
MelatiWriter output = melati.getWriter();
output.write(
"<html><head><title>ConfigServlet Test</title></head><body><h2> " +
"ConfigServlet Test</h2><p>This servlet tests your basic melati " +
"configuration. If you can read this message, it means that you have " +
"successfully created a Melati and a Melati, using the configuration " +
"given in org.melati.MelatiServlet.properties. Please note that this " +
"servlet does not construct a POEM session or initialise a template " +
"engine.</p><h4>Your Melati is configured with the following parameters: " +
"</h4><table><tr><td>TemplateEngine</td><td>" +
config.getTemplateEngine().getClass().getName() +
"</td></tr><tr><td>AccessHandler</td><td>" +
config.getAccessHandler().getClass().getName() +
"</td></tr><tr><td>FormDataAdaptorFactory</td><td>" +
config.getFormDataAdaptorFactory().getClass().getName() +
"</td></tr><tr><td>Locale</td><td>" +
config.getLocale().getClass().getName() +
"</td></tr><tr><td>TempletLoader</td><td>" +
config.getTempletLoader().getClass().getName() +
"</td></tr><tr><td>JavascriptLibraryURL</td><td>" +
config.getJavascriptLibraryURL() +
"</td></tr><tr><td>StaticURL</td><td>" +
config.getStaticURL() + "</td></tr></table>" +
"<h4>This servlet was called with the following Method (taken from " +
"melati.getMethod()): " +
melati.getMethod() +
"</h4><h4>Further Testing:</h4>You can test melati Exception handling by " +
"clicking <a href=" +
melati.getSameURL() +
"/Exception>Exception</a><br>You can test melati Redirect " +
"handling by clicking <a href=" +
melati.getSameURL() +
"/Redirect>Redirect</a><br>You can test your " +
"POEM setup (connecting to logical database <tt>melatitest</tt>) by " +
"clicking <a href=" +
melati.getZoneURL() +
"/org.melati.test.PoemServletTest/melatitest/>" +
"org.melati.test.PoemServletTest/melatitest/</a><br>" +
"<form method=\"post\" action=\"" +
melati.getSameURL() +
"/Upload\" enctype=\"multipart/form-data\" target=_blank>" +
"You can upload a file here:<br>" +
"<input type=hidden name=upload value=yes>" +
"<input type=\"file\" name=\"file\" enctype=\"multipart/form-data\">" +
"<input type=\"submit\" name=\"Submit\" value=\"Upload file\"><br>" +
getUploadMessage(melati) +
"</form>");
if (method != null) {
if (method.equals("Exception"))
throw new MelatiBugMelatiException("It got caught!");
if (method.equals("Redirect")) {
melati.getResponse().sendRedirect("http://www.melati.org");
return;
}
}
}
|
diff --git a/app/backend/PlasteBot.java b/app/backend/PlasteBot.java
index eed5a2c..7550304 100644
--- a/app/backend/PlasteBot.java
+++ b/app/backend/PlasteBot.java
@@ -1,89 +1,91 @@
package backend;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import play.Logger;
import play.Play;
import play.mvc.Router;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class PlasteBot extends PircBot {
private static PlasteBot instance = null;
private final String channel;
private final String nick;
private PlasteBot() throws IOException, IrcException {
this.nick = Play.configuration.getProperty("irc.nick", "PlasteBot");
final String server = Play.configuration.getProperty("irc.server", "irc.lunatech.com");
this.channel = Play.configuration.getProperty("irc.channel", "#test");
Logger.info("IRC bot connecting as [" + nick + "]");
setName(this.nick);
setAutoNickChange(true);
setEncoding("UTF-8");
+ setLogin(this.nick);
+ setVersion("PlasteBot, " + getNewPasteUrl());
connect(server);
Logger.info("IRC bot connected to [" + server + "]");
joinChannel(channel);
Logger.info("IRC bot joined channel [" + channel + "]");
}
public static synchronized PlasteBot getInstance() {
if (PlasteBot.instance == null)
throw new IllegalStateException("PlasteBot instance requested before starting");
return PlasteBot.instance;
}
public static synchronized void start() throws InterruptedException, IOException, IrcException {
PlasteBot bot = PlasteBot.instance;
if (bot != null) {
if (bot.isConnected()) {
Logger.info("Disconnecting IRC bot before reconnecting");
bot.disconnect();
Thread.sleep(1000);
Logger.info("Disconnected");
}
}
PlasteBot.instance = new PlasteBot();
}
public List<String> getNicks() {
final List<String> nicks = new ArrayList<String>();
final User[] users = getUsers(this.channel);
if (users != null)
for (User user : users)
nicks.add(user.getNick());
return nicks;
}
public void sendMessage(final String message) {
sendMessage(this.channel, message);
}
@Override
protected void onMessage(final String channel, final String sender, final String login,
final String hostname, final String message) {
if (message.matches("^" + getNick() + ":.*$")) {
sendMessage(sender + ": " + getNewPasteUrl());
}
}
@Override
protected void onPrivateMessage(final String sender, final String login, final String hostname,
final String message) {
sendMessage(sender, getNewPasteUrl());
}
private String getNewPasteUrl() {
return Router.getFullUrl("Application.newPaste");
}
}
| true | true | private PlasteBot() throws IOException, IrcException {
this.nick = Play.configuration.getProperty("irc.nick", "PlasteBot");
final String server = Play.configuration.getProperty("irc.server", "irc.lunatech.com");
this.channel = Play.configuration.getProperty("irc.channel", "#test");
Logger.info("IRC bot connecting as [" + nick + "]");
setName(this.nick);
setAutoNickChange(true);
setEncoding("UTF-8");
connect(server);
Logger.info("IRC bot connected to [" + server + "]");
joinChannel(channel);
Logger.info("IRC bot joined channel [" + channel + "]");
}
| private PlasteBot() throws IOException, IrcException {
this.nick = Play.configuration.getProperty("irc.nick", "PlasteBot");
final String server = Play.configuration.getProperty("irc.server", "irc.lunatech.com");
this.channel = Play.configuration.getProperty("irc.channel", "#test");
Logger.info("IRC bot connecting as [" + nick + "]");
setName(this.nick);
setAutoNickChange(true);
setEncoding("UTF-8");
setLogin(this.nick);
setVersion("PlasteBot, " + getNewPasteUrl());
connect(server);
Logger.info("IRC bot connected to [" + server + "]");
joinChannel(channel);
Logger.info("IRC bot joined channel [" + channel + "]");
}
|
diff --git a/nephele/nephele-queuescheduler/src/test/java/eu/stratosphere/nephele/jobmanager/scheduler/queue/QueueSchedulerTest.java b/nephele/nephele-queuescheduler/src/test/java/eu/stratosphere/nephele/jobmanager/scheduler/queue/QueueSchedulerTest.java
index 5d41853ed..ee45d0c2e 100644
--- a/nephele/nephele-queuescheduler/src/test/java/eu/stratosphere/nephele/jobmanager/scheduler/queue/QueueSchedulerTest.java
+++ b/nephele/nephele-queuescheduler/src/test/java/eu/stratosphere/nephele/jobmanager/scheduler/queue/QueueSchedulerTest.java
@@ -1,240 +1,240 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.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.stratosphere.nephele.jobmanager.scheduler.queue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.lang.reflect.Method;
import java.util.Deque;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.membermodification.MemberMatcher;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import eu.stratosphere.nephele.configuration.Configuration;
import eu.stratosphere.nephele.execution.ExecutionState;
import eu.stratosphere.nephele.executiongraph.ExecutionGraph;
import eu.stratosphere.nephele.executiongraph.ExecutionGraphIterator;
import eu.stratosphere.nephele.executiongraph.ExecutionStage;
import eu.stratosphere.nephele.executiongraph.ExecutionVertex;
import eu.stratosphere.nephele.instance.AllocatedResource;
import eu.stratosphere.nephele.instance.HardwareDescription;
import eu.stratosphere.nephele.instance.InstanceConnectionInfo;
import eu.stratosphere.nephele.instance.InstanceException;
import eu.stratosphere.nephele.instance.InstanceManager;
import eu.stratosphere.nephele.instance.InstanceType;
import eu.stratosphere.nephele.instance.InstanceTypeDescription;
import eu.stratosphere.nephele.instance.InstanceTypeDescriptionFactory;
import eu.stratosphere.nephele.instance.local.LocalInstance;
import eu.stratosphere.nephele.jobgraph.JobID;
import eu.stratosphere.nephele.jobmanager.DeploymentManager;
import eu.stratosphere.nephele.jobmanager.scheduler.SchedulingException;
/**
* @author marrus
* This class checks the functionality of the {@link QueueScheduler} class
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(QueueScheduler.class)
@SuppressStaticInitializationFor("eu.stratosphere.nephele.jobmanager.scheduler.queue.QueueScheduler")
public class QueueSchedulerTest {
@Mock
private ExecutionGraph executionGraph;
@Mock
private ExecutionStage stage1;
@Mock
private ExecutionVertex vertex1;
@Mock
private ExecutionGraphIterator graphIterator;
@Mock
private ExecutionGraphIterator graphIterator2;
@Mock
private InstanceManager instanceManager;
@Mock
private Log loggerMock;
/**
* Setting up the mocks and necessary internal states
*/
@Before
public void before() {
MockitoAnnotations.initMocks(this);
Whitebox.setInternalState(QueueScheduler.class, this.loggerMock);
}
/**
* Checks the behavior of the scheduleJob() method
*/
@Test
public void testSchedulJob() {
final InstanceType type = new InstanceType();
InstanceTypeDescription desc = InstanceTypeDescriptionFactory.construct(type, new HardwareDescription(), 4);
final HashMap<InstanceType, Integer> requiredInstanceTypes = new HashMap<InstanceType, Integer>();
requiredInstanceTypes.put(type, 3);
final HashMap<InstanceType, InstanceTypeDescription> availableInstances = new HashMap<InstanceType, InstanceTypeDescription>();
availableInstances.put(type, desc);
final DeploymentManager deploymentManager = new TestDeploymentManager();
try {
whenNew(HashMap.class).withNoArguments().thenReturn(requiredInstanceTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
when(this.executionGraph.getNumberOfStages()).thenReturn(1);
when(this.executionGraph.getStage(0)).thenReturn(this.stage1);
when(this.executionGraph.getCurrentExecutionStage()).thenReturn(this.stage1);
when(this.instanceManager.getMapOfAvailableInstanceTypes()).thenReturn(availableInstances);
when(this.stage1.getExecutionGraph()).thenReturn(this.executionGraph);
// correct walk through method
final QueueScheduler toTest = new QueueScheduler(deploymentManager, this.instanceManager);
try {
toTest.schedulJob(this.executionGraph);
final Deque<ExecutionGraph> jobQueue = Whitebox.getInternalState(toTest, "jobQueue");
assertEquals("Job should be in list", true, jobQueue.contains(this.executionGraph));
jobQueue.remove(this.executionGraph);
} catch (SchedulingException e) {
fail();
e.printStackTrace();
}
// not enough available Instances
desc = InstanceTypeDescriptionFactory.construct(type, new HardwareDescription(), 2);
availableInstances.put(type, desc);
try {
toTest.schedulJob(this.executionGraph);
fail();
} catch (SchedulingException e) {
final Deque<ExecutionGraph> jobQueue = Whitebox.getInternalState(toTest, "jobQueue");
assertEquals("Job should not be in list", false, jobQueue.contains(this.executionGraph));
}
// Instance unknown
availableInstances.clear();
try {
toTest.schedulJob(this.executionGraph);
fail();
} catch (SchedulingException e) {
Deque<ExecutionGraph> jobQueue = Whitebox.getInternalState(toTest, "jobQueue");
assertEquals("Job should not be in list", false, jobQueue.contains(this.executionGraph));
}
}
/**
* Checks the behavior of the resourceAllocated() method
*
* @throws Exception
*/
@Test
public void testResourceAllocated() throws Exception {
final DeploymentManager deploymentManager = new TestDeploymentManager();
final QueueScheduler toTest = spy(new QueueScheduler(deploymentManager, this.instanceManager));
- final JobID jobid = mock(JobID.class);
+ final JobID jobid = new JobID();
final AllocatedResource resource = mock(AllocatedResource.class);
final InstanceType instanceType = new InstanceType();
InstanceConnectionInfo instanceConnectionInfo = mock(InstanceConnectionInfo.class);
when(instanceConnectionInfo.toString()).thenReturn("");
LocalInstance instance = spy(new LocalInstance(instanceType, instanceConnectionInfo, null, null, null));
// given resource is null
toTest.resourceAllocated(null, null);
verify(this.loggerMock).error(Matchers.anyString());
// jobs have have been canceled
final Method methodToMock = MemberMatcher.method(QueueScheduler.class, JobID.class);
PowerMockito.when(toTest, methodToMock).withArguments(Matchers.any(JobID.class)).thenReturn(null);
when(resource.getInstance()).thenReturn(instance);
toTest.resourceAllocated(jobid, resource);
try {
verify(this.instanceManager).releaseAllocatedResource(Matchers.any(JobID.class),
Matchers.any(Configuration.class), Matchers.any(AllocatedResource.class));
} catch (InstanceException e1) {
e1.printStackTrace();
}
// vertex resource is null
PowerMockito.when(toTest, methodToMock).withArguments(Matchers.any(JobID.class))
.thenReturn(this.executionGraph);
when(this.graphIterator.next()).thenReturn(this.vertex1);
when(this.graphIterator.hasNext()).thenReturn(true, true, true, true, false);
when(this.graphIterator2.next()).thenReturn(this.vertex1);
when(this.graphIterator2.hasNext()).thenReturn(true, true, true, true, false);
when(this.vertex1.getExecutionState()).thenReturn(ExecutionState.ASSIGNING);
try {
whenNew(ExecutionGraphIterator.class).withArguments(Matchers.any(ExecutionGraph.class),
Matchers.anyBoolean()).thenReturn(this.graphIterator);
whenNew(ExecutionGraphIterator.class).withArguments(Matchers.any(ExecutionGraph.class), Matchers.anyInt(),
Matchers.anyBoolean(), Matchers.anyBoolean()).thenReturn(this.graphIterator2);
} catch (Exception e) {
throw new RuntimeException(e);
}
when(this.executionGraph.getJobID()).thenReturn(jobid);
Deque<ExecutionGraph> jobQueue = Whitebox.getInternalState(toTest, "jobQueue");
jobQueue.add(this.executionGraph);
Whitebox.setInternalState(toTest, "jobQueue", jobQueue);
when(this.vertex1.getAllocatedResource()).thenReturn(null);
when(resource.getInstance()).thenReturn(instance);
toTest.resourceAllocated(jobid, resource);
verify(this.loggerMock).warn(Matchers.anyString());
// correct walk through method
when(this.graphIterator2.hasNext()).thenReturn(true, true, true, true, false);
when(this.graphIterator.hasNext()).thenReturn(true, true, true, true, false);
when(this.vertex1.getAllocatedResource()).thenReturn(resource);
when(resource.getInstanceType()).thenReturn(instanceType);
toTest.resourceAllocated(jobid, resource);
verify(this.vertex1, times(4)).setExecutionState(ExecutionState.ASSIGNED);
}
}
| true | true | public void testResourceAllocated() throws Exception {
final DeploymentManager deploymentManager = new TestDeploymentManager();
final QueueScheduler toTest = spy(new QueueScheduler(deploymentManager, this.instanceManager));
final JobID jobid = mock(JobID.class);
final AllocatedResource resource = mock(AllocatedResource.class);
final InstanceType instanceType = new InstanceType();
InstanceConnectionInfo instanceConnectionInfo = mock(InstanceConnectionInfo.class);
when(instanceConnectionInfo.toString()).thenReturn("");
LocalInstance instance = spy(new LocalInstance(instanceType, instanceConnectionInfo, null, null, null));
// given resource is null
toTest.resourceAllocated(null, null);
verify(this.loggerMock).error(Matchers.anyString());
// jobs have have been canceled
final Method methodToMock = MemberMatcher.method(QueueScheduler.class, JobID.class);
PowerMockito.when(toTest, methodToMock).withArguments(Matchers.any(JobID.class)).thenReturn(null);
when(resource.getInstance()).thenReturn(instance);
toTest.resourceAllocated(jobid, resource);
try {
verify(this.instanceManager).releaseAllocatedResource(Matchers.any(JobID.class),
Matchers.any(Configuration.class), Matchers.any(AllocatedResource.class));
} catch (InstanceException e1) {
e1.printStackTrace();
}
// vertex resource is null
PowerMockito.when(toTest, methodToMock).withArguments(Matchers.any(JobID.class))
.thenReturn(this.executionGraph);
when(this.graphIterator.next()).thenReturn(this.vertex1);
when(this.graphIterator.hasNext()).thenReturn(true, true, true, true, false);
when(this.graphIterator2.next()).thenReturn(this.vertex1);
when(this.graphIterator2.hasNext()).thenReturn(true, true, true, true, false);
when(this.vertex1.getExecutionState()).thenReturn(ExecutionState.ASSIGNING);
try {
whenNew(ExecutionGraphIterator.class).withArguments(Matchers.any(ExecutionGraph.class),
Matchers.anyBoolean()).thenReturn(this.graphIterator);
whenNew(ExecutionGraphIterator.class).withArguments(Matchers.any(ExecutionGraph.class), Matchers.anyInt(),
Matchers.anyBoolean(), Matchers.anyBoolean()).thenReturn(this.graphIterator2);
} catch (Exception e) {
throw new RuntimeException(e);
}
when(this.executionGraph.getJobID()).thenReturn(jobid);
Deque<ExecutionGraph> jobQueue = Whitebox.getInternalState(toTest, "jobQueue");
jobQueue.add(this.executionGraph);
Whitebox.setInternalState(toTest, "jobQueue", jobQueue);
when(this.vertex1.getAllocatedResource()).thenReturn(null);
when(resource.getInstance()).thenReturn(instance);
toTest.resourceAllocated(jobid, resource);
verify(this.loggerMock).warn(Matchers.anyString());
// correct walk through method
when(this.graphIterator2.hasNext()).thenReturn(true, true, true, true, false);
when(this.graphIterator.hasNext()).thenReturn(true, true, true, true, false);
when(this.vertex1.getAllocatedResource()).thenReturn(resource);
when(resource.getInstanceType()).thenReturn(instanceType);
toTest.resourceAllocated(jobid, resource);
verify(this.vertex1, times(4)).setExecutionState(ExecutionState.ASSIGNED);
}
| public void testResourceAllocated() throws Exception {
final DeploymentManager deploymentManager = new TestDeploymentManager();
final QueueScheduler toTest = spy(new QueueScheduler(deploymentManager, this.instanceManager));
final JobID jobid = new JobID();
final AllocatedResource resource = mock(AllocatedResource.class);
final InstanceType instanceType = new InstanceType();
InstanceConnectionInfo instanceConnectionInfo = mock(InstanceConnectionInfo.class);
when(instanceConnectionInfo.toString()).thenReturn("");
LocalInstance instance = spy(new LocalInstance(instanceType, instanceConnectionInfo, null, null, null));
// given resource is null
toTest.resourceAllocated(null, null);
verify(this.loggerMock).error(Matchers.anyString());
// jobs have have been canceled
final Method methodToMock = MemberMatcher.method(QueueScheduler.class, JobID.class);
PowerMockito.when(toTest, methodToMock).withArguments(Matchers.any(JobID.class)).thenReturn(null);
when(resource.getInstance()).thenReturn(instance);
toTest.resourceAllocated(jobid, resource);
try {
verify(this.instanceManager).releaseAllocatedResource(Matchers.any(JobID.class),
Matchers.any(Configuration.class), Matchers.any(AllocatedResource.class));
} catch (InstanceException e1) {
e1.printStackTrace();
}
// vertex resource is null
PowerMockito.when(toTest, methodToMock).withArguments(Matchers.any(JobID.class))
.thenReturn(this.executionGraph);
when(this.graphIterator.next()).thenReturn(this.vertex1);
when(this.graphIterator.hasNext()).thenReturn(true, true, true, true, false);
when(this.graphIterator2.next()).thenReturn(this.vertex1);
when(this.graphIterator2.hasNext()).thenReturn(true, true, true, true, false);
when(this.vertex1.getExecutionState()).thenReturn(ExecutionState.ASSIGNING);
try {
whenNew(ExecutionGraphIterator.class).withArguments(Matchers.any(ExecutionGraph.class),
Matchers.anyBoolean()).thenReturn(this.graphIterator);
whenNew(ExecutionGraphIterator.class).withArguments(Matchers.any(ExecutionGraph.class), Matchers.anyInt(),
Matchers.anyBoolean(), Matchers.anyBoolean()).thenReturn(this.graphIterator2);
} catch (Exception e) {
throw new RuntimeException(e);
}
when(this.executionGraph.getJobID()).thenReturn(jobid);
Deque<ExecutionGraph> jobQueue = Whitebox.getInternalState(toTest, "jobQueue");
jobQueue.add(this.executionGraph);
Whitebox.setInternalState(toTest, "jobQueue", jobQueue);
when(this.vertex1.getAllocatedResource()).thenReturn(null);
when(resource.getInstance()).thenReturn(instance);
toTest.resourceAllocated(jobid, resource);
verify(this.loggerMock).warn(Matchers.anyString());
// correct walk through method
when(this.graphIterator2.hasNext()).thenReturn(true, true, true, true, false);
when(this.graphIterator.hasNext()).thenReturn(true, true, true, true, false);
when(this.vertex1.getAllocatedResource()).thenReturn(resource);
when(resource.getInstanceType()).thenReturn(instanceType);
toTest.resourceAllocated(jobid, resource);
verify(this.vertex1, times(4)).setExecutionState(ExecutionState.ASSIGNED);
}
|
diff --git a/src/dungeonCrawler/GameLogic.java b/src/dungeonCrawler/GameLogic.java
index 574ea60..b1f1df6 100755
--- a/src/dungeonCrawler/GameLogic.java
+++ b/src/dungeonCrawler/GameLogic.java
@@ -1,651 +1,652 @@
package dungeonCrawler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.Timer;
import dungeonCrawler.GameElements.Bow;
import dungeonCrawler.GameElements.CheckPoint;
import dungeonCrawler.GameElements.Enemy;
import dungeonCrawler.GameElements.Exit;
import dungeonCrawler.GameElements.Healthpot;
import dungeonCrawler.GameElements.Manapot;
import dungeonCrawler.GameElements.Money;
import dungeonCrawler.GameElements.NPC;
import dungeonCrawler.GameElements.Player;
import dungeonCrawler.GameElements.Trap;
import dungeonCrawler.GameElements.Wall;
import dungeonCrawler.GameElements.Active;
import dungeonCrawler.GameElements.FireBolt;
import dungeonCrawler.GameElements.IceBolt;
import dungeonCrawler.GameElements.WarpPoint;
//import dungeonCrawler.GameElements.Spell;
public class GameLogic implements KeyListener, ActionListener {
// private long time;
private Vector2d direction = new Vector2d(0,0);
private Vector2d lastDirection = new Vector2d(0,1);
private Vector2d checkPoint = new Vector2d(0,0);
private SettingSet settings = new SettingSet();
private int[] delay = new int[1000];
private int[] max_delay = new int[1000];
protected GameContent level;
private BitSet keys;
protected Timer timer;
public App app;
protected Player player;
public ShopSystem new_shop = null;
// public ShopItem new_item;
public int Money;
public LinkedList<GameObject> Inventar = new LinkedList<GameObject>();
private Vector2d startpos= new Vector2d(0,0);
private Vector2d endpos= new Vector2d(0,0);
private Vector2d oldendpos= new Vector2d(0,0);
private Vector2d oldstartpos= new Vector2d(0,0);
private boolean setze=false; // für editor, wenn variable gesetzt ist, dann nochmal drücken um das gameelement hinzu zu fügen
public File file;
int movedelay=0;
int editspeed=5;
boolean tpset=false;
public GameLogic(App app) {
// TODO Auto-generated constructor stub
keys = new BitSet();
keys.clear();
timer = new Timer(1, this);
timer.setActionCommand("Timer");
timer.stop();
this.app = app;
Money = 0;
for(int i=0;i<1000;i++){
max_delay[i] = 3;
}
max_delay[settings.SHOOT] = 200;
max_delay[settings.USE_HEALTHPOT] = 500;
max_delay[settings.USE_MANAPOT] = 500;
max_delay[settings.CHANGE_ARMOR] = 50;
}
private void reduceDelay(){
for(int i=0;i<1000;i++){
if(delay[i] > 0) delay[i]--;
}
}
public boolean checkKey(int i){
if(delay[i]<=0 && keys.get(i)){
delay[i] = max_delay[i];
return true;
}
return false;
}
private void createElement(int sx,int sy,int px,int py,String elementtype){
if (!setze) { startpos=level.getPlayer().getPosition(); setze=true;System.out.println("startpos gesetzt");}
else {
level.removeElement(level.getPlayer());
calculatepositions(sx,sy,px,py);
switch (elementtype){
case "Bow": level.addGameElement(new Bow(startpos,endpos)); setze=false; break;
case "Checkpoint": level.addGameElement(new CheckPoint(startpos,endpos)); setze=false; break;
case "Enemy": level.addGameElement(new Enemy(startpos,endpos)); setze=false; break;
case "Exit": level.addGameElement(new Exit(startpos,endpos)); setze=false; break;
case "Healthpot": level.addGameElement(new Healthpot(startpos,endpos)); setze=false; break;
case "Manapot": level.addGameElement(new Manapot(startpos,endpos)); setze=false; break;
case "Money": level.addGameElement(new Money(startpos,endpos)); setze=false; break;
case "NPC": level.addGameElement(new NPC(startpos,endpos)); setze=false; break;
case "Trap": level.addGameElement(new Trap(startpos,endpos)); setze=false; break;
case "Wall": level.addGameElement(new Wall(startpos,endpos)); setze=false; break;
case "Warppoint": if(tpset){level.addGameElement(new WarpPoint(oldstartpos,oldendpos,new Vector2d(px,py)));tpset=false;setze=false; break;}
else {tpset=true;oldstartpos=startpos;oldendpos=endpos;break;}
}
level.addGameElement(player);
}
}
private void calculatepositions(int sx,int sy,int px,int py){
/**
* berechnet die start- und endposition für ein zu erzeugendes Element
* */
if (px> sx && py>sy){
startpos= new Vector2d(sx,sy);
endpos= new Vector2d(px-sx,py-sy);
}
else if (px< sx && py>sy){
startpos= new Vector2d(px,sy);
endpos= new Vector2d(sx-px,py-sy);
}
else if (px< sx && py<sy){
startpos= new Vector2d(px,py);
endpos= new Vector2d(sx-px,sy-py);
}
else if (px> sx && py<sy){
startpos= new Vector2d(sx,py);
endpos= new Vector2d(px-sx,sy-py);
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
keys.set(e.getKeyCode());
if (app.editmode==true){
int sx = startpos.getX();
int sy = startpos.getY();
int px = level.getPlayer().getPosition().getX();
int py = level.getPlayer().getPosition().getY();
switch (e.getKeyCode()) {
case 66:setze=true;createElement(px,py,px+5,py+5,"Bow"); break; //Bow
case 67:setze=true;createElement(px,py,px+30,py+30,"Enemy"); break; //Enemy
case 69:createElement(sx,sy,px,py,"Exit"); break; //Exit
case 71:setze=true;createElement(px,py,px+10,py+10,"Money"); break; //Money
case 72:setze=true;createElement(px,py,px+10,py+10,"Healthpot"); break; //Healthpot
case 77:setze=true;createElement(px,py,px+10,py+10,"Manapot"); break; //Manapot
case 78:setze=true;createElement(px,py,px+30,py+30,"NPC"); break; //NPC
case 83:setze=true;createElement(px,py,px+30,py+30,"Checkpoint"); break; //CheckPoint
case 84:createElement(sx,sy,px,py,"Trap"); break; //Trap
case 87:createElement(sx,sy,px,py,"Wall"); break; //Wall
case 90:createElement(sx,sy,px,py,"Warppoint"); break; //Wall
}
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
keys.clear(e.getKeyCode());
if(e.getKeyCode() == settings.USE_HEALTHPOT)
delay[settings.USE_HEALTHPOT] = 0;
if(e.getKeyCode() == settings.USE_MANAPOT)
delay[settings.USE_MANAPOT] = 0;
}
private String convertLvltoStr(int currentLevel) {
String str;
try {
str = 0 + Integer.toString(currentLevel);
str = str.substring(str.length()-2);
System.out.println(str);
} catch (Exception e) {
return "99";
}
return str;
}
private void writeLvl(){
LinkedList<GameElement> currentelement;
//file.delete();
file = new File("Levels"+File.separator+"level" + convertLvltoStr(app.currentLevel) +".lvl");
//FileWriter writer = null;
try {
PrintWriter outputstream = new PrintWriter(file);
while ((currentelement=level.getGameElements())!=null && level.getPlayer() != currentelement.getFirst()){
if (currentelement.element().getName()=="WARPPOINT"){
outputstream.println(currentelement.element().getName()+","+currentelement.element().getPosition().getX()+","+currentelement.element().getPosition().getY()+","+currentelement.element().getSize().getX()+","+currentelement.element().getSize().getY()+","+((WarpPoint)currentelement.getFirst()).getTarget().getX()+","+((WarpPoint)currentelement.getFirst()).getTarget().getY());
level.removeElement(currentelement.getFirst());
System.out.println(currentelement.element().getName()+","+currentelement.element().getPosition().getX()+","+currentelement.element().getPosition().getY()+","+currentelement.element().getSize().getX()+","+currentelement.element().getSize().getY());
outputstream.flush();
}
else{
outputstream.println(currentelement.element().getName()+","+currentelement.element().getPosition().getX()+","+currentelement.element().getPosition().getY()+","+currentelement.element().getSize().getX()+","+currentelement.element().getSize().getY());
level.removeElement(currentelement.getFirst());
System.out.println(currentelement.element().getName()+","+currentelement.element().getPosition().getX()+","+currentelement.element().getPosition().getY()+","+currentelement.element().getSize().getX()+","+currentelement.element().getSize().getY());
outputstream.flush();
}
}
outputstream.println(currentelement.element().getName()+","+currentelement.element().getPosition().getX()+","+currentelement.element().getPosition().getY()+","+currentelement.element().getSize().getX()+","+currentelement.element().getSize().getY());
System.out.println(currentelement.element().getName()+","+currentelement.element().getPosition().getX()+","+currentelement.element().getPosition().getY()+","+currentelement.element().getSize().getX()+","+currentelement.element().getSize().getY());
outputstream.flush();
outputstream.close();
level.removeElement(currentelement.getFirst());
} catch (IOException e1) {
}
}
private void increaselevels(){
file = new File("Levels"+File.separator+"level.lvl");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write(String.valueOf(app.level));
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
System.out.printf("File is located at %s%n", file.getAbsolutePath());
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
if (app.editmode==true){
if(keys.get(27)){
writeLvl();
System.out.println("geht weiter");
app.editmode=false;
app.currentLevel=app.level;
app.startGame();
increaselevels();
}
if(keys.get(68)){
for(GameElement collisioncheck : level.getGameElements()){
if(level.getPlayer().collision(collisioncheck) && collisioncheck!=level.getPlayer()){
level.removeElement(collisioncheck);
}
}
}
}
if (app.editmode == false){
if (keys.get(37)) {// left
direction=direction.addX(-1);
System.out.println("LEFT");
}
if (keys.get(38)) {// up
direction=direction.addY(-1);
System.out.println("UP");
}
if (keys.get(39)) {// right
direction=direction.addX(1);
System.out.println("RIGHT");
}
if (keys.get(40)) {// down
direction=direction.addY(1);
System.out.println("DOWN");
}
if(keys.get(27)){
if (timer.isRunning()){
timer.stop();
}
else {
timer.start();
}
}
if (e.getKeyChar() == 'h') {// "h" for health
keys.clear(72);
Iterator<GameObject> it = player.getInventar().iterator();
boolean b = true;
GameObject obj;
while (it.hasNext() && b) {
obj = it.next();
if (obj.getClass().getName().equalsIgnoreCase("dungeonCrawler.GameObjects.HealthPotion")) {
obj.performOn(player);
player.getInventar().remove(obj);
b = false;
}
}
}
if (e.getKeyChar() == 'm') {// "m" for mana
keys.clear(77);
Iterator<GameObject> it = player.getInventar().iterator();
boolean b = true;
GameObject obj;
while (it.hasNext() && b) {
obj = it.next();
if (obj.getClass().getName().equalsIgnoreCase("dungeonCrawler.GameObjects.ManaPotion")) {
obj.performOn(player);
player.getInventar().remove(obj);
b = false;
}
}
}
if (e.getKeyChar() == 'p') {// print string
System.out.println(player.getString());
}
}
}
public GameContent getLevel() {
return level;
}
public void setLevel(GameContent level) {
this.level = level;
}
private void handleCollision(GameElement active, GameElement passive){
//TODO generate GameEvents
GameEvent e = new GameEvent(passive, EventType.COLLISION, this);
active.GameEventPerformed(e);
e = new GameEvent(active, EventType.COLLISION, this);
passive.GameEventPerformed(e);
}
public boolean moveElement(GameElement e, Vector2d direction){
if (app.editmode==false){
if(e.type.contains(ElementType.MOVABLE)){ //TODO call handleCollision only once per GameElement
// System.out.println("test" + collisioncheck.type.toString());
HashSet<GameElement> collides = new HashSet<GameElement>();
e.setPosition(e.position.add(new Vector2d(direction.getX(), 0)));
for(GameElement collisioncheck : level.getGameElements()){
if(e.collision(collisioncheck)){
if(!collisioncheck.type.contains(ElementType.WALKABLE)){
e.setPosition(e.position.add(new Vector2d(-direction.getX(), 0)));
}
collides.add(collisioncheck);
}
}
//if(level.getGameElements().contains(e)){
e.setPosition(e.position.add(new Vector2d(0, direction.getY())));
for(GameElement collisioncheck : level.getGameElements()){
if(e.collision(collisioncheck)){
if(!collisioncheck.type.contains(ElementType.WALKABLE)){
e.setPosition(e.position.add(new Vector2d(0, -direction.getY())));
}
collides.add(collisioncheck);
}
}
for(GameElement col : collides){
handleCollision(e, col);
}
//}
//e.setPosition(direction.add(e.position));
return true;
}
else
return false;
}
else return true;
}
public boolean teleportElement(GameElement e, Vector2d position){
e.setPosition(position);
return false;
}
@Override
public void actionPerformed(ActionEvent e) {
player = (Player)level.getPlayer();
Vector2d position = player.getPosition();
// TODO: abfragen, welche Bits gesetzt sind und ensprechend handeln
if (app.editmode==true){
movedelay=movedelay-1;
if (keys.get(100)) {// cheat left
player.setPosition(position.addX(-10));
System.out.println("CHEAT LEFT");
}
if (keys.get(104)) {// cheat up
player.setPosition(position.addY(-10));
System.out.println("CHEAT UP");
}
if (keys.get(98)) {// cheat down
player.setPosition(position.addY(10));
System.out.println("CHEAT DOWN");
}
if (keys.get(102)) {// cheat right
player.setPosition(position.addX(10));
System.out.println("CHEAT RIGHT");
}
if (keys.get(107) && editspeed > 10) {// left
editspeed-=10;
System.out.println(editspeed);
keys.clear();
}
else if (keys.get(107) && editspeed > 0) {// left
editspeed-=1;
System.out.println(editspeed);
keys.clear();
}
if (keys.get(109) && editspeed < 10) {// left
editspeed+=1;
keys.clear();
System.out.println(editspeed);
}
else if (keys.get(109) && editspeed < 100) {// left
editspeed+=10;
keys.clear();
System.out.println(editspeed);
}
if (keys.get(37) && movedelay <=0) {// left
player.setPosition(position.addX(-1));
movedelay=editspeed;
System.out.println("LEFT");
}
if (keys.get(38) && movedelay <=0) {// up
player.setPosition(position.addY(-1));
movedelay=editspeed;
System.out.println("UP");
}
if (keys.get(39) && movedelay <=0) {// right
player.setPosition(position.addX(1));
movedelay=editspeed;
System.out.println("RIGHT");
}
if (keys.get(40) && movedelay <=0) {// down
player.setPosition(position.addY(1));
movedelay=editspeed;
System.out.println("DOWN");
}
if (keys.get(103)) {// position output
System.out.println("x= " + player.getPosition().getX() + " ; y= " + player.getPosition().getY());
}
}
if (app.editmode==false){
reduceDelay();
player = (Player)level.getPlayer();
if(!(direction.getX() == 0 && direction.getY() == 0)){
lastDirection = direction;
}
direction = new Vector2d(0,0);
for(Active active : level.getActives()){
active.interaction(this, settings, keys);
}
if (keys.get(100)) {// cheat left
player.setPosition(position.addX(-10));
System.out.println("CHEAT LEFT");
}
if (keys.get(104)) {// cheat up
player.setPosition(position.addY(-10));
System.out.println("CHEAT UP");
}
if (keys.get(98)) {// cheat down
player.setPosition(position.addY(10));
System.out.println("CHEAT DOWN");
}
if (keys.get(102)) {// cheat right
player.setPosition(position.addX(10));
System.out.println("CHEAT RIGHT");
}
if (keys.get(101)) {// cheat Leben
player.setHealth(player.getHealth()+1000);
System.out.println("CHEAT Leben");
}
if (keys.get(103)) {// position output
System.out.println("x= " + player.getPosition().getX() + "y= " + player.getPosition().getY());
}
if (keys.get(99)) {// Exit
if (level.getExit() != null){
level.getPlayer().setPosition(level.getExit().getPosition().addX(10).addY(60));}
System.out.println("CHEAT EXIT");
}
if (keys.get(37)) {// left arrow
direction = direction.addX(-1);
//System.out.println("LEFT");
}
if (keys.get(38)) {// up arrow
direction = direction.addY(-1);
//System.out.println("UP");
}
if (keys.get(39)) {// right arrow
direction = direction.addX(1);
//System.out.println("RIGHT");
}
if (keys.get(40)) {// down arrow
direction = direction.addY(1);
//System.out.println("DOWN");
}
if (checkKey(83)) { // s
keys.clear();
//timer.stop();
if (level.getPlayer() != null) {
if (new_shop == null) {
// initialize shop
new_shop = new ShopSystem((Player)level.getPlayer());
- new_shop.fillShop(new_shop.getvermoegen(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
+ ((Player)level.getPlayer()).setMoney(100);
+ new_shop.fillShop(((Player)level.getPlayer()).getMoney(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
}
else{
System.out.println("Shop Visable you have " + player.getMoney() + " Geld");
- new_shop.fillShop(new_shop.getvermoegen(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
+ new_shop.fillShop(((Player)level.getPlayer()).getMoney(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
player.setMoney(new_shop.getvermoegen());
}
}
}
if (keys.get(KeyEvent.VK_Q)){// q (fire bolt)
System.out.println(delay[KeyEvent.VK_Q]);
if(delay[KeyEvent.VK_Q] <= 0 && player.reduceMana(20, this)){
delay[KeyEvent.VK_Q] = 250;
Vector2d pos = new Vector2d(position.add(player.size.mul(0.5)).add(new Vector2d(-5, -5)));
if(lastDirection.getX() > 0)
pos = pos.add(new Vector2d(player.size.getX()-2,0));
if(lastDirection.getX() < 0)
pos = pos.add(new Vector2d(-player.size.getX()+2,0));
if(lastDirection.getY() > 0)
pos = pos.add(new Vector2d(0,player.size.getX()-2));
if(lastDirection.getY() < 0)
pos = pos.add(new Vector2d(0,-player.size.getX()+2));
FireBolt tmp = new FireBolt(pos, new Vector2d(10, 10));
tmp.setDirection(lastDirection.mul(1));
level.addGameElement(tmp);
}
}
if (keys.get(KeyEvent.VK_W)){// w (ice bolt)
System.out.println(delay[KeyEvent.VK_W]);
if(delay[KeyEvent.VK_W] <= 0 && player.reduceMana(10, this)){
delay[KeyEvent.VK_W] = 250;
Vector2d pos = new Vector2d(position.add(player.size.mul(0.5)).add(new Vector2d(-5, -5)));
if(lastDirection.getX() > 0)
pos = pos.add(new Vector2d(player.size.getX()-2,0));
if(lastDirection.getX() < 0)
pos = pos.add(new Vector2d(-player.size.getX()+2,0));
if(lastDirection.getY() > 0)
pos = pos.add(new Vector2d(0,player.size.getX()-2));
if(lastDirection.getY() < 0)
pos = pos.add(new Vector2d(0,-player.size.getX()+2));
IceBolt tmp = new IceBolt(pos, new Vector2d(10, 10));
tmp.setDirection(lastDirection.mul(1));
level.addGameElement(tmp);
}
}
if (((Player) player).getHealth()<=0){
app.cp.removeAll();
app.cp.validate();
app.gameContent = new GameContent(this);
app.loader = new LevelLoader(app.gameContent, app);
this.timer.stop();
app.startMainMenu();
}
}
if (e.getActionCommand() == "Timer"){
GameElement tmpRem = null;
for(GameElement element : level.getGameElements()){
GameEvent event = new GameEvent(null, EventType.TIMER, this);
element.GameEventPerformed(event);
if(element.size.getX() == 0 || element.size.getY() == 0){
tmpRem = element;
}
}
if (tmpRem != null) {
level.removeElement(tmpRem);
}
app.camera.repaint();
// System.out.println("Timediff " + (System.currentTimeMillis() - time));
}
}
public void addGameElement(GameElement element){
level.addGameElement(element);
}
public void startMainMenu(){
app.cp.removeAll();
app.cp.validate();
app.gameContent = new GameContent(this);
app.loader = new LevelLoader(app.gameContent, app);
this.timer.stop();
app.startMainMenu();
}
public void lost(Player player) {
startMainMenu();
}
public void changeTimer(boolean newStatus){
if(newStatus &&(!timer.isRunning())) timer.start();
if((!newStatus) &&timer.isRunning()) timer.stop();
}
}
| false | true | public void actionPerformed(ActionEvent e) {
player = (Player)level.getPlayer();
Vector2d position = player.getPosition();
// TODO: abfragen, welche Bits gesetzt sind und ensprechend handeln
if (app.editmode==true){
movedelay=movedelay-1;
if (keys.get(100)) {// cheat left
player.setPosition(position.addX(-10));
System.out.println("CHEAT LEFT");
}
if (keys.get(104)) {// cheat up
player.setPosition(position.addY(-10));
System.out.println("CHEAT UP");
}
if (keys.get(98)) {// cheat down
player.setPosition(position.addY(10));
System.out.println("CHEAT DOWN");
}
if (keys.get(102)) {// cheat right
player.setPosition(position.addX(10));
System.out.println("CHEAT RIGHT");
}
if (keys.get(107) && editspeed > 10) {// left
editspeed-=10;
System.out.println(editspeed);
keys.clear();
}
else if (keys.get(107) && editspeed > 0) {// left
editspeed-=1;
System.out.println(editspeed);
keys.clear();
}
if (keys.get(109) && editspeed < 10) {// left
editspeed+=1;
keys.clear();
System.out.println(editspeed);
}
else if (keys.get(109) && editspeed < 100) {// left
editspeed+=10;
keys.clear();
System.out.println(editspeed);
}
if (keys.get(37) && movedelay <=0) {// left
player.setPosition(position.addX(-1));
movedelay=editspeed;
System.out.println("LEFT");
}
if (keys.get(38) && movedelay <=0) {// up
player.setPosition(position.addY(-1));
movedelay=editspeed;
System.out.println("UP");
}
if (keys.get(39) && movedelay <=0) {// right
player.setPosition(position.addX(1));
movedelay=editspeed;
System.out.println("RIGHT");
}
if (keys.get(40) && movedelay <=0) {// down
player.setPosition(position.addY(1));
movedelay=editspeed;
System.out.println("DOWN");
}
if (keys.get(103)) {// position output
System.out.println("x= " + player.getPosition().getX() + " ; y= " + player.getPosition().getY());
}
}
if (app.editmode==false){
reduceDelay();
player = (Player)level.getPlayer();
if(!(direction.getX() == 0 && direction.getY() == 0)){
lastDirection = direction;
}
direction = new Vector2d(0,0);
for(Active active : level.getActives()){
active.interaction(this, settings, keys);
}
if (keys.get(100)) {// cheat left
player.setPosition(position.addX(-10));
System.out.println("CHEAT LEFT");
}
if (keys.get(104)) {// cheat up
player.setPosition(position.addY(-10));
System.out.println("CHEAT UP");
}
if (keys.get(98)) {// cheat down
player.setPosition(position.addY(10));
System.out.println("CHEAT DOWN");
}
if (keys.get(102)) {// cheat right
player.setPosition(position.addX(10));
System.out.println("CHEAT RIGHT");
}
if (keys.get(101)) {// cheat Leben
player.setHealth(player.getHealth()+1000);
System.out.println("CHEAT Leben");
}
if (keys.get(103)) {// position output
System.out.println("x= " + player.getPosition().getX() + "y= " + player.getPosition().getY());
}
if (keys.get(99)) {// Exit
if (level.getExit() != null){
level.getPlayer().setPosition(level.getExit().getPosition().addX(10).addY(60));}
System.out.println("CHEAT EXIT");
}
if (keys.get(37)) {// left arrow
direction = direction.addX(-1);
//System.out.println("LEFT");
}
if (keys.get(38)) {// up arrow
direction = direction.addY(-1);
//System.out.println("UP");
}
if (keys.get(39)) {// right arrow
direction = direction.addX(1);
//System.out.println("RIGHT");
}
if (keys.get(40)) {// down arrow
direction = direction.addY(1);
//System.out.println("DOWN");
}
if (checkKey(83)) { // s
keys.clear();
//timer.stop();
if (level.getPlayer() != null) {
if (new_shop == null) {
// initialize shop
new_shop = new ShopSystem((Player)level.getPlayer());
new_shop.fillShop(new_shop.getvermoegen(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
}
else{
System.out.println("Shop Visable you have " + player.getMoney() + " Geld");
new_shop.fillShop(new_shop.getvermoegen(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
player.setMoney(new_shop.getvermoegen());
}
}
}
if (keys.get(KeyEvent.VK_Q)){// q (fire bolt)
System.out.println(delay[KeyEvent.VK_Q]);
if(delay[KeyEvent.VK_Q] <= 0 && player.reduceMana(20, this)){
delay[KeyEvent.VK_Q] = 250;
Vector2d pos = new Vector2d(position.add(player.size.mul(0.5)).add(new Vector2d(-5, -5)));
if(lastDirection.getX() > 0)
pos = pos.add(new Vector2d(player.size.getX()-2,0));
if(lastDirection.getX() < 0)
pos = pos.add(new Vector2d(-player.size.getX()+2,0));
if(lastDirection.getY() > 0)
pos = pos.add(new Vector2d(0,player.size.getX()-2));
if(lastDirection.getY() < 0)
pos = pos.add(new Vector2d(0,-player.size.getX()+2));
FireBolt tmp = new FireBolt(pos, new Vector2d(10, 10));
tmp.setDirection(lastDirection.mul(1));
level.addGameElement(tmp);
}
}
if (keys.get(KeyEvent.VK_W)){// w (ice bolt)
System.out.println(delay[KeyEvent.VK_W]);
if(delay[KeyEvent.VK_W] <= 0 && player.reduceMana(10, this)){
delay[KeyEvent.VK_W] = 250;
Vector2d pos = new Vector2d(position.add(player.size.mul(0.5)).add(new Vector2d(-5, -5)));
if(lastDirection.getX() > 0)
pos = pos.add(new Vector2d(player.size.getX()-2,0));
if(lastDirection.getX() < 0)
pos = pos.add(new Vector2d(-player.size.getX()+2,0));
if(lastDirection.getY() > 0)
pos = pos.add(new Vector2d(0,player.size.getX()-2));
if(lastDirection.getY() < 0)
pos = pos.add(new Vector2d(0,-player.size.getX()+2));
IceBolt tmp = new IceBolt(pos, new Vector2d(10, 10));
tmp.setDirection(lastDirection.mul(1));
level.addGameElement(tmp);
}
}
if (((Player) player).getHealth()<=0){
app.cp.removeAll();
app.cp.validate();
app.gameContent = new GameContent(this);
app.loader = new LevelLoader(app.gameContent, app);
this.timer.stop();
app.startMainMenu();
}
}
if (e.getActionCommand() == "Timer"){
GameElement tmpRem = null;
for(GameElement element : level.getGameElements()){
GameEvent event = new GameEvent(null, EventType.TIMER, this);
element.GameEventPerformed(event);
if(element.size.getX() == 0 || element.size.getY() == 0){
tmpRem = element;
}
}
if (tmpRem != null) {
level.removeElement(tmpRem);
}
app.camera.repaint();
// System.out.println("Timediff " + (System.currentTimeMillis() - time));
}
}
| public void actionPerformed(ActionEvent e) {
player = (Player)level.getPlayer();
Vector2d position = player.getPosition();
// TODO: abfragen, welche Bits gesetzt sind und ensprechend handeln
if (app.editmode==true){
movedelay=movedelay-1;
if (keys.get(100)) {// cheat left
player.setPosition(position.addX(-10));
System.out.println("CHEAT LEFT");
}
if (keys.get(104)) {// cheat up
player.setPosition(position.addY(-10));
System.out.println("CHEAT UP");
}
if (keys.get(98)) {// cheat down
player.setPosition(position.addY(10));
System.out.println("CHEAT DOWN");
}
if (keys.get(102)) {// cheat right
player.setPosition(position.addX(10));
System.out.println("CHEAT RIGHT");
}
if (keys.get(107) && editspeed > 10) {// left
editspeed-=10;
System.out.println(editspeed);
keys.clear();
}
else if (keys.get(107) && editspeed > 0) {// left
editspeed-=1;
System.out.println(editspeed);
keys.clear();
}
if (keys.get(109) && editspeed < 10) {// left
editspeed+=1;
keys.clear();
System.out.println(editspeed);
}
else if (keys.get(109) && editspeed < 100) {// left
editspeed+=10;
keys.clear();
System.out.println(editspeed);
}
if (keys.get(37) && movedelay <=0) {// left
player.setPosition(position.addX(-1));
movedelay=editspeed;
System.out.println("LEFT");
}
if (keys.get(38) && movedelay <=0) {// up
player.setPosition(position.addY(-1));
movedelay=editspeed;
System.out.println("UP");
}
if (keys.get(39) && movedelay <=0) {// right
player.setPosition(position.addX(1));
movedelay=editspeed;
System.out.println("RIGHT");
}
if (keys.get(40) && movedelay <=0) {// down
player.setPosition(position.addY(1));
movedelay=editspeed;
System.out.println("DOWN");
}
if (keys.get(103)) {// position output
System.out.println("x= " + player.getPosition().getX() + " ; y= " + player.getPosition().getY());
}
}
if (app.editmode==false){
reduceDelay();
player = (Player)level.getPlayer();
if(!(direction.getX() == 0 && direction.getY() == 0)){
lastDirection = direction;
}
direction = new Vector2d(0,0);
for(Active active : level.getActives()){
active.interaction(this, settings, keys);
}
if (keys.get(100)) {// cheat left
player.setPosition(position.addX(-10));
System.out.println("CHEAT LEFT");
}
if (keys.get(104)) {// cheat up
player.setPosition(position.addY(-10));
System.out.println("CHEAT UP");
}
if (keys.get(98)) {// cheat down
player.setPosition(position.addY(10));
System.out.println("CHEAT DOWN");
}
if (keys.get(102)) {// cheat right
player.setPosition(position.addX(10));
System.out.println("CHEAT RIGHT");
}
if (keys.get(101)) {// cheat Leben
player.setHealth(player.getHealth()+1000);
System.out.println("CHEAT Leben");
}
if (keys.get(103)) {// position output
System.out.println("x= " + player.getPosition().getX() + "y= " + player.getPosition().getY());
}
if (keys.get(99)) {// Exit
if (level.getExit() != null){
level.getPlayer().setPosition(level.getExit().getPosition().addX(10).addY(60));}
System.out.println("CHEAT EXIT");
}
if (keys.get(37)) {// left arrow
direction = direction.addX(-1);
//System.out.println("LEFT");
}
if (keys.get(38)) {// up arrow
direction = direction.addY(-1);
//System.out.println("UP");
}
if (keys.get(39)) {// right arrow
direction = direction.addX(1);
//System.out.println("RIGHT");
}
if (keys.get(40)) {// down arrow
direction = direction.addY(1);
//System.out.println("DOWN");
}
if (checkKey(83)) { // s
keys.clear();
//timer.stop();
if (level.getPlayer() != null) {
if (new_shop == null) {
// initialize shop
new_shop = new ShopSystem((Player)level.getPlayer());
((Player)level.getPlayer()).setMoney(100);
new_shop.fillShop(((Player)level.getPlayer()).getMoney(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
}
else{
System.out.println("Shop Visable you have " + player.getMoney() + " Geld");
new_shop.fillShop(((Player)level.getPlayer()).getMoney(), new ShopItem("Armor",20), new ShopItem("Health", 10), new ShopItem("Mana", 5));
player.setMoney(new_shop.getvermoegen());
}
}
}
if (keys.get(KeyEvent.VK_Q)){// q (fire bolt)
System.out.println(delay[KeyEvent.VK_Q]);
if(delay[KeyEvent.VK_Q] <= 0 && player.reduceMana(20, this)){
delay[KeyEvent.VK_Q] = 250;
Vector2d pos = new Vector2d(position.add(player.size.mul(0.5)).add(new Vector2d(-5, -5)));
if(lastDirection.getX() > 0)
pos = pos.add(new Vector2d(player.size.getX()-2,0));
if(lastDirection.getX() < 0)
pos = pos.add(new Vector2d(-player.size.getX()+2,0));
if(lastDirection.getY() > 0)
pos = pos.add(new Vector2d(0,player.size.getX()-2));
if(lastDirection.getY() < 0)
pos = pos.add(new Vector2d(0,-player.size.getX()+2));
FireBolt tmp = new FireBolt(pos, new Vector2d(10, 10));
tmp.setDirection(lastDirection.mul(1));
level.addGameElement(tmp);
}
}
if (keys.get(KeyEvent.VK_W)){// w (ice bolt)
System.out.println(delay[KeyEvent.VK_W]);
if(delay[KeyEvent.VK_W] <= 0 && player.reduceMana(10, this)){
delay[KeyEvent.VK_W] = 250;
Vector2d pos = new Vector2d(position.add(player.size.mul(0.5)).add(new Vector2d(-5, -5)));
if(lastDirection.getX() > 0)
pos = pos.add(new Vector2d(player.size.getX()-2,0));
if(lastDirection.getX() < 0)
pos = pos.add(new Vector2d(-player.size.getX()+2,0));
if(lastDirection.getY() > 0)
pos = pos.add(new Vector2d(0,player.size.getX()-2));
if(lastDirection.getY() < 0)
pos = pos.add(new Vector2d(0,-player.size.getX()+2));
IceBolt tmp = new IceBolt(pos, new Vector2d(10, 10));
tmp.setDirection(lastDirection.mul(1));
level.addGameElement(tmp);
}
}
if (((Player) player).getHealth()<=0){
app.cp.removeAll();
app.cp.validate();
app.gameContent = new GameContent(this);
app.loader = new LevelLoader(app.gameContent, app);
this.timer.stop();
app.startMainMenu();
}
}
if (e.getActionCommand() == "Timer"){
GameElement tmpRem = null;
for(GameElement element : level.getGameElements()){
GameEvent event = new GameEvent(null, EventType.TIMER, this);
element.GameEventPerformed(event);
if(element.size.getX() == 0 || element.size.getY() == 0){
tmpRem = element;
}
}
if (tmpRem != null) {
level.removeElement(tmpRem);
}
app.camera.repaint();
// System.out.println("Timediff " + (System.currentTimeMillis() - time));
}
}
|
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/msgbus/ManagementPlugin.java b/araqne-logdb/src/main/java/org/araqne/logdb/msgbus/ManagementPlugin.java
index 8bb83c7c..fee33df8 100644
--- a/araqne-logdb/src/main/java/org/araqne/logdb/msgbus/ManagementPlugin.java
+++ b/araqne-logdb/src/main/java/org/araqne/logdb/msgbus/ManagementPlugin.java
@@ -1,647 +1,650 @@
/*
* Copyright 2013 Eediom 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.araqne.logdb.msgbus;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Requires;
import org.araqne.api.PrimitiveConverter;
import org.araqne.log.api.FieldDefinition;
import org.araqne.logdb.AccountService;
import org.araqne.logdb.Permission;
import org.araqne.logdb.Privilege;
import org.araqne.logstorage.LogCryptoProfile;
import org.araqne.logstorage.LogCryptoProfileRegistry;
import org.araqne.logstorage.LogFileService;
import org.araqne.logstorage.LogFileServiceRegistry;
import org.araqne.logstorage.LogRetentionPolicy;
import org.araqne.logstorage.LogStorage;
import org.araqne.logstorage.LogTableRegistry;
import org.araqne.logstorage.StorageConfig;
import org.araqne.logstorage.TableConfig;
import org.araqne.logstorage.TableConfigSpec;
import org.araqne.logstorage.TableSchema;
import org.araqne.msgbus.MessageBus;
import org.araqne.msgbus.MsgbusException;
import org.araqne.msgbus.Request;
import org.araqne.msgbus.Response;
import org.araqne.msgbus.Session;
import org.araqne.msgbus.handler.AllowGuestAccess;
import org.araqne.msgbus.handler.CallbackType;
import org.araqne.msgbus.handler.MsgbusMethod;
import org.araqne.msgbus.handler.MsgbusPlugin;
@Component(name = "logdb-management-msgbus")
@MsgbusPlugin
public class ManagementPlugin {
private final org.slf4j.Logger slog = org.slf4j.LoggerFactory.getLogger(ManagementPlugin.class.getName());
@Requires
private AccountService accountService;
@Requires
private LogTableRegistry tableRegistry;
@Requires
private MessageBus msgbus;
@Requires
private LogStorage storage;
@Requires
private LogFileServiceRegistry lfsRegistry;
@Requires
private LogCryptoProfileRegistry logCryptoProfileRegistry;
private UploadDataHandler uploadDataHandler = new UploadDataHandler();
@AllowGuestAccess
@MsgbusMethod
public void login(Request req, Response resp) {
Session session = req.getSession();
if (session.get("araqne_logdb_session") != null)
throw new MsgbusException("logdb", "already-logon");
String loginName = req.getString("login_name", true);
String password = req.getString("password", true);
org.araqne.logdb.Session dbSession = accountService.login(loginName, password);
if (session.getOrgDomain() == null && session.getAdminLoginName() == null) {
session.setProperty("org_domain", "localhost");
session.setProperty("admin_login_name", loginName);
session.setProperty("auth", "logdb");
}
session.setProperty("araqne_logdb_session", dbSession);
}
@MsgbusMethod
public void logout(Request req, Response resp) {
Session session = req.getSession();
org.araqne.logdb.Session dbSession = (org.araqne.logdb.Session) session.get("araqne_logdb_session");
if (dbSession != null) {
try {
accountService.logout(dbSession);
} catch (Throwable t) {
}
session.unsetProperty("araqne_logdb_session");
}
String auth = session.getString("auth");
if (auth != null && auth.equals("logdb"))
msgbus.closeSession(session);
}
@MsgbusMethod(type = CallbackType.SessionClosed)
public void onClose(Session session) {
if (session == null)
return;
org.araqne.logdb.Session dbSession = (org.araqne.logdb.Session) session.get("araqne_logdb_session");
if (dbSession != null) {
try {
accountService.logout(dbSession);
} catch (Throwable t) {
}
session.unsetProperty("araqne_logdb_session");
}
}
@MsgbusMethod
public void listAccounts(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
List<Object> accounts = new ArrayList<Object>();
for (String loginName : accountService.getAccountNames()) {
List<Privilege> privileges = accountService.getPrivileges(session, loginName);
Map<String, Object> m = new HashMap<String, Object>();
m.put("login_name", loginName);
m.put("privileges", serialize(privileges));
accounts.add(m);
}
resp.put("accounts", accounts);
}
@MsgbusMethod
public void getInstanceGuid(Request req, Response resp) {
resp.put("instance_guid", accountService.getInstanceGuid());
}
private List<Object> serialize(List<Privilege> privileges) {
List<Object> l = new ArrayList<Object>();
for (Privilege p : privileges)
l.add(PrimitiveConverter.serialize(p));
return l;
}
@MsgbusMethod
public void changePassword(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
String password = req.getString("password", true);
accountService.changePassword(session, loginName, password);
}
@MsgbusMethod
public void createAccount(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
String password = req.getString("password", true);
accountService.createAccount(session, loginName, password);
}
@MsgbusMethod
public void removeAccount(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
accountService.removeAccount(session, loginName);
}
@MsgbusMethod
public void getPrivileges(Request req, Response resp) {
org.araqne.logdb.Session session = ensureDbSession(req);
String loginName = req.getString("login_name", true);
List<Privilege> privileges = accountService.getPrivileges(session, loginName);
Map<String, List<String>> m = new HashMap<String, List<String>>();
List<String> l = Arrays.asList(Permission.READ.toString());
for (Privilege p : privileges)
m.put(p.getTableName(), l);
resp.putAll(m);
}
@SuppressWarnings("unchecked")
@MsgbusMethod
public void setPrivileges(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
List<String> tableNames = (List<String>) req.get("table_names", true);
List<Privilege> privileges = new ArrayList<Privilege>();
for (String tableName : tableNames)
privileges.add(new Privilege(loginName, tableName, Permission.READ));
accountService.setPrivileges(session, loginName, privileges);
}
@MsgbusMethod
public void grantPrivilege(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
String tableName = req.getString("table_name", true);
accountService.grantPrivilege(session, loginName, tableName, Permission.READ);
}
@SuppressWarnings("unchecked")
@MsgbusMethod
public void grantPrivileges(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
List<String> tableNames = (List<String>) req.get("table_names", true);
for (String tableName : tableNames)
accountService.grantPrivilege(session, loginName, tableName, Permission.READ);
}
@MsgbusMethod
public void revokePrivilege(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
String tableName = req.getString("table_name", true);
accountService.revokePrivilege(session, loginName, tableName, Permission.READ);
}
@SuppressWarnings("unchecked")
@MsgbusMethod
public void revokePrivileges(Request req, Response resp) {
org.araqne.logdb.Session session = ensureAdminSession(req);
String loginName = req.getString("login_name", true);
List<String> tableNames = (List<String>) req.get("table_names");
for (String tableName : tableNames)
accountService.revokePrivilege(session, loginName, tableName, Permission.READ);
}
@MsgbusMethod
public void listTables(Request req, Response resp) {
org.araqne.logdb.Session session = ensureDbSession(req);
Map<String, Object> tables = new HashMap<String, Object>();
Map<String, Object> fields = new HashMap<String, Object>();
if (session.isAdmin()) {
for (TableSchema schema : tableRegistry.getTableSchemas()) {
tables.put(schema.getName(), getTableMetadata(schema));
List<FieldDefinition> defs = schema.getFieldDefinitions();
if (defs != null)
fields.put(schema.getName(), PrimitiveConverter.serialize(defs));
}
} else {
List<Privilege> privileges = accountService.getPrivileges(session, session.getLoginName());
for (Privilege p : privileges) {
if (p.getPermissions().size() > 0 && tableRegistry.exists(p.getTableName())) {
TableSchema schema = tableRegistry.getTableSchema(p.getTableName(), true);
tables.put(p.getTableName(), getTableMetadata(schema));
List<FieldDefinition> defs = schema.getFieldDefinitions();
if (defs != null)
fields.put(p.getTableName(), PrimitiveConverter.serialize(defs));
}
}
}
resp.put("tables", tables);
// @since 2.0.2
resp.put("fields", fields);
}
@MsgbusMethod
public void getTableInfo(Request req, Response resp) {
String tableName = req.getString("table", true);
checkTableAccess(req, tableName, Permission.READ);
TableSchema schema = tableRegistry.getTableSchema(tableName);
List<FieldDefinition> defs = schema.getFieldDefinitions();
if (defs != null)
resp.put("fields", PrimitiveConverter.serialize(defs));
resp.put("table", getTableMetadata(schema));
}
private Map<String, Object> getTableMetadata(TableSchema schema) {
Map<String, Object> metadata = new HashMap<String, Object>();
Map<String, String> strings = schema.getMetadata();
for (String key : strings.keySet()) {
metadata.put(key, strings.get(key));
}
return metadata;
}
/**
* @since 2.0.3
*/
@SuppressWarnings("unchecked")
@MsgbusMethod
public void setTableFields(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
List<Object> l = (List<Object>) req.get("fields");
List<FieldDefinition> fields = null;
if (l != null) {
fields = new ArrayList<FieldDefinition>();
for (Object o : l) {
Map<String, Object> m = (Map<String, Object>) o;
FieldDefinition f = new FieldDefinition();
f.setName((String) m.get("name"));
f.setType((String) m.get("type"));
f.setLength((Integer) m.get("length"));
fields.add(f);
}
}
TableSchema schema = tableRegistry.getTableSchema(tableName, true);
schema.setFieldDefinitions(fields);
tableRegistry.alterTable(tableName, schema);
}
@SuppressWarnings("unchecked")
@MsgbusMethod
public void setTableMetadata(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
Map<String, Object> metadata = (Map<String, Object>) req.get("metadata", true);
TableSchema schema = tableRegistry.getTableSchema(tableName, true);
for (String key : metadata.keySet()) {
Object value = metadata.get(key);
schema.getMetadata().put(key, value == null ? null : value.toString());
}
tableRegistry.alterTable(tableName, schema);
}
@SuppressWarnings("unchecked")
@MsgbusMethod
public void unsetTableMetadata(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
List<Object> keys = (List<Object>) req.get("keys", true);
TableSchema schema = tableRegistry.getTableSchema(tableName, true);
Map<String, String> metadata = schema.getMetadata();
for (Object key : keys) {
metadata.remove(key.toString());
}
tableRegistry.alterTable(tableName, schema);
}
private void checkTableAccess(Request req, String tableName, Permission permission) {
org.araqne.logdb.Session session = (org.araqne.logdb.Session) req.getSession().get("araqne_logdb_session");
if (session == null)
throw new MsgbusException("logdb", "no-logdb-session");
boolean allowed = session.isAdmin() || accountService.checkPermission(session, tableName, permission);
if (!allowed)
throw new MsgbusException("logdb", "no-permission");
}
@SuppressWarnings("unchecked")
@MsgbusMethod
public void createTable(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
String engineType = req.getString("type", true);
String basePath = req.getString("base_path");
Map<String, String> primaryConfigs = (Map<String, String>) req.get("primary_configs");
if (primaryConfigs == null)
primaryConfigs = new HashMap<String, String>();
Map<String, String> replicaConfigs = (Map<String, String>) req.get("replica_configs");
if (replicaConfigs == null)
replicaConfigs = new HashMap<String, String>();
Map<String, String> metadata = (Map<String, String>) req.get("metadata");
LogFileService lfs = lfsRegistry.getLogFileService(engineType);
StorageConfig primaryStorage = new StorageConfig(engineType, basePath);
for (TableConfigSpec spec : lfs.getConfigSpecs()) {
String value = primaryConfigs.get(spec.getKey());
if (value != null) {
if (spec.getValidator() != null)
spec.getValidator().validate(spec.getKey(), Arrays.asList(value));
primaryStorage.getConfigs().add(new TableConfig(spec.getKey(), value));
} else if (!spec.isOptional())
throw new MsgbusException("logdb", "table-config-missing");
}
// TODO check replica storage initiation
StorageConfig replicaStorage = primaryStorage.clone();
for (TableConfigSpec spec : lfs.getReplicaConfigSpecs()) {
String value = replicaConfigs.get(spec.getKey());
if (value != null) {
if (spec.getValidator() != null)
spec.getValidator().validate(spec.getKey(), Arrays.asList(value));
replicaStorage.getConfigs().add(new TableConfig(spec.getKey(), value));
} else if (!spec.isOptional())
throw new MsgbusException("logdb", "table-config-missing");
}
- TableSchema schema = new TableSchema(tableName, new StorageConfig("v3p"));
+ TableSchema schema = new TableSchema();
+ schema.setName(tableName);
+ schema.setPrimaryStorage(primaryStorage);
+ schema.setReplicaStorage(replicaStorage);
schema.setMetadata(metadata);
storage.createTable(schema);
}
@MsgbusMethod
public void dropTable(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
storage.dropTable(tableName);
}
@MsgbusMethod
public void dropTables(Request req, Response resp) {
ensureAdminSession(req);
@SuppressWarnings("unchecked")
List<String> tableNames = (List<String>) req.get("tables", true);
for (String name : tableNames)
storage.dropTable(name);
}
private org.araqne.logdb.Session ensureAdminSession(Request req) {
org.araqne.logdb.Session session = (org.araqne.logdb.Session) req.getSession().get("araqne_logdb_session");
if (session != null && !session.isAdmin())
throw new SecurityException("logdb management is not allowed to " + session.getLoginName());
return session;
}
private org.araqne.logdb.Session ensureDbSession(Request req) {
org.araqne.logdb.Session session = (org.araqne.logdb.Session) req.getSession().get("araqne_logdb_session");
if (session == null)
throw new SecurityException("logdb session not found: " + req.getSession().getAdminLoginName());
return session;
}
@MsgbusMethod
public void purge(Request req, Response resp) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
String tableName = req.getString("table");
Date fromDay = null;
Date toDay = null;
try {
fromDay = df.parse(req.getString("from_day"));
toDay = df.parse(req.getString("to_day"));
} catch (ParseException e) {
throw new MsgbusException("logdb", "not-parse-date");
}
storage.purge(tableName, fromDay, toDay);
}
@MsgbusMethod
public void getLogDates(Request req, Response resp) {
String tableName = req.getString("table");
Collection<Date> logDates = storage.getLogDates(tableName);
resp.put("logdates", logDates);
}
@MsgbusMethod
public void getCryptoProfiles(Request req, Response resp) {
List<Object> l = new ArrayList<Object>();
for (LogCryptoProfile p : logCryptoProfileRegistry.getProfiles()) {
Map<String, Object> m = serialize(p);
l.add(m);
}
resp.put("profiles", l);
}
private Map<String, Object> serialize(LogCryptoProfile profile) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("name", profile.getName());
m.put("cipher", profile.getCipher());
m.put("digest", profile.getDigest());
m.put("file_path", profile.getFilePath());
return m;
}
@MsgbusMethod
public void getCryptoProfile(Request req, Response resp) {
String name = req.getString("name");
resp.put("profile", logCryptoProfileRegistry.getProfile(name));
}
@MsgbusMethod
public void addCryptoProfile(Request req, Response resp) {
String name = req.getString("name");
String cipher = req.getString("cipher");
String digest = req.getString("digest");
String filePath = req.getString("file_path");
String password = req.getString("password");
LogCryptoProfile p = new LogCryptoProfile();
p.setName(name);
p.setCipher(cipher);
p.setDigest(digest);
p.setFilePath(filePath);
p.setPassword(password);
logCryptoProfileRegistry.addProfile(p);
}
@MsgbusMethod
public void removeCryptoProfile(Request req, Response resp) {
String name = req.getString("name");
logCryptoProfileRegistry.removeProfile(name);
}
@MsgbusMethod
public void getCipherTransformers(Request req, Response resp) {
List<String> l = new ArrayList<String>();
l.add("AES/CBC/NoPadding");
l.add("AES/CBC/PKCS5Padding");
l.add("AES/ECB/NoPadding");
l.add("AES/ECB/PKCS5Padding");
l.add("DES/CBC/NoPadding");
l.add("DES/CBC/PKCS5Padding");
l.add("DES/ECB/NoPadding");
l.add("DES/ECB/PKCS5Padding");
l.add("DESede/CBC/NoPadding");
l.add("DESede/CBC/PKCS5Padding");
l.add("DESede/ECB/NoPadding");
l.add("DESede/ECB/PKCS5Padding");
l.add("RSA/ECB/PKCS1Padding");
l.add("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
l.add("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
resp.put("cipher_transformers", l);
}
@MsgbusMethod
public void loadTextFile(Request req, Response resp) throws IOException {
uploadDataHandler.loadTextFile(storage, req, resp);
}
@MsgbusMethod
public void getStorageEngines(Request req, Response resp) {
Locale locale = req.getSession().getLocale();
String s = req.getString("locale");
if (s != null)
locale = new Locale(s);
List<Object> engines = new ArrayList<Object>();
for (String type : lfsRegistry.getInstalledTypes()) {
// prevent hang
if (type.equals("v1"))
continue;
LogFileService lfs = lfsRegistry.getLogFileService(type);
Map<String, Object> engine = new HashMap<String, Object>();
engine.put("type", type);
List<Object> primarySpecs = new ArrayList<Object>();
for (TableConfigSpec spec : lfs.getConfigSpecs())
primarySpecs.add(marshal(spec, locale));
List<Object> replicaSpecs = new ArrayList<Object>();
for (TableConfigSpec spec : lfs.getReplicaConfigSpecs())
replicaSpecs.add(marshal(spec, locale));
engine.put("primary_config_specs", primarySpecs);
engine.put("replica_config_specs", replicaSpecs);
engines.add(engine);
}
resp.put("engines", engines);
}
private Map<String, Object> marshal(TableConfigSpec spec, Locale locale) {
String displayName = spec.getDisplayNames().get(locale);
if (displayName == null)
displayName = spec.getDisplayNames().get(Locale.ENGLISH);
String description = spec.getDescriptions().get(locale);
if (description == null)
description = spec.getDescriptions().get(Locale.ENGLISH);
Map<String, Object> m = new HashMap<String, Object>();
m.put("type", spec.getType().toString().toLowerCase());
m.put("key", spec.getKey());
m.put("optional", spec.isOptional());
m.put("updatable", spec.isUpdatable());
m.put("display_name", displayName);
m.put("description", description);
m.put("enums", spec.getEnums());
return m;
}
@MsgbusMethod
public void setRetention(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
int retention = req.getInteger("retention", true);
if (!tableRegistry.exists(tableName))
throw new MsgbusException("logdb", "table-not-found");
if (retention < 0)
throw new MsgbusException("logdb", "invalid-retention");
LogRetentionPolicy p = new LogRetentionPolicy();
p.setTableName(tableName);
p.setRetentionDays(retention);
storage.setRetentionPolicy(p);
}
}
| true | true | public void createTable(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
String engineType = req.getString("type", true);
String basePath = req.getString("base_path");
Map<String, String> primaryConfigs = (Map<String, String>) req.get("primary_configs");
if (primaryConfigs == null)
primaryConfigs = new HashMap<String, String>();
Map<String, String> replicaConfigs = (Map<String, String>) req.get("replica_configs");
if (replicaConfigs == null)
replicaConfigs = new HashMap<String, String>();
Map<String, String> metadata = (Map<String, String>) req.get("metadata");
LogFileService lfs = lfsRegistry.getLogFileService(engineType);
StorageConfig primaryStorage = new StorageConfig(engineType, basePath);
for (TableConfigSpec spec : lfs.getConfigSpecs()) {
String value = primaryConfigs.get(spec.getKey());
if (value != null) {
if (spec.getValidator() != null)
spec.getValidator().validate(spec.getKey(), Arrays.asList(value));
primaryStorage.getConfigs().add(new TableConfig(spec.getKey(), value));
} else if (!spec.isOptional())
throw new MsgbusException("logdb", "table-config-missing");
}
// TODO check replica storage initiation
StorageConfig replicaStorage = primaryStorage.clone();
for (TableConfigSpec spec : lfs.getReplicaConfigSpecs()) {
String value = replicaConfigs.get(spec.getKey());
if (value != null) {
if (spec.getValidator() != null)
spec.getValidator().validate(spec.getKey(), Arrays.asList(value));
replicaStorage.getConfigs().add(new TableConfig(spec.getKey(), value));
} else if (!spec.isOptional())
throw new MsgbusException("logdb", "table-config-missing");
}
TableSchema schema = new TableSchema(tableName, new StorageConfig("v3p"));
schema.setMetadata(metadata);
storage.createTable(schema);
}
| public void createTable(Request req, Response resp) {
ensureAdminSession(req);
String tableName = req.getString("table", true);
String engineType = req.getString("type", true);
String basePath = req.getString("base_path");
Map<String, String> primaryConfigs = (Map<String, String>) req.get("primary_configs");
if (primaryConfigs == null)
primaryConfigs = new HashMap<String, String>();
Map<String, String> replicaConfigs = (Map<String, String>) req.get("replica_configs");
if (replicaConfigs == null)
replicaConfigs = new HashMap<String, String>();
Map<String, String> metadata = (Map<String, String>) req.get("metadata");
LogFileService lfs = lfsRegistry.getLogFileService(engineType);
StorageConfig primaryStorage = new StorageConfig(engineType, basePath);
for (TableConfigSpec spec : lfs.getConfigSpecs()) {
String value = primaryConfigs.get(spec.getKey());
if (value != null) {
if (spec.getValidator() != null)
spec.getValidator().validate(spec.getKey(), Arrays.asList(value));
primaryStorage.getConfigs().add(new TableConfig(spec.getKey(), value));
} else if (!spec.isOptional())
throw new MsgbusException("logdb", "table-config-missing");
}
// TODO check replica storage initiation
StorageConfig replicaStorage = primaryStorage.clone();
for (TableConfigSpec spec : lfs.getReplicaConfigSpecs()) {
String value = replicaConfigs.get(spec.getKey());
if (value != null) {
if (spec.getValidator() != null)
spec.getValidator().validate(spec.getKey(), Arrays.asList(value));
replicaStorage.getConfigs().add(new TableConfig(spec.getKey(), value));
} else if (!spec.isOptional())
throw new MsgbusException("logdb", "table-config-missing");
}
TableSchema schema = new TableSchema();
schema.setName(tableName);
schema.setPrimaryStorage(primaryStorage);
schema.setReplicaStorage(replicaStorage);
schema.setMetadata(metadata);
storage.createTable(schema);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.