repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
leonardoanalista/java2word | java2word/src/test/java/word/w2004/AbstractHeadingTest.java | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/AbstractHeading.java
// public abstract class AbstractHeading<E> implements IElement, IFluentElementStylable<E>{
//
// /**
// * this is actual heading1, heading2 or heading3.
// */
// private String headingType;
// private String value; //value/text for the Heading
//
// protected AbstractHeading(String headingType, String value){
// this.headingType = headingType;
// this.value = value;
// }
//
// private String template =
// "\n<w:p wsp:rsidR=\"004429ED\" wsp:rsidRDefault=\"00000000\" wsp:rsidP=\"004429ED\">"
// +"\n <w:pPr>"
// +"\n <w:pStyle w:val=\"{heading}\" />"
// +"\n {styleAlign}"
// +"\n </w:pPr>"
// +"\n <w:r>"
// +"\n {styleText}"
// +"\n <w:t>{value}</w:t>"
// +"\n </w:r>"
// +"\n</w:p>";
//
// private HeadingStyle style = new HeadingStyle();
//
// @Override
// public String getContent() {
// if("".equals(this.value)){
// return "";
// }
//
// //For convention, it should be the last thing before returning the xml content.
// String txt = style.getNewContentWithStyle(getTemplate());
//
// return txt.replace("{value}", this.value);
// }
//
//
// // #### Getters and setters ####
// public String getTemplate() {
// return this.template.replace("{heading}", this.headingType);
// }
//
// //Implements the stylable and the heading classes reuse it
// @Override
// @SuppressWarnings("unchecked")
// public E withStyle() {
// this.style.setElement(this); //, Heading1.class
// return (E) this.style;
// }
//
// }
| import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.AbstractHeading; | package word.w2004;
public class AbstractHeadingTest extends Assert{
//### TODO: I won't test the method applyStyle because I will pull this off to another class in order to reuse this for all other "stylable" class.
//anonymous implementation - this is the way I leaned how to test abstract classes.
@SuppressWarnings("rawtypes") | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/AbstractHeading.java
// public abstract class AbstractHeading<E> implements IElement, IFluentElementStylable<E>{
//
// /**
// * this is actual heading1, heading2 or heading3.
// */
// private String headingType;
// private String value; //value/text for the Heading
//
// protected AbstractHeading(String headingType, String value){
// this.headingType = headingType;
// this.value = value;
// }
//
// private String template =
// "\n<w:p wsp:rsidR=\"004429ED\" wsp:rsidRDefault=\"00000000\" wsp:rsidP=\"004429ED\">"
// +"\n <w:pPr>"
// +"\n <w:pStyle w:val=\"{heading}\" />"
// +"\n {styleAlign}"
// +"\n </w:pPr>"
// +"\n <w:r>"
// +"\n {styleText}"
// +"\n <w:t>{value}</w:t>"
// +"\n </w:r>"
// +"\n</w:p>";
//
// private HeadingStyle style = new HeadingStyle();
//
// @Override
// public String getContent() {
// if("".equals(this.value)){
// return "";
// }
//
// //For convention, it should be the last thing before returning the xml content.
// String txt = style.getNewContentWithStyle(getTemplate());
//
// return txt.replace("{value}", this.value);
// }
//
//
// // #### Getters and setters ####
// public String getTemplate() {
// return this.template.replace("{heading}", this.headingType);
// }
//
// //Implements the stylable and the heading classes reuse it
// @Override
// @SuppressWarnings("unchecked")
// public E withStyle() {
// this.style.setElement(this); //, Heading1.class
// return (E) this.style;
// }
//
// }
// Path: java2word/src/test/java/word/w2004/AbstractHeadingTest.java
import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.AbstractHeading;
package word.w2004;
public class AbstractHeadingTest extends Assert{
//### TODO: I won't test the method applyStyle because I will pull this off to another class in order to reuse this for all other "stylable" class.
//anonymous implementation - this is the way I leaned how to test abstract classes.
@SuppressWarnings("rawtypes") | AbstractHeading heading1 = new AbstractHeading("Heading1", "h111") { |
leonardoanalista/java2word | java2word/src/test/java/word/w2004/AbstractHeadingTest.java | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/AbstractHeading.java
// public abstract class AbstractHeading<E> implements IElement, IFluentElementStylable<E>{
//
// /**
// * this is actual heading1, heading2 or heading3.
// */
// private String headingType;
// private String value; //value/text for the Heading
//
// protected AbstractHeading(String headingType, String value){
// this.headingType = headingType;
// this.value = value;
// }
//
// private String template =
// "\n<w:p wsp:rsidR=\"004429ED\" wsp:rsidRDefault=\"00000000\" wsp:rsidP=\"004429ED\">"
// +"\n <w:pPr>"
// +"\n <w:pStyle w:val=\"{heading}\" />"
// +"\n {styleAlign}"
// +"\n </w:pPr>"
// +"\n <w:r>"
// +"\n {styleText}"
// +"\n <w:t>{value}</w:t>"
// +"\n </w:r>"
// +"\n</w:p>";
//
// private HeadingStyle style = new HeadingStyle();
//
// @Override
// public String getContent() {
// if("".equals(this.value)){
// return "";
// }
//
// //For convention, it should be the last thing before returning the xml content.
// String txt = style.getNewContentWithStyle(getTemplate());
//
// return txt.replace("{value}", this.value);
// }
//
//
// // #### Getters and setters ####
// public String getTemplate() {
// return this.template.replace("{heading}", this.headingType);
// }
//
// //Implements the stylable and the heading classes reuse it
// @Override
// @SuppressWarnings("unchecked")
// public E withStyle() {
// this.style.setElement(this); //, Heading1.class
// return (E) this.style;
// }
//
// }
| import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.AbstractHeading; | package word.w2004;
public class AbstractHeadingTest extends Assert{
//### TODO: I won't test the method applyStyle because I will pull this off to another class in order to reuse this for all other "stylable" class.
//anonymous implementation - this is the way I leaned how to test abstract classes.
@SuppressWarnings("rawtypes")
AbstractHeading heading1 = new AbstractHeading("Heading1", "h111") {
};
@Test
public void sanityTest(){ | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/AbstractHeading.java
// public abstract class AbstractHeading<E> implements IElement, IFluentElementStylable<E>{
//
// /**
// * this is actual heading1, heading2 or heading3.
// */
// private String headingType;
// private String value; //value/text for the Heading
//
// protected AbstractHeading(String headingType, String value){
// this.headingType = headingType;
// this.value = value;
// }
//
// private String template =
// "\n<w:p wsp:rsidR=\"004429ED\" wsp:rsidRDefault=\"00000000\" wsp:rsidP=\"004429ED\">"
// +"\n <w:pPr>"
// +"\n <w:pStyle w:val=\"{heading}\" />"
// +"\n {styleAlign}"
// +"\n </w:pPr>"
// +"\n <w:r>"
// +"\n {styleText}"
// +"\n <w:t>{value}</w:t>"
// +"\n </w:r>"
// +"\n</w:p>";
//
// private HeadingStyle style = new HeadingStyle();
//
// @Override
// public String getContent() {
// if("".equals(this.value)){
// return "";
// }
//
// //For convention, it should be the last thing before returning the xml content.
// String txt = style.getNewContentWithStyle(getTemplate());
//
// return txt.replace("{value}", this.value);
// }
//
//
// // #### Getters and setters ####
// public String getTemplate() {
// return this.template.replace("{heading}", this.headingType);
// }
//
// //Implements the stylable and the heading classes reuse it
// @Override
// @SuppressWarnings("unchecked")
// public E withStyle() {
// this.style.setElement(this); //, Heading1.class
// return (E) this.style;
// }
//
// }
// Path: java2word/src/test/java/word/w2004/AbstractHeadingTest.java
import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.AbstractHeading;
package word.w2004;
public class AbstractHeadingTest extends Assert{
//### TODO: I won't test the method applyStyle because I will pull this off to another class in order to reuse this for all other "stylable" class.
//anonymous implementation - this is the way I leaned how to test abstract classes.
@SuppressWarnings("rawtypes")
AbstractHeading heading1 = new AbstractHeading("Heading1", "h111") {
};
@Test
public void sanityTest(){ | assertEquals(1, TestUtils.regexCount(heading1.getTemplate(), "<w:p wsp:rsidR*")); |
leonardoanalista/java2word | java2word/src/main/java/word/w2004/Footer2004.java | // Path: java2word/src/main/java/word/api/interfaces/IElement.java
// public interface IElement {
//
// /**
// * <p>This method returns the content (XML or HTML) of the Element and the content.</p>
// * <p>If you are using W2004, the return will be the XML required to generate the element.</p>
// *
// * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p>
// *
// * @return this is the String value of the element ready to be appended/inserted in the Document.<br>
// *
// * <p>This is the XML that generates a <code>BreakLine</code>:</p>
// * <code>
// * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/>
// * </code>
// */
// public String getContent();
//
// }
//
// Path: java2word/src/main/java/word/api/interfaces/IFooter.java
// public interface IFooter extends IHasElement{
//
// public void showPageNumber(boolean value);//default is true
//
// }
| import word.api.interfaces.IElement;
import word.api.interfaces.IFooter; | package word.w2004;
public class Footer2004 implements IFooter{
StringBuilder txt = new StringBuilder("");
private boolean hasBeenCalledBefore = false; // if getContent has already been called, I cached the result for future invocations
private boolean showPageNumber = true;
| // Path: java2word/src/main/java/word/api/interfaces/IElement.java
// public interface IElement {
//
// /**
// * <p>This method returns the content (XML or HTML) of the Element and the content.</p>
// * <p>If you are using W2004, the return will be the XML required to generate the element.</p>
// *
// * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p>
// *
// * @return this is the String value of the element ready to be appended/inserted in the Document.<br>
// *
// * <p>This is the XML that generates a <code>BreakLine</code>:</p>
// * <code>
// * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/>
// * </code>
// */
// public String getContent();
//
// }
//
// Path: java2word/src/main/java/word/api/interfaces/IFooter.java
// public interface IFooter extends IHasElement{
//
// public void showPageNumber(boolean value);//default is true
//
// }
// Path: java2word/src/main/java/word/w2004/Footer2004.java
import word.api.interfaces.IElement;
import word.api.interfaces.IFooter;
package word.w2004;
public class Footer2004 implements IFooter{
StringBuilder txt = new StringBuilder("");
private boolean hasBeenCalledBefore = false; // if getContent has already been called, I cached the result for future invocations
private boolean showPageNumber = true;
| public void addEle(IElement e) { |
leonardoanalista/java2word | java2word/src/main/java/word/utils/Utils.java | // Path: java2word/src/main/java/word/api/interfaces/IDocument.java
// public interface IDocument extends IHasElement {
//
// /**
// * @return the URI ready to be added to the document
// */
// String getUri();
//
// /**
// * @return the body of the document
// */
// IBody getBody();
//
// /**
// * @return the header that may contain other elements
// */
// IHeader getHeader();
//
// /**
// * @return the Footer that may contain other elements
// */
// IFooter getFooter();
//
// /**
// * Sets page orientation to Landscape. Default is Portrait
// */
// void setPageOrientationLandscape();
//
//
// /**
// * @param title Represents the title of the document. The title can be different than the file name. The title is used when searching for the document and also when creating Web pages from the document.
// * @return fluent @Document reference
// */
// public Document2004 title(String title);
//
// /**
// * @param subject Represents the subject of the document. This property can be used to group similar files together, so you can search for all files that have the same subject.
// * @return fluent @Document reference
// */
// public Document2004 subject(String subject);
//
// /**
// * @param keywords Represents keywords to be used when searching for the document.
// * @return fluent @Document reference
// */
// public Document2004 keywords(String keywords);
//
// /**
// * @param description Represents comments to be used when searching for the document.
// * @return fluent @Document reference
// */
// public Document2004 description(String description);
//
// /**
// * @param category Represents the author who created the document.
// * @return fluent @Document reference
// */
// public Document2004 category(String category);
//
// /**
// * @param author Represents the name of the author of the document.
// * @return fluent @Document reference
// */
// public Document2004 author(String author);
//
// /**
// * @param lastAuthor Represents the name of the author who last saved the document.
// * @return fluent @Document reference
// */
// public Document2004 lastAuthor(String lastAuthor);
//
// /**
// * @param manager Represents the manager of the author of the document. This property can be used to group similar files together, so you can search for all the files that have the same manager.
// * @return fluent @Document reference
// */
// public Document2004 manager(String manager);
//
// /**
// * @param company Represents the company that employs the author. This property can be used to group similar files together, so you can search for all files that have the same company.
// * @return fluent @Document reference
// */
// public Document2004 company(String company);
//
// /**
// * @param encoding The encoding you want to use in your document. UTF-8 or ISO8859-1, according to the Enum @Encoding
// * @return
// */
// public Document2004 encoding(Encoding encoding);
//
// /**
// * It gives a chance to set up your own encoding by passing the final string ready to go.
// * @param encoding
// * @return
// */
// public Document2004 encoding(String encoding);
//
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import word.api.interfaces.IDocument; | *
* @return String with the content of the file
*/
public static String readFile(String file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Can't find the file", e);
}
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
reader = null;
}
}
| // Path: java2word/src/main/java/word/api/interfaces/IDocument.java
// public interface IDocument extends IHasElement {
//
// /**
// * @return the URI ready to be added to the document
// */
// String getUri();
//
// /**
// * @return the body of the document
// */
// IBody getBody();
//
// /**
// * @return the header that may contain other elements
// */
// IHeader getHeader();
//
// /**
// * @return the Footer that may contain other elements
// */
// IFooter getFooter();
//
// /**
// * Sets page orientation to Landscape. Default is Portrait
// */
// void setPageOrientationLandscape();
//
//
// /**
// * @param title Represents the title of the document. The title can be different than the file name. The title is used when searching for the document and also when creating Web pages from the document.
// * @return fluent @Document reference
// */
// public Document2004 title(String title);
//
// /**
// * @param subject Represents the subject of the document. This property can be used to group similar files together, so you can search for all files that have the same subject.
// * @return fluent @Document reference
// */
// public Document2004 subject(String subject);
//
// /**
// * @param keywords Represents keywords to be used when searching for the document.
// * @return fluent @Document reference
// */
// public Document2004 keywords(String keywords);
//
// /**
// * @param description Represents comments to be used when searching for the document.
// * @return fluent @Document reference
// */
// public Document2004 description(String description);
//
// /**
// * @param category Represents the author who created the document.
// * @return fluent @Document reference
// */
// public Document2004 category(String category);
//
// /**
// * @param author Represents the name of the author of the document.
// * @return fluent @Document reference
// */
// public Document2004 author(String author);
//
// /**
// * @param lastAuthor Represents the name of the author who last saved the document.
// * @return fluent @Document reference
// */
// public Document2004 lastAuthor(String lastAuthor);
//
// /**
// * @param manager Represents the manager of the author of the document. This property can be used to group similar files together, so you can search for all the files that have the same manager.
// * @return fluent @Document reference
// */
// public Document2004 manager(String manager);
//
// /**
// * @param company Represents the company that employs the author. This property can be used to group similar files together, so you can search for all files that have the same company.
// * @return fluent @Document reference
// */
// public Document2004 company(String company);
//
// /**
// * @param encoding The encoding you want to use in your document. UTF-8 or ISO8859-1, according to the Enum @Encoding
// * @return
// */
// public Document2004 encoding(Encoding encoding);
//
// /**
// * It gives a chance to set up your own encoding by passing the final string ready to go.
// * @param encoding
// * @return
// */
// public Document2004 encoding(String encoding);
//
//
// }
// Path: java2word/src/main/java/word/utils/Utils.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import word.api.interfaces.IDocument;
*
* @return String with the content of the file
*/
public static String readFile(String file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Can't find the file", e);
}
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
reader = null;
}
}
| public static String replaceSpecialCharacters(IDocument myDoc) { |
leonardoanalista/java2word | java2word/src/test/java/word/w2004/PageBreakTest.java | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/PageBreak.java
// public class PageBreak implements IElement{
//
// public String getContent() {
// return "\n<w:br w:type=\"page\" />";
// }
//
// /**
// * This is a different fluent way.
// * Because there is no create "with", we will have to create a static method to return an instance of the pageBreak.
// * * Notice that this class doesn't implement IFluentInterface.
// *
// * */
// public static PageBreak create() {
// return new PageBreak();
// }
//
// }
| import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.PageBreak; | package word.w2004;
public class PageBreakTest extends Assert{
@Test
public void testPageBreak(){ | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/PageBreak.java
// public class PageBreak implements IElement{
//
// public String getContent() {
// return "\n<w:br w:type=\"page\" />";
// }
//
// /**
// * This is a different fluent way.
// * Because there is no create "with", we will have to create a static method to return an instance of the pageBreak.
// * * Notice that this class doesn't implement IFluentInterface.
// *
// * */
// public static PageBreak create() {
// return new PageBreak();
// }
//
// }
// Path: java2word/src/test/java/word/w2004/PageBreakTest.java
import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.PageBreak;
package word.w2004;
public class PageBreakTest extends Assert{
@Test
public void testPageBreak(){ | PageBreak pb = new PageBreak(); |
leonardoanalista/java2word | java2word/src/test/java/word/w2004/PageBreakTest.java | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/PageBreak.java
// public class PageBreak implements IElement{
//
// public String getContent() {
// return "\n<w:br w:type=\"page\" />";
// }
//
// /**
// * This is a different fluent way.
// * Because there is no create "with", we will have to create a static method to return an instance of the pageBreak.
// * * Notice that this class doesn't implement IFluentInterface.
// *
// * */
// public static PageBreak create() {
// return new PageBreak();
// }
//
// }
| import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.PageBreak; | package word.w2004;
public class PageBreakTest extends Assert{
@Test
public void testPageBreak(){
PageBreak pb = new PageBreak(); | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
//
// Path: java2word/src/main/java/word/w2004/elements/PageBreak.java
// public class PageBreak implements IElement{
//
// public String getContent() {
// return "\n<w:br w:type=\"page\" />";
// }
//
// /**
// * This is a different fluent way.
// * Because there is no create "with", we will have to create a static method to return an instance of the pageBreak.
// * * Notice that this class doesn't implement IFluentInterface.
// *
// * */
// public static PageBreak create() {
// return new PageBreak();
// }
//
// }
// Path: java2word/src/test/java/word/w2004/PageBreakTest.java
import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
import word.w2004.elements.PageBreak;
package word.w2004;
public class PageBreakTest extends Assert{
@Test
public void testPageBreak(){
PageBreak pb = new PageBreak(); | assertEquals(1, TestUtils.regexCount(pb.getContent(), "<w:br w:type=\"page\" />")); |
leonardoanalista/java2word | java2word/src/test/java/word/TestUtilsTest.java | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
| import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils; | package word;
public class TestUtilsTest extends Assert{
@Test
public void testRegex(){ | // Path: java2word/src/main/java/word/utils/TestUtils.java
// public class TestUtils {
//
// public static int regexCount(String text, String regex){
// if(text == null || regex == null){
// throw new IllegalArgumentException("Can't be null.");
// }
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(text);
//
// int total = 0;
// while (matcher.find()) {
// total ++;
// }
//
// return total;
// }
//
// public static void createLocalDoc(String myDoc) {
// createLocalDocument(myDoc, "Java2word_allInOne.doc");
// }
//
// public static void createLocalDoc(String myDoc, String fileName) {
// if("".equals(fileName) || fileName == null) {
// fileName = "Java2word_allInOne.doc";
// }
// createLocalDocument(myDoc, fileName);
// }
//
// public static void createLocalDocument(String myDoc, String fileName) {
// //Property prop = new Property("");
// Properties prop = new Properties();
// String tmpDocs = "";
// try {
// prop.load(new FileInputStream("build.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// tmpDocs = (String) prop.get("tmp.docs.dir");
//
// //System.out.println(tmpDocs);
// //"/home/leonardo/Desktop/Java2word_allInOne.doc"
//
// File fileObj = new File(tmpDocs + "/" + fileName);
//
// PrintWriter writer = null;
// try {
// writer = new PrintWriter(fileObj);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// String myWord = myDoc;
//
// writer.println(myWord);
// writer.close();
// }
//
// }
// Path: java2word/src/test/java/word/TestUtilsTest.java
import junit.framework.Assert;
import org.junit.Test;
import word.utils.TestUtils;
package word;
public class TestUtilsTest extends Assert{
@Test
public void testRegex(){ | assertNotNull(new TestUtils()); |
leonardoanalista/java2word | j2w-webtest/src/test/java/java2word/TestingTest.java | // Path: j2w-webtest/src/main/java/java2word/actions/Testing.java
// public class Testing extends ActionSupport implements ServletResponseAware, ServletRequestAware {
//
// @Override
// public String execute() throws Exception {
// // System.out.println("### About to generate Word doc...");
//
// // System.out.println("XML is: \n" + this.xml + "\n");
// //###LEO
//
// request.setAttribute("res", "@@@ " + new Date());
// request.getSession().setAttribute("xml", xml);
//
// //'UTF-8', 'ISO-8859-1' or nothing? up to you...
// if (!StringUtils.isEmpty(xml)) {
// response.setContentType("application/msword; charset=UTF-8");
// response.setHeader("Content-disposition",
// "inline;filename=wordDoc.doc");
//
// PrintWriter writer = response.getWriter();
// writer.println(xml);
// writer.flush();
// // System.out.println("### Doc generated...");
// return null;
// }else{
// System.out.println("Error: Empty XML field porra!!!" );
// }
//
//
// return SUCCESS;
// }
//
// // ### Getters and setters
// private String xml;
// private HttpServletResponse response;
// private HttpServletRequest request;
//
// public String getXml() {
// return xml;
// }
//
// public void setXml(String xml) {
// this.xml = xml;
// }
//
// //@Override
// public void setServletResponse(HttpServletResponse servletResponse) {
// response = servletResponse;
// }
//
// public void setServletRequest(HttpServletRequest servletRequest) {
// request = servletRequest;
// }
//
//
//
// }
| import java2word.actions.Testing;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.junit.Test;
import com.opensymphony.xwork2.ActionProxy;
import static com.opensymphony.xwork2.ActionSupport.*; | package java2word;
public class TestingTest extends StrutsTestCase{
@Test
public void testSanity() throws Exception{
//pre requirements
request.setParameter("xml", "this is the xml");
//kinda of replay()
ActionProxy proxy = getActionProxy("/testing"); | // Path: j2w-webtest/src/main/java/java2word/actions/Testing.java
// public class Testing extends ActionSupport implements ServletResponseAware, ServletRequestAware {
//
// @Override
// public String execute() throws Exception {
// // System.out.println("### About to generate Word doc...");
//
// // System.out.println("XML is: \n" + this.xml + "\n");
// //###LEO
//
// request.setAttribute("res", "@@@ " + new Date());
// request.getSession().setAttribute("xml", xml);
//
// //'UTF-8', 'ISO-8859-1' or nothing? up to you...
// if (!StringUtils.isEmpty(xml)) {
// response.setContentType("application/msword; charset=UTF-8");
// response.setHeader("Content-disposition",
// "inline;filename=wordDoc.doc");
//
// PrintWriter writer = response.getWriter();
// writer.println(xml);
// writer.flush();
// // System.out.println("### Doc generated...");
// return null;
// }else{
// System.out.println("Error: Empty XML field porra!!!" );
// }
//
//
// return SUCCESS;
// }
//
// // ### Getters and setters
// private String xml;
// private HttpServletResponse response;
// private HttpServletRequest request;
//
// public String getXml() {
// return xml;
// }
//
// public void setXml(String xml) {
// this.xml = xml;
// }
//
// //@Override
// public void setServletResponse(HttpServletResponse servletResponse) {
// response = servletResponse;
// }
//
// public void setServletRequest(HttpServletRequest servletRequest) {
// request = servletRequest;
// }
//
//
//
// }
// Path: j2w-webtest/src/test/java/java2word/TestingTest.java
import java2word.actions.Testing;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.junit.Test;
import com.opensymphony.xwork2.ActionProxy;
import static com.opensymphony.xwork2.ActionSupport.*;
package java2word;
public class TestingTest extends StrutsTestCase{
@Test
public void testSanity() throws Exception{
//pre requirements
request.setParameter("xml", "this is the xml");
//kinda of replay()
ActionProxy proxy = getActionProxy("/testing"); | Testing testingAction = (Testing) proxy.getAction(); |
leonardoanalista/java2word | java2word/src/main/java/word/w2004/elements/AbstractHeading.java | // Path: java2word/src/main/java/word/api/interfaces/IElement.java
// public interface IElement {
//
// /**
// * <p>This method returns the content (XML or HTML) of the Element and the content.</p>
// * <p>If you are using W2004, the return will be the XML required to generate the element.</p>
// *
// * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p>
// *
// * @return this is the String value of the element ready to be appended/inserted in the Document.<br>
// *
// * <p>This is the XML that generates a <code>BreakLine</code>:</p>
// * <code>
// * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/>
// * </code>
// */
// public String getContent();
//
// }
//
// Path: java2word/src/main/java/word/api/interfaces/IFluentElementStylable.java
// public interface IFluentElementStylable <S>{
//
// /**
// * This method returns style for the element. The element knows who is his style class, but the style doesn't.
// * This method will do this:
// * 1) set up the itself to the style class
// * this.getStyle().setElement(this); //, Heading1.class
// * 2) Return the style class
// * return this.getStyle();
// *
// */
// public S withStyle();
//
// }
//
// Path: java2word/src/main/java/word/w2004/style/HeadingStyle.java
// public class HeadingStyle extends AbstractStyle implements ISuperStylin{
//
// /**
// * Default align is left
// */
// private Align align = Align.LEFT;
// private boolean bold = false;
// private boolean italic = false;
//
// //we could abstract this or not... if we want to apply style to one word inside a the Heading, you can NOT apply align JUSTIFIED, for example.
// //For this reason I will leave this here for instance...
// public enum Align {
// CENTER("center"), LEFT("left"), RIGHT("right"), JUSTIFIED("both");
//
// private String value;
//
// Align(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
//
// //This method holds the logic to replace all place holders for styling.
// //I also noticed if you don't replace the place holder, it doesn't cause any error!
// //But we should try to replace in order to keep the result xml clean.
// @Override
// public String getNewContentWithStyle(String txt) {
// String alignValue = "\n <w:jc w:val=\"" + align.getValue()+ "\" />";
// txt = txt.replace("{styleAlign}", alignValue);
//
// StringBuilder sbText = new StringBuilder("");
//
// applyBoldAndItalic(sbText);
//
// if(!"".equals(sbText.toString())) {
// sbText.insert(0, "\n <w:rPr>");
// sbText.append("\n </w:rPr>");
// }
//
// txt = txt.replace("{styleText}", sbText.toString());//Convention: apply styles
// txt = txt.replaceAll("[{]style(.*)[}]", ""); //Convention: remove unused styles after...
//
// return txt;
// }
//
//
// private void applyBoldAndItalic(StringBuilder sbText) {
// if(bold) {
// sbText.append("\n <w:b/><w:b-cs/>");
// }
// if(italic) {
// sbText.append("\n <w:i/>");
// }
// }
//
//
// //### Getters setters... ###
//
// /**
// * Heading alignment
// * @param align
// * @return fluent @HeadingStyle
// */
// public HeadingStyle align(Align align) {
// this.align = align;
// return this;
// }
//
// /**
// * Set Heading font to bold
// * @return fluent @HeadingStyle
// */
// public HeadingStyle bold() {
// bold = true;
// return this;
// }
//
// /**
// * Set Heading font to italic
// * @return fluent @HeadingStyle
// */
// public HeadingStyle italic() {
// italic = true;
// return this;
// }
//
//
// }
| import word.api.interfaces.IElement;
import word.api.interfaces.IFluentElementStylable;
import word.w2004.style.HeadingStyle; | package word.w2004.elements;
/**
* @author leonardo
* @param <E>
* Heading is utilized to organize documents the same way you do for web pages.
* You can use Heading1 to 3.
*/
public abstract class AbstractHeading<E> implements IElement, IFluentElementStylable<E>{
/**
* this is actual heading1, heading2 or heading3.
*/
private String headingType;
private String value; //value/text for the Heading
protected AbstractHeading(String headingType, String value){
this.headingType = headingType;
this.value = value;
}
private String template =
"\n<w:p wsp:rsidR=\"004429ED\" wsp:rsidRDefault=\"00000000\" wsp:rsidP=\"004429ED\">"
+"\n <w:pPr>"
+"\n <w:pStyle w:val=\"{heading}\" />"
+"\n {styleAlign}"
+"\n </w:pPr>"
+"\n <w:r>"
+"\n {styleText}"
+"\n <w:t>{value}</w:t>"
+"\n </w:r>"
+"\n</w:p>";
| // Path: java2word/src/main/java/word/api/interfaces/IElement.java
// public interface IElement {
//
// /**
// * <p>This method returns the content (XML or HTML) of the Element and the content.</p>
// * <p>If you are using W2004, the return will be the XML required to generate the element.</p>
// *
// * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p>
// *
// * @return this is the String value of the element ready to be appended/inserted in the Document.<br>
// *
// * <p>This is the XML that generates a <code>BreakLine</code>:</p>
// * <code>
// * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/>
// * </code>
// */
// public String getContent();
//
// }
//
// Path: java2word/src/main/java/word/api/interfaces/IFluentElementStylable.java
// public interface IFluentElementStylable <S>{
//
// /**
// * This method returns style for the element. The element knows who is his style class, but the style doesn't.
// * This method will do this:
// * 1) set up the itself to the style class
// * this.getStyle().setElement(this); //, Heading1.class
// * 2) Return the style class
// * return this.getStyle();
// *
// */
// public S withStyle();
//
// }
//
// Path: java2word/src/main/java/word/w2004/style/HeadingStyle.java
// public class HeadingStyle extends AbstractStyle implements ISuperStylin{
//
// /**
// * Default align is left
// */
// private Align align = Align.LEFT;
// private boolean bold = false;
// private boolean italic = false;
//
// //we could abstract this or not... if we want to apply style to one word inside a the Heading, you can NOT apply align JUSTIFIED, for example.
// //For this reason I will leave this here for instance...
// public enum Align {
// CENTER("center"), LEFT("left"), RIGHT("right"), JUSTIFIED("both");
//
// private String value;
//
// Align(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
//
// //This method holds the logic to replace all place holders for styling.
// //I also noticed if you don't replace the place holder, it doesn't cause any error!
// //But we should try to replace in order to keep the result xml clean.
// @Override
// public String getNewContentWithStyle(String txt) {
// String alignValue = "\n <w:jc w:val=\"" + align.getValue()+ "\" />";
// txt = txt.replace("{styleAlign}", alignValue);
//
// StringBuilder sbText = new StringBuilder("");
//
// applyBoldAndItalic(sbText);
//
// if(!"".equals(sbText.toString())) {
// sbText.insert(0, "\n <w:rPr>");
// sbText.append("\n </w:rPr>");
// }
//
// txt = txt.replace("{styleText}", sbText.toString());//Convention: apply styles
// txt = txt.replaceAll("[{]style(.*)[}]", ""); //Convention: remove unused styles after...
//
// return txt;
// }
//
//
// private void applyBoldAndItalic(StringBuilder sbText) {
// if(bold) {
// sbText.append("\n <w:b/><w:b-cs/>");
// }
// if(italic) {
// sbText.append("\n <w:i/>");
// }
// }
//
//
// //### Getters setters... ###
//
// /**
// * Heading alignment
// * @param align
// * @return fluent @HeadingStyle
// */
// public HeadingStyle align(Align align) {
// this.align = align;
// return this;
// }
//
// /**
// * Set Heading font to bold
// * @return fluent @HeadingStyle
// */
// public HeadingStyle bold() {
// bold = true;
// return this;
// }
//
// /**
// * Set Heading font to italic
// * @return fluent @HeadingStyle
// */
// public HeadingStyle italic() {
// italic = true;
// return this;
// }
//
//
// }
// Path: java2word/src/main/java/word/w2004/elements/AbstractHeading.java
import word.api.interfaces.IElement;
import word.api.interfaces.IFluentElementStylable;
import word.w2004.style.HeadingStyle;
package word.w2004.elements;
/**
* @author leonardo
* @param <E>
* Heading is utilized to organize documents the same way you do for web pages.
* You can use Heading1 to 3.
*/
public abstract class AbstractHeading<E> implements IElement, IFluentElementStylable<E>{
/**
* this is actual heading1, heading2 or heading3.
*/
private String headingType;
private String value; //value/text for the Heading
protected AbstractHeading(String headingType, String value){
this.headingType = headingType;
this.value = value;
}
private String template =
"\n<w:p wsp:rsidR=\"004429ED\" wsp:rsidRDefault=\"00000000\" wsp:rsidP=\"004429ED\">"
+"\n <w:pPr>"
+"\n <w:pStyle w:val=\"{heading}\" />"
+"\n {styleAlign}"
+"\n </w:pPr>"
+"\n <w:r>"
+"\n {styleText}"
+"\n <w:t>{value}</w:t>"
+"\n </w:r>"
+"\n</w:p>";
| private HeadingStyle style = new HeadingStyle(); |
makubi/avrohugger-maven-plugin | src/test/java/at/makubi/maven/plugin/avrohugger/GeneratorMojoTest.java | // Path: src/test/java/at/makubi/maven/plugin/avrohugger/TestHelper.java
// public static void failTestIfFilesDiffer(Path expectedFile, Path actualFile) throws IOException {
// String fileDiff = TestHelper.fileDiff(expectedFile.toFile(), actualFile.toFile());
// if (!fileDiff.isEmpty()) {
// fail("Expected file " + expectedFile + " and actual file " + actualFile + " differ. See output below." + System.lineSeparator() + fileDiff);
// }
// }
| import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import static at.makubi.maven.plugin.avrohugger.TestHelper.failTestIfFilesDiffer; | /*
* Copyright 2016 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 at.makubi.maven.plugin.avrohugger;
public class GeneratorMojoTest extends AbstractHarnessMojoTestCase {
final Path testResourcesDir = Paths.get("src/test/resources/unit/avrohugger-maven-plugin/mojo");
// ${basedir}
final Path testRunnerBaseDir = Paths.get("target/test-harness/avrohugger-maven-plugin");
// ${project.build.directory}
final Path testRunnerProjectBuildDir = testRunnerBaseDir.resolve("target");
@Before
public void setUp() throws Exception {
super.setUp();
FileUtils.deleteDirectory(testRunnerBaseDir.toFile());
createDir(testRunnerBaseDir);
}
public void testGenerateScalaSourcesWithDefaultSettings() throws Exception {
final Path defaultTestResourcesDir = testResourcesDir.resolve("default");
final Path testAvroSourceDir = testRunnerBaseDir.resolve(Defaults.relativeSourceDirectory);
final Path testAvroSourceSubDir = testAvroSourceDir.resolve("subdir");
final Path apiAvdl = Paths.get("Api.avdl");
final Path subApiAvdl = Paths.get("SubApi.avdl");
final Path recordWith25FieldsAvdl = Paths.get("RecordWith25Fields.avdl");
final String testPomName = "pom-defaults.xml";
createDir(testAvroSourceDir);
createDir(testAvroSourceSubDir);
// Copy pom
Path srcPom = defaultTestResourcesDir.resolve(testPomName);
Path pomPath = testRunnerBaseDir.resolve(testPomName);
Files.copy(srcPom, pomPath, StandardCopyOption.REPLACE_EXISTING);
// Copy AVDL files
Files.copy(testResourcesDir.resolve(apiAvdl), testAvroSourceDir.resolve(apiAvdl), StandardCopyOption.REPLACE_EXISTING);
Files.copy(testResourcesDir.resolve(subApiAvdl), testAvroSourceSubDir.resolve(subApiAvdl), StandardCopyOption.REPLACE_EXISTING);
Files.copy(testResourcesDir.resolve(recordWith25FieldsAvdl), testAvroSourceDir.resolve(recordWith25FieldsAvdl), StandardCopyOption.REPLACE_EXISTING);
GeneratorMojo generatorMojo = (GeneratorMojo) lookupMojo(pomPath, "generate-scala-sources");
generatorMojo.execute();
// Test 'sourceDirectory', 'outputDirectory' and 'sourceGenerationFormat' | // Path: src/test/java/at/makubi/maven/plugin/avrohugger/TestHelper.java
// public static void failTestIfFilesDiffer(Path expectedFile, Path actualFile) throws IOException {
// String fileDiff = TestHelper.fileDiff(expectedFile.toFile(), actualFile.toFile());
// if (!fileDiff.isEmpty()) {
// fail("Expected file " + expectedFile + " and actual file " + actualFile + " differ. See output below." + System.lineSeparator() + fileDiff);
// }
// }
// Path: src/test/java/at/makubi/maven/plugin/avrohugger/GeneratorMojoTest.java
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import static at.makubi.maven.plugin.avrohugger.TestHelper.failTestIfFilesDiffer;
/*
* Copyright 2016 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 at.makubi.maven.plugin.avrohugger;
public class GeneratorMojoTest extends AbstractHarnessMojoTestCase {
final Path testResourcesDir = Paths.get("src/test/resources/unit/avrohugger-maven-plugin/mojo");
// ${basedir}
final Path testRunnerBaseDir = Paths.get("target/test-harness/avrohugger-maven-plugin");
// ${project.build.directory}
final Path testRunnerProjectBuildDir = testRunnerBaseDir.resolve("target");
@Before
public void setUp() throws Exception {
super.setUp();
FileUtils.deleteDirectory(testRunnerBaseDir.toFile());
createDir(testRunnerBaseDir);
}
public void testGenerateScalaSourcesWithDefaultSettings() throws Exception {
final Path defaultTestResourcesDir = testResourcesDir.resolve("default");
final Path testAvroSourceDir = testRunnerBaseDir.resolve(Defaults.relativeSourceDirectory);
final Path testAvroSourceSubDir = testAvroSourceDir.resolve("subdir");
final Path apiAvdl = Paths.get("Api.avdl");
final Path subApiAvdl = Paths.get("SubApi.avdl");
final Path recordWith25FieldsAvdl = Paths.get("RecordWith25Fields.avdl");
final String testPomName = "pom-defaults.xml";
createDir(testAvroSourceDir);
createDir(testAvroSourceSubDir);
// Copy pom
Path srcPom = defaultTestResourcesDir.resolve(testPomName);
Path pomPath = testRunnerBaseDir.resolve(testPomName);
Files.copy(srcPom, pomPath, StandardCopyOption.REPLACE_EXISTING);
// Copy AVDL files
Files.copy(testResourcesDir.resolve(apiAvdl), testAvroSourceDir.resolve(apiAvdl), StandardCopyOption.REPLACE_EXISTING);
Files.copy(testResourcesDir.resolve(subApiAvdl), testAvroSourceSubDir.resolve(subApiAvdl), StandardCopyOption.REPLACE_EXISTING);
Files.copy(testResourcesDir.resolve(recordWith25FieldsAvdl), testAvroSourceDir.resolve(recordWith25FieldsAvdl), StandardCopyOption.REPLACE_EXISTING);
GeneratorMojo generatorMojo = (GeneratorMojo) lookupMojo(pomPath, "generate-scala-sources");
generatorMojo.execute();
// Test 'sourceDirectory', 'outputDirectory' and 'sourceGenerationFormat' | failTestIfFilesDiffer(defaultTestResourcesDir.resolve("Record.scala"), testRunnerProjectBuildDir.resolve(Defaults.relativeOutputDirectory).resolve("at/makubi/maven/plugin/model/Record.scala")); |
makubi/avrohugger-maven-plugin | src/main/java/at/makubi/maven/plugin/avrohugger/typeoverride/TypeOverrides.java | // Path: src/main/java/at/makubi/maven/plugin/avrohugger/typeoverride/logical/AvroScalaTimestampMillisType.java
// public enum AvroScalaTimestampMillisType {
//
// JAVA_TIME_INSTANT(JavaTimeInstant$.MODULE$),
// JAVA_SQL_TIMESTAMP(JavaSqlTimestamp$.MODULE$);
//
// public final avrohugger.types.AvroScalaTimestampMillisType avrohuggerScalaTimestampMillisType;
//
// AvroScalaTimestampMillisType(avrohugger.types.AvroScalaTimestampMillisType avrohuggerScalaTimestampMillisType) {
// this.avrohuggerScalaTimestampMillisType = avrohuggerScalaTimestampMillisType;
// }
// }
| import at.makubi.maven.plugin.avrohugger.typeoverride.complex.*;
import at.makubi.maven.plugin.avrohugger.typeoverride.logical.AvroScalaTimestampMillisType;
import at.makubi.maven.plugin.avrohugger.typeoverride.primitive.*; | package at.makubi.maven.plugin.avrohugger.typeoverride;
public class TypeOverrides {
private avrohugger.types.AvroScalaArrayType arrayType;
private avrohugger.types.AvroScalaEnumType enumType;
private avrohugger.types.AvroScalaFixedType fixedType;
private avrohugger.types.AvroScalaMapType mapType;
private avrohugger.types.AvroScalaProtocolType protocolType;
private avrohugger.types.AvroScalaRecordType recordType;
private avrohugger.types.AvroScalaUnionType unionType;
private avrohugger.types.AvroScalaBooleanType booleanType;
private avrohugger.types.AvroScalaBytesType bytesType;
private avrohugger.types.AvroScalaNumberType doubleType;
private avrohugger.types.AvroScalaNumberType floatType;
private avrohugger.types.AvroScalaNumberType intType;
private avrohugger.types.AvroScalaNumberType longType;
private avrohugger.types.AvroScalaNullType nullType;
private avrohugger.types.AvroScalaStringType stringType; | // Path: src/main/java/at/makubi/maven/plugin/avrohugger/typeoverride/logical/AvroScalaTimestampMillisType.java
// public enum AvroScalaTimestampMillisType {
//
// JAVA_TIME_INSTANT(JavaTimeInstant$.MODULE$),
// JAVA_SQL_TIMESTAMP(JavaSqlTimestamp$.MODULE$);
//
// public final avrohugger.types.AvroScalaTimestampMillisType avrohuggerScalaTimestampMillisType;
//
// AvroScalaTimestampMillisType(avrohugger.types.AvroScalaTimestampMillisType avrohuggerScalaTimestampMillisType) {
// this.avrohuggerScalaTimestampMillisType = avrohuggerScalaTimestampMillisType;
// }
// }
// Path: src/main/java/at/makubi/maven/plugin/avrohugger/typeoverride/TypeOverrides.java
import at.makubi.maven.plugin.avrohugger.typeoverride.complex.*;
import at.makubi.maven.plugin.avrohugger.typeoverride.logical.AvroScalaTimestampMillisType;
import at.makubi.maven.plugin.avrohugger.typeoverride.primitive.*;
package at.makubi.maven.plugin.avrohugger.typeoverride;
public class TypeOverrides {
private avrohugger.types.AvroScalaArrayType arrayType;
private avrohugger.types.AvroScalaEnumType enumType;
private avrohugger.types.AvroScalaFixedType fixedType;
private avrohugger.types.AvroScalaMapType mapType;
private avrohugger.types.AvroScalaProtocolType protocolType;
private avrohugger.types.AvroScalaRecordType recordType;
private avrohugger.types.AvroScalaUnionType unionType;
private avrohugger.types.AvroScalaBooleanType booleanType;
private avrohugger.types.AvroScalaBytesType bytesType;
private avrohugger.types.AvroScalaNumberType doubleType;
private avrohugger.types.AvroScalaNumberType floatType;
private avrohugger.types.AvroScalaNumberType intType;
private avrohugger.types.AvroScalaNumberType longType;
private avrohugger.types.AvroScalaNullType nullType;
private avrohugger.types.AvroScalaStringType stringType; | private avrohugger.types.AvroScalaTimestampMillisType timestampMillisType; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/DefaultKeyResolution.java | // Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
| import org.wildfly.metrics.scheduler.polling.Task; | package org.wildfly.metrics.scheduler.storage;
/**
* Resolve data input attributes to final metric (storage) names.
*
* @author Heiko Braun
* @since 24/10/14
*/
public class DefaultKeyResolution implements KeyResolution {
@Override | // Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DefaultKeyResolution.java
import org.wildfly.metrics.scheduler.polling.Task;
package org.wildfly.metrics.scheduler.storage;
/**
* Resolve data input attributes to final metric (storage) names.
*
* @author Heiko Braun
* @since 24/10/14
*/
public class DefaultKeyResolution implements KeyResolution {
@Override | public String resolve(Task task) { |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/BufferedStorageDispatcher.java | // Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Scheduler.java
// public interface Scheduler {
//
// public enum State {RUNNING, STOPPED}
//
// void schedule(List<Task> operations, CompletionHandler completionHandler);
//
// void shutdown();
//
// /**
// * Callback for completed tasks
// */
// interface CompletionHandler {
// void onCompleted(DataPoint sample);
// void onFailed(Throwable e);
// }
// }
| import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Scheduler;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; | package org.wildfly.metrics.scheduler.storage;
/**
* @author Heiko Braun
* @since 13/10/14
*/
public class BufferedStorageDispatcher implements Scheduler.CompletionHandler {
private static final int MAX_BATCH_SIZE = 24;
private static final int BUFFER_SIZE = 100;
private final StorageAdapter storageAdapter; | // Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Scheduler.java
// public interface Scheduler {
//
// public enum State {RUNNING, STOPPED}
//
// void schedule(List<Task> operations, CompletionHandler completionHandler);
//
// void shutdown();
//
// /**
// * Callback for completed tasks
// */
// interface CompletionHandler {
// void onCompleted(DataPoint sample);
// void onFailed(Throwable e);
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/BufferedStorageDispatcher.java
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Scheduler;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
package org.wildfly.metrics.scheduler.storage;
/**
* @author Heiko Braun
* @since 13/10/14
*/
public class BufferedStorageDispatcher implements Scheduler.CompletionHandler {
private static final int MAX_BATCH_SIZE = 24;
private static final int BUFFER_SIZE = 100;
private final StorageAdapter storageAdapter; | private final Diagnostics diagnostics; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/Task.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Address.java
// public class Address implements Iterable<Address.Tuple> {
//
// public static Address apply(String address) {
// List<String> tokens = address == null ? Collections.<String>emptyList() :
// Splitter.on(CharMatcher.anyOf("/="))
// .trimResults()
// .omitEmptyStrings()
// .splitToList(address);
//
// List<Tuple> tuples = new ArrayList<>(tokens.size() / 2 + 1);
// for (Iterator<String> iterator = tokens.iterator(); iterator.hasNext(); ) {
// String type = iterator.next();
// String name = iterator.hasNext() ? iterator.next() : "";
// tuples.add(new Tuple(type, name));
// }
//
// return new Address(tuples);
// }
//
//
// private final List<Tuple> tuples;
//
// private Address(final List<Tuple> tuples) {
// this.tuples = new ArrayList<>();
// if (tuples != null) {
// this.tuples.addAll(tuples);
// }
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Address)) { return false; }
//
// Address address = (Address) o;
//
// if (!tuples.equals(address.tuples)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return tuples.hashCode();
// }
//
// @Override
// public String toString() {
// return Joiner.on('/').join(tuples);
// }
//
// @Override
// public Iterator<Tuple> iterator() {
// return Iterators.unmodifiableIterator(tuples.iterator());
// }
//
// public boolean isEmpty() {return tuples.isEmpty();}
//
// public boolean isBalanced() {
// for (Tuple tuple : this) {
// if (tuple.getValue() == null || tuple.getValue().length() == 0) {
// return false;
// }
// }
// return true;
// }
//
// public boolean startsWith(Tuple tuple) {
// return !tuples.isEmpty() && tuples.get(0).equals(tuple);
// }
//
//
// /**
// * @author Harald Pehl
// */
// public static class Tuple {
//
// public static Tuple apply(String tuple) {
// if (tuple == null) {
// throw new IllegalArgumentException("Tuple must not be null");
// }
// List<String> tuples = Splitter.on('=')
// .omitEmptyStrings()
// .trimResults()
// .splitToList(tuple);
// if (tuples.isEmpty() || tuples.size() != 2) {
// throw new IllegalArgumentException("Malformed tuple: " + tuple);
// }
// return new Tuple(tuples.get(0), tuples.get(1));
// }
//
// private final String key;
// private final String value;
//
// private Tuple(final String key, final String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Tuple)) { return false; }
//
// Tuple that = (Tuple) o;
//
// if (!value.equals(that.value)) { return false; }
// if (!key.equals(that.key)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key.hashCode();
// result = 31 * result + value.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return key + "=" + value;
// }
//
// public String getKey() {
// return key;
// }
//
// public String getValue() {
// return value;
// }
// }
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
| import org.wildfly.metrics.scheduler.config.Address;
import org.wildfly.metrics.scheduler.config.Interval; | package org.wildfly.metrics.scheduler.polling;
/**
* Represents a monitoring task. Represents and absolute address within a domain.
*
* @author Heiko Braun
* @since 10/10/14
*/
public class Task {
private final String host;
private final String server; | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Address.java
// public class Address implements Iterable<Address.Tuple> {
//
// public static Address apply(String address) {
// List<String> tokens = address == null ? Collections.<String>emptyList() :
// Splitter.on(CharMatcher.anyOf("/="))
// .trimResults()
// .omitEmptyStrings()
// .splitToList(address);
//
// List<Tuple> tuples = new ArrayList<>(tokens.size() / 2 + 1);
// for (Iterator<String> iterator = tokens.iterator(); iterator.hasNext(); ) {
// String type = iterator.next();
// String name = iterator.hasNext() ? iterator.next() : "";
// tuples.add(new Tuple(type, name));
// }
//
// return new Address(tuples);
// }
//
//
// private final List<Tuple> tuples;
//
// private Address(final List<Tuple> tuples) {
// this.tuples = new ArrayList<>();
// if (tuples != null) {
// this.tuples.addAll(tuples);
// }
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Address)) { return false; }
//
// Address address = (Address) o;
//
// if (!tuples.equals(address.tuples)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return tuples.hashCode();
// }
//
// @Override
// public String toString() {
// return Joiner.on('/').join(tuples);
// }
//
// @Override
// public Iterator<Tuple> iterator() {
// return Iterators.unmodifiableIterator(tuples.iterator());
// }
//
// public boolean isEmpty() {return tuples.isEmpty();}
//
// public boolean isBalanced() {
// for (Tuple tuple : this) {
// if (tuple.getValue() == null || tuple.getValue().length() == 0) {
// return false;
// }
// }
// return true;
// }
//
// public boolean startsWith(Tuple tuple) {
// return !tuples.isEmpty() && tuples.get(0).equals(tuple);
// }
//
//
// /**
// * @author Harald Pehl
// */
// public static class Tuple {
//
// public static Tuple apply(String tuple) {
// if (tuple == null) {
// throw new IllegalArgumentException("Tuple must not be null");
// }
// List<String> tuples = Splitter.on('=')
// .omitEmptyStrings()
// .trimResults()
// .splitToList(tuple);
// if (tuples.isEmpty() || tuples.size() != 2) {
// throw new IllegalArgumentException("Malformed tuple: " + tuple);
// }
// return new Tuple(tuples.get(0), tuples.get(1));
// }
//
// private final String key;
// private final String value;
//
// private Tuple(final String key, final String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Tuple)) { return false; }
//
// Tuple that = (Tuple) o;
//
// if (!value.equals(that.value)) { return false; }
// if (!key.equals(that.key)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key.hashCode();
// result = 31 * result + value.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return key + "=" + value;
// }
//
// public String getKey() {
// return key;
// }
//
// public String getValue() {
// return value;
// }
// }
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
import org.wildfly.metrics.scheduler.config.Address;
import org.wildfly.metrics.scheduler.config.Interval;
package org.wildfly.metrics.scheduler.polling;
/**
* Represents a monitoring task. Represents and absolute address within a domain.
*
* @author Heiko Braun
* @since 10/10/14
*/
public class Task {
private final String host;
private final String server; | private final Address address; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/Task.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Address.java
// public class Address implements Iterable<Address.Tuple> {
//
// public static Address apply(String address) {
// List<String> tokens = address == null ? Collections.<String>emptyList() :
// Splitter.on(CharMatcher.anyOf("/="))
// .trimResults()
// .omitEmptyStrings()
// .splitToList(address);
//
// List<Tuple> tuples = new ArrayList<>(tokens.size() / 2 + 1);
// for (Iterator<String> iterator = tokens.iterator(); iterator.hasNext(); ) {
// String type = iterator.next();
// String name = iterator.hasNext() ? iterator.next() : "";
// tuples.add(new Tuple(type, name));
// }
//
// return new Address(tuples);
// }
//
//
// private final List<Tuple> tuples;
//
// private Address(final List<Tuple> tuples) {
// this.tuples = new ArrayList<>();
// if (tuples != null) {
// this.tuples.addAll(tuples);
// }
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Address)) { return false; }
//
// Address address = (Address) o;
//
// if (!tuples.equals(address.tuples)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return tuples.hashCode();
// }
//
// @Override
// public String toString() {
// return Joiner.on('/').join(tuples);
// }
//
// @Override
// public Iterator<Tuple> iterator() {
// return Iterators.unmodifiableIterator(tuples.iterator());
// }
//
// public boolean isEmpty() {return tuples.isEmpty();}
//
// public boolean isBalanced() {
// for (Tuple tuple : this) {
// if (tuple.getValue() == null || tuple.getValue().length() == 0) {
// return false;
// }
// }
// return true;
// }
//
// public boolean startsWith(Tuple tuple) {
// return !tuples.isEmpty() && tuples.get(0).equals(tuple);
// }
//
//
// /**
// * @author Harald Pehl
// */
// public static class Tuple {
//
// public static Tuple apply(String tuple) {
// if (tuple == null) {
// throw new IllegalArgumentException("Tuple must not be null");
// }
// List<String> tuples = Splitter.on('=')
// .omitEmptyStrings()
// .trimResults()
// .splitToList(tuple);
// if (tuples.isEmpty() || tuples.size() != 2) {
// throw new IllegalArgumentException("Malformed tuple: " + tuple);
// }
// return new Tuple(tuples.get(0), tuples.get(1));
// }
//
// private final String key;
// private final String value;
//
// private Tuple(final String key, final String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Tuple)) { return false; }
//
// Tuple that = (Tuple) o;
//
// if (!value.equals(that.value)) { return false; }
// if (!key.equals(that.key)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key.hashCode();
// result = 31 * result + value.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return key + "=" + value;
// }
//
// public String getKey() {
// return key;
// }
//
// public String getValue() {
// return value;
// }
// }
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
| import org.wildfly.metrics.scheduler.config.Address;
import org.wildfly.metrics.scheduler.config.Interval; | package org.wildfly.metrics.scheduler.polling;
/**
* Represents a monitoring task. Represents and absolute address within a domain.
*
* @author Heiko Braun
* @since 10/10/14
*/
public class Task {
private final String host;
private final String server;
private final Address address;
private final String attribute;
private final String subref; | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Address.java
// public class Address implements Iterable<Address.Tuple> {
//
// public static Address apply(String address) {
// List<String> tokens = address == null ? Collections.<String>emptyList() :
// Splitter.on(CharMatcher.anyOf("/="))
// .trimResults()
// .omitEmptyStrings()
// .splitToList(address);
//
// List<Tuple> tuples = new ArrayList<>(tokens.size() / 2 + 1);
// for (Iterator<String> iterator = tokens.iterator(); iterator.hasNext(); ) {
// String type = iterator.next();
// String name = iterator.hasNext() ? iterator.next() : "";
// tuples.add(new Tuple(type, name));
// }
//
// return new Address(tuples);
// }
//
//
// private final List<Tuple> tuples;
//
// private Address(final List<Tuple> tuples) {
// this.tuples = new ArrayList<>();
// if (tuples != null) {
// this.tuples.addAll(tuples);
// }
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Address)) { return false; }
//
// Address address = (Address) o;
//
// if (!tuples.equals(address.tuples)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return tuples.hashCode();
// }
//
// @Override
// public String toString() {
// return Joiner.on('/').join(tuples);
// }
//
// @Override
// public Iterator<Tuple> iterator() {
// return Iterators.unmodifiableIterator(tuples.iterator());
// }
//
// public boolean isEmpty() {return tuples.isEmpty();}
//
// public boolean isBalanced() {
// for (Tuple tuple : this) {
// if (tuple.getValue() == null || tuple.getValue().length() == 0) {
// return false;
// }
// }
// return true;
// }
//
// public boolean startsWith(Tuple tuple) {
// return !tuples.isEmpty() && tuples.get(0).equals(tuple);
// }
//
//
// /**
// * @author Harald Pehl
// */
// public static class Tuple {
//
// public static Tuple apply(String tuple) {
// if (tuple == null) {
// throw new IllegalArgumentException("Tuple must not be null");
// }
// List<String> tuples = Splitter.on('=')
// .omitEmptyStrings()
// .trimResults()
// .splitToList(tuple);
// if (tuples.isEmpty() || tuples.size() != 2) {
// throw new IllegalArgumentException("Malformed tuple: " + tuple);
// }
// return new Tuple(tuples.get(0), tuples.get(1));
// }
//
// private final String key;
// private final String value;
//
// private Tuple(final String key, final String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Tuple)) { return false; }
//
// Tuple that = (Tuple) o;
//
// if (!value.equals(that.value)) { return false; }
// if (!key.equals(that.key)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key.hashCode();
// result = 31 * result + value.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return key + "=" + value;
// }
//
// public String getKey() {
// return key;
// }
//
// public String getValue() {
// return value;
// }
// }
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
import org.wildfly.metrics.scheduler.config.Address;
import org.wildfly.metrics.scheduler.config.Interval;
package org.wildfly.metrics.scheduler.polling;
/**
* Represents a monitoring task. Represents and absolute address within a domain.
*
* @author Heiko Braun
* @since 10/10/14
*/
public class Task {
private final String host;
private final String server;
private final Address address;
private final String attribute;
private final String subref; | private final Interval interval; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/StorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
| import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import java.util.Set; | package org.wildfly.metrics.scheduler.storage;
/**
* @author Heiko Braun
* @since 10/10/14
*/
public interface StorageAdapter {
void store(Set<DataPoint> datapoints); | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/StorageAdapter.java
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import java.util.Set;
package org.wildfly.metrics.scheduler.storage;
/**
* @author Heiko Braun
* @since 10/10/14
*/
public interface StorageAdapter {
void store(Set<DataPoint> datapoints); | void setConfiguration(Configuration config); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/StorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
| import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import java.util.Set; | package org.wildfly.metrics.scheduler.storage;
/**
* @author Heiko Braun
* @since 10/10/14
*/
public interface StorageAdapter {
void store(Set<DataPoint> datapoints);
void setConfiguration(Configuration config); | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/StorageAdapter.java
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import java.util.Set;
package org.wildfly.metrics.scheduler.storage;
/**
* @author Heiko Braun
* @since 10/10/14
*/
public interface StorageAdapter {
void store(Set<DataPoint> datapoints);
void setConfiguration(Configuration config); | void setDiagnostics(Diagnostics diag); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/IntervalGrouping.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
| import org.wildfly.metrics.scheduler.config.Interval;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
*/
public class IntervalGrouping implements TaskGrouping {
@Override
public List<TaskGroup> apply(final List<Task> tasks) {
Collections.sort(tasks, new Comparator<Task>() {
@Override
public int compare(Task t1, Task t2) {
return new Long(t1.getInterval().millis()).compareTo(t2.getInterval().millis());
}
});
List<TaskGroup> groups = new ArrayList<>(); | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/IntervalGrouping.java
import org.wildfly.metrics.scheduler.config.Interval;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
*/
public class IntervalGrouping implements TaskGrouping {
@Override
public List<TaskGroup> apply(final List<Task> tasks) {
Collections.sort(tasks, new Comparator<Task>() {
@Override
public int compare(Task t1, Task t2) {
return new Long(t1.getInterval().millis()).compareTo(t2.getInterval().millis());
}
});
List<TaskGroup> groups = new ArrayList<>(); | Interval interval = tasks.get(0).getInterval(); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/Scheduler.java | // Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
| import java.util.List;
import org.wildfly.metrics.scheduler.storage.DataPoint; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* Performs the actual work collecting the data from the monitored resources.
* Used by the main {@link org.wildfly.metrics.scheduler.Service}
*
* @author Harald Pehl
*/
public interface Scheduler {
public enum State {RUNNING, STOPPED}
void schedule(List<Task> operations, CompletionHandler completionHandler);
void shutdown();
/**
* Callback for completed tasks
*/
interface CompletionHandler { | // Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Scheduler.java
import java.util.List;
import org.wildfly.metrics.scheduler.storage.DataPoint;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* Performs the actual work collecting the data from the monitored resources.
* Used by the main {@link org.wildfly.metrics.scheduler.Service}
*
* @author Harald Pehl
*/
public interface Scheduler {
public enum State {RUNNING, STOPPED}
void schedule(List<Task> operations, CompletionHandler completionHandler);
void shutdown();
/**
* Callback for completed tasks
*/
interface CompletionHandler { | void onCompleted(DataPoint sample); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/TaskGroup.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
| import com.google.common.collect.Iterators;
import org.wildfly.metrics.scheduler.config.Interval;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.UUID; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
*/
public class TaskGroup implements Iterable<Task> {
private final String id; // to uniquely reference this group | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Interval.java
// public class Interval{
//
// public final static Interval EACH_SECOND = new Interval(1, SECONDS);
// public final static Interval TWENTY_SECONDS = new Interval(20, SECONDS);
// public final static Interval EACH_MINUTE = new Interval(1, MINUTES);
// public final static Interval TWENTY_MINUTES = new Interval(20, MINUTES);
// public final static Interval EACH_HOUR = new Interval(1, HOURS);
// public final static Interval FOUR_HOURS = new Interval(4, HOURS);
// public final static Interval EACH_DAY = new Interval(24, HOURS);
//
// private final int val;
// private final TimeUnit unit;
//
// public Interval(int val, TimeUnit unit) {
// this.val = val;
// this.unit = unit;
// }
//
// public long millis() {
// return MILLISECONDS.convert(val, unit);
// }
//
// public int getVal() {
// return val;
// }
//
// public TimeUnit getUnit() {
// return unit;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/TaskGroup.java
import com.google.common.collect.Iterators;
import org.wildfly.metrics.scheduler.config.Interval;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.UUID;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
*/
public class TaskGroup implements Iterable<Task> {
private final String id; // to uniquely reference this group | private final Interval interval; // impacts thread scheduling |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/RHQStorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
| import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.rhq.metrics.client.common.Batcher;
import org.rhq.metrics.client.common.SingleMetric;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.ArrayList;
import java.util.List;
import java.util.Set; | package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to RHQ metrics.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class RHQStorageAdapter implements StorageAdapter {
private Configuration config; | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/RHQStorageAdapter.java
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.rhq.metrics.client.common.Batcher;
import org.rhq.metrics.client.common.SingleMetric;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to RHQ metrics.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class RHQStorageAdapter implements StorageAdapter {
private Configuration config; | private Diagnostics diagnostics; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/RHQStorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
| import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.rhq.metrics.client.common.Batcher;
import org.rhq.metrics.client.common.SingleMetric;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.ArrayList;
import java.util.List;
import java.util.Set; | package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to RHQ metrics.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class RHQStorageAdapter implements StorageAdapter {
private Configuration config;
private Diagnostics diagnostics;
private final HttpClient httpclient;
private final DefaultKeyResolution keyResolution;
public RHQStorageAdapter() {
this.httpclient = new DefaultHttpClient();
this.keyResolution = new DefaultKeyResolution();
}
@Override
public void setConfiguration(Configuration config) {
this.config = config;
}
@Override
public void setDiagnostics(Diagnostics diag) {
this.diagnostics = diag;
}
@Override
public void store(Set<DataPoint> datapoints) {
HttpPost post = new HttpPost(config.getStorageUrl());
try {
List<SingleMetric> metrics = new ArrayList<>();
for (DataPoint datapoint : datapoints) { | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/RHQStorageAdapter.java
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.rhq.metrics.client.common.Batcher;
import org.rhq.metrics.client.common.SingleMetric;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to RHQ metrics.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class RHQStorageAdapter implements StorageAdapter {
private Configuration config;
private Diagnostics diagnostics;
private final HttpClient httpclient;
private final DefaultKeyResolution keyResolution;
public RHQStorageAdapter() {
this.httpclient = new DefaultHttpClient();
this.keyResolution = new DefaultKeyResolution();
}
@Override
public void setConfiguration(Configuration config) {
this.config = config;
}
@Override
public void setDiagnostics(Diagnostics diag) {
this.diagnostics = diag;
}
@Override
public void store(Set<DataPoint> datapoints) {
HttpPost post = new HttpPost(config.getStorageUrl());
try {
List<SingleMetric> metrics = new ArrayList<>();
for (DataPoint datapoint : datapoints) { | Task task = datapoint.getTask(); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java | // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
| import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
* @author Heiko Braun
*/
public class IntervalBasedScheduler extends AbstractScheduler {
private final ScheduledExecutorService executorService;
private final List<ScheduledFuture> jobs;
private final int poolSize;
| // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java
import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
* @author Heiko Braun
*/
public class IntervalBasedScheduler extends AbstractScheduler {
private final ScheduledExecutorService executorService;
private final List<ScheduledFuture> jobs;
private final int poolSize;
| private final ModelControllerClientFactory clientFactory; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java | // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
| import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
* @author Heiko Braun
*/
public class IntervalBasedScheduler extends AbstractScheduler {
private final ScheduledExecutorService executorService;
private final List<ScheduledFuture> jobs;
private final int poolSize;
private final ModelControllerClientFactory clientFactory; | // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java
import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
* @author Heiko Braun
*/
public class IntervalBasedScheduler extends AbstractScheduler {
private final ScheduledExecutorService executorService;
private final List<ScheduledFuture> jobs;
private final int poolSize;
private final ModelControllerClientFactory clientFactory; | private final Diagnostics monitor; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java | // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
| import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
* @author Heiko Braun
*/
public class IntervalBasedScheduler extends AbstractScheduler {
private final ScheduledExecutorService executorService;
private final List<ScheduledFuture> jobs;
private final int poolSize;
private final ModelControllerClientFactory clientFactory;
private final Diagnostics monitor;
private ConcurrentLinkedQueue<ModelControllerClient> connectionPool = new ConcurrentLinkedQueue<>();
public IntervalBasedScheduler(ModelControllerClientFactory clientFactory, Diagnostics monitor, final int poolSize) {
this.clientFactory = clientFactory;
this.monitor = monitor;
this.poolSize = poolSize;
this.executorService = Executors.newScheduledThreadPool(poolSize, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) { | // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java
import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* @author Harald Pehl
* @author Heiko Braun
*/
public class IntervalBasedScheduler extends AbstractScheduler {
private final ScheduledExecutorService executorService;
private final List<ScheduledFuture> jobs;
private final int poolSize;
private final ModelControllerClientFactory clientFactory;
private final Diagnostics monitor;
private ConcurrentLinkedQueue<ModelControllerClient> connectionPool = new ConcurrentLinkedQueue<>();
public IntervalBasedScheduler(ModelControllerClientFactory clientFactory, Diagnostics monitor, final int poolSize) {
this.clientFactory = clientFactory;
this.monitor = monitor;
this.poolSize = poolSize;
this.executorService = Executors.newScheduledThreadPool(poolSize, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) { | SchedulerLogger.LOGGER.debug("Creating new executor thread"); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java | // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
| import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED; |
long durationMs = requestContext.stop() / 1000000;
String outcome = response.get(OUTCOME).asString();
if (SUCCESS.equals(outcome))
{
if (durationMs > group.getInterval().millis()) {
monitor.getDelayedRate().mark(1);
}
List<Property> steps = response.get(RESULT).asPropertyList();
assert steps.size() == group.size() : "group structure doesn't match actual response structure";
int i=0;
for (Property step : steps) {
Task task = group.getTask(i);
// deconstruct model node
ModelNode data = step.getValue();
Double value = null;
if(task.getSubref()!=null)
{
value = data.get(RESULT).get(task.getSubref()).asDouble();
}
else
{
value = data.get(RESULT).asDouble();
}
| // Path: src/main/java/org/rhq/wfly/monitor/extension/MonitorLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface MonitorLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.rhq.wfly.monitor}.
// */
// MonitorLogger LOGGER = Logger.getMessageLogger(MonitorLogger.class, "org.rhq.wfly.monitor");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/ModelControllerClientFactory.java
// public interface ModelControllerClientFactory {
// ModelControllerClient createClient();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/SchedulerLogger.java
// @MessageLogger(projectCode = "<<none>>")
// public interface SchedulerLogger extends BasicLogger {
// /**
// * A logger with the category {@code org.wildfly.metrics.scheduler}.
// */
// SchedulerLogger LOGGER = Logger.getMessageLogger(SchedulerLogger.class, "org.wildfly.metrics.scheduler");
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/DataPoint.java
// public final class DataPoint {
// private Task task;
// private long timestamp;
// private double value;
//
// public DataPoint(Task task, double value) {
// this.task = task;
// this.timestamp = System.currentTimeMillis();
// this.value = value;
// }
//
// public Task getTask() {
// return task;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public double getValue() {
// return value;
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/IntervalBasedScheduler.java
import com.codahale.metrics.Timer;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.rhq.wfly.monitor.extension.MonitorLogger;
import org.wildfly.metrics.scheduler.ModelControllerClientFactory;
import org.wildfly.metrics.scheduler.SchedulerLogger;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.storage.DataPoint;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.RUNNING;
import static org.wildfly.metrics.scheduler.polling.Scheduler.State.STOPPED;
long durationMs = requestContext.stop() / 1000000;
String outcome = response.get(OUTCOME).asString();
if (SUCCESS.equals(outcome))
{
if (durationMs > group.getInterval().millis()) {
monitor.getDelayedRate().mark(1);
}
List<Property> steps = response.get(RESULT).asPropertyList();
assert steps.size() == group.size() : "group structure doesn't match actual response structure";
int i=0;
for (Property step : steps) {
Task task = group.getTask(i);
// deconstruct model node
ModelNode data = step.getValue();
Double value = null;
if(task.getSubref()!=null)
{
value = data.get(RESULT).get(task.getSubref()).asDouble();
}
else
{
value = data.get(RESULT).asDouble();
}
| completionHandler.onCompleted(new DataPoint(task, value)); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/polling/ReadAttributeOperationBuilder.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Address.java
// public class Address implements Iterable<Address.Tuple> {
//
// public static Address apply(String address) {
// List<String> tokens = address == null ? Collections.<String>emptyList() :
// Splitter.on(CharMatcher.anyOf("/="))
// .trimResults()
// .omitEmptyStrings()
// .splitToList(address);
//
// List<Tuple> tuples = new ArrayList<>(tokens.size() / 2 + 1);
// for (Iterator<String> iterator = tokens.iterator(); iterator.hasNext(); ) {
// String type = iterator.next();
// String name = iterator.hasNext() ? iterator.next() : "";
// tuples.add(new Tuple(type, name));
// }
//
// return new Address(tuples);
// }
//
//
// private final List<Tuple> tuples;
//
// private Address(final List<Tuple> tuples) {
// this.tuples = new ArrayList<>();
// if (tuples != null) {
// this.tuples.addAll(tuples);
// }
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Address)) { return false; }
//
// Address address = (Address) o;
//
// if (!tuples.equals(address.tuples)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return tuples.hashCode();
// }
//
// @Override
// public String toString() {
// return Joiner.on('/').join(tuples);
// }
//
// @Override
// public Iterator<Tuple> iterator() {
// return Iterators.unmodifiableIterator(tuples.iterator());
// }
//
// public boolean isEmpty() {return tuples.isEmpty();}
//
// public boolean isBalanced() {
// for (Tuple tuple : this) {
// if (tuple.getValue() == null || tuple.getValue().length() == 0) {
// return false;
// }
// }
// return true;
// }
//
// public boolean startsWith(Tuple tuple) {
// return !tuples.isEmpty() && tuples.get(0).equals(tuple);
// }
//
//
// /**
// * @author Harald Pehl
// */
// public static class Tuple {
//
// public static Tuple apply(String tuple) {
// if (tuple == null) {
// throw new IllegalArgumentException("Tuple must not be null");
// }
// List<String> tuples = Splitter.on('=')
// .omitEmptyStrings()
// .trimResults()
// .splitToList(tuple);
// if (tuples.isEmpty() || tuples.size() != 2) {
// throw new IllegalArgumentException("Malformed tuple: " + tuple);
// }
// return new Tuple(tuples.get(0), tuples.get(1));
// }
//
// private final String key;
// private final String value;
//
// private Tuple(final String key, final String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Tuple)) { return false; }
//
// Tuple that = (Tuple) o;
//
// if (!value.equals(that.value)) { return false; }
// if (!key.equals(that.key)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key.hashCode();
// result = 31 * result + value.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return key + "=" + value;
// }
//
// public String getKey() {
// return key;
// }
//
// public String getValue() {
// return value;
// }
// }
// }
| import org.wildfly.metrics.scheduler.config.Address;
import java.util.ArrayList;
import java.util.List;
import org.jboss.dmr.ModelNode; | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* Creates a {@code read-attribute} operation of the given {@link TaskGroup}.
*
* @author Harald Pehl
*/
public class ReadAttributeOperationBuilder implements OperationBuilder {
@Override
public ModelNode createOperation(final TaskGroup group) {
if (group.isEmpty()) {
throw new IllegalArgumentException("Empty groups are not allowed");
}
ModelNode comp = new ModelNode();
List<ModelNode> steps = new ArrayList<>();
comp.get("address").setEmptyList();
comp.get("operation").set("composite");
for (Task task : group) {
steps.add(readAttribute(task));
}
comp.get("steps").set(steps);
return comp;
}
private ModelNode readAttribute(Task task) {
ModelNode node = new ModelNode(); | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Address.java
// public class Address implements Iterable<Address.Tuple> {
//
// public static Address apply(String address) {
// List<String> tokens = address == null ? Collections.<String>emptyList() :
// Splitter.on(CharMatcher.anyOf("/="))
// .trimResults()
// .omitEmptyStrings()
// .splitToList(address);
//
// List<Tuple> tuples = new ArrayList<>(tokens.size() / 2 + 1);
// for (Iterator<String> iterator = tokens.iterator(); iterator.hasNext(); ) {
// String type = iterator.next();
// String name = iterator.hasNext() ? iterator.next() : "";
// tuples.add(new Tuple(type, name));
// }
//
// return new Address(tuples);
// }
//
//
// private final List<Tuple> tuples;
//
// private Address(final List<Tuple> tuples) {
// this.tuples = new ArrayList<>();
// if (tuples != null) {
// this.tuples.addAll(tuples);
// }
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Address)) { return false; }
//
// Address address = (Address) o;
//
// if (!tuples.equals(address.tuples)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return tuples.hashCode();
// }
//
// @Override
// public String toString() {
// return Joiner.on('/').join(tuples);
// }
//
// @Override
// public Iterator<Tuple> iterator() {
// return Iterators.unmodifiableIterator(tuples.iterator());
// }
//
// public boolean isEmpty() {return tuples.isEmpty();}
//
// public boolean isBalanced() {
// for (Tuple tuple : this) {
// if (tuple.getValue() == null || tuple.getValue().length() == 0) {
// return false;
// }
// }
// return true;
// }
//
// public boolean startsWith(Tuple tuple) {
// return !tuples.isEmpty() && tuples.get(0).equals(tuple);
// }
//
//
// /**
// * @author Harald Pehl
// */
// public static class Tuple {
//
// public static Tuple apply(String tuple) {
// if (tuple == null) {
// throw new IllegalArgumentException("Tuple must not be null");
// }
// List<String> tuples = Splitter.on('=')
// .omitEmptyStrings()
// .trimResults()
// .splitToList(tuple);
// if (tuples.isEmpty() || tuples.size() != 2) {
// throw new IllegalArgumentException("Malformed tuple: " + tuple);
// }
// return new Tuple(tuples.get(0), tuples.get(1));
// }
//
// private final String key;
// private final String value;
//
// private Tuple(final String key, final String value) {
// this.key = key;
// this.value = value;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) { return true; }
// if (!(o instanceof Tuple)) { return false; }
//
// Tuple that = (Tuple) o;
//
// if (!value.equals(that.value)) { return false; }
// if (!key.equals(that.key)) { return false; }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = key.hashCode();
// result = 31 * result + value.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return key + "=" + value;
// }
//
// public String getKey() {
// return key;
// }
//
// public String getValue() {
// return value;
// }
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/ReadAttributeOperationBuilder.java
import org.wildfly.metrics.scheduler.config.Address;
import java.util.ArrayList;
import java.util.List;
import org.jboss.dmr.ModelNode;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.wildfly.metrics.scheduler.polling;
/**
* Creates a {@code read-attribute} operation of the given {@link TaskGroup}.
*
* @author Harald Pehl
*/
public class ReadAttributeOperationBuilder implements OperationBuilder {
@Override
public ModelNode createOperation(final TaskGroup group) {
if (group.isEmpty()) {
throw new IllegalArgumentException("Empty groups are not allowed");
}
ModelNode comp = new ModelNode();
List<ModelNode> steps = new ArrayList<>();
comp.get("address").setEmptyList();
comp.get("operation").set("composite");
for (Task task : group) {
steps.add(readAttribute(task));
}
comp.get("steps").set(steps);
return comp;
}
private ModelNode readAttribute(Task task) {
ModelNode node = new ModelNode(); | Address address = task.getAddress(); |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/InfluxStorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
| import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Serie;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.Set;
import java.util.concurrent.TimeUnit; | package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to Influx.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class InfluxStorageAdapter implements StorageAdapter {
private InfluxDB influxDB;
private String dbName; | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/InfluxStorageAdapter.java
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Serie;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.Set;
import java.util.concurrent.TimeUnit;
package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to Influx.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class InfluxStorageAdapter implements StorageAdapter {
private InfluxDB influxDB;
private String dbName; | private Diagnostics diagnostics; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/InfluxStorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
| import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Serie;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.Set;
import java.util.concurrent.TimeUnit; | package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to Influx.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class InfluxStorageAdapter implements StorageAdapter {
private InfluxDB influxDB;
private String dbName;
private Diagnostics diagnostics; | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/InfluxStorageAdapter.java
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Serie;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.Set;
import java.util.concurrent.TimeUnit;
package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to Influx.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class InfluxStorageAdapter implements StorageAdapter {
private InfluxDB influxDB;
private String dbName;
private Diagnostics diagnostics; | private Configuration config; |
hawkular/wildfly-monitor | src/main/java/org/wildfly/metrics/scheduler/storage/InfluxStorageAdapter.java | // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
| import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Serie;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.Set;
import java.util.concurrent.TimeUnit; | package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to Influx.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class InfluxStorageAdapter implements StorageAdapter {
private InfluxDB influxDB;
private String dbName;
private Diagnostics diagnostics;
private Configuration config;
private DefaultKeyResolution keyResolution;
@Override
public void setConfiguration(Configuration config) {
this.config = config;
this.influxDB = InfluxDBFactory.connect(
config.getStorageUrl(),
config.getStorageUser(),
config.getStoragePassword()
);
this.dbName = config.getStorageDBName();
this.keyResolution = new DefaultKeyResolution();
}
@Override
public void setDiagnostics(Diagnostics diag) {
this.diagnostics = diag;
}
@Override
public void store(Set<DataPoint> datapoints) {
try {
Serie[] series = new Serie[datapoints.size()];
int i=0;
for (DataPoint datapoint : datapoints) {
| // Path: src/main/java/org/wildfly/metrics/scheduler/config/Configuration.java
// public interface Configuration {
//
// public enum Diagnostics {STORAGE, CONSOLE};
// public enum Storage {RHQ, INFLUX}
//
// /**
// * The host controller host.
// * @return
// */
// String getHost();
//
// /**
// * The host controller port.
// *
// * @return
// */
// int getPort();
//
// /**
// * Host controller user
// * @return
// */
// String getUsername();
//
// /**
// * Host controller password
// * @return
// */
// String getPassword();
//
// /**
// * Number of threads the scheduler uses to poll for new data.
// *
// * @return
// */
// int getSchedulerThreads();
//
// /**
// * The resources that are to be monitored.
// * {@link org.wildfly.metrics.scheduler.config.ResourceRef}'s use relative addresses.
// * The core {@link org.wildfly.metrics.scheduler.Service} will resolve it against absolute address within a Wildfly domain.
// *
// * @return
// */
// List<ResourceRef> getResourceRefs();
//
// Storage getStorageAdapter();
//
// String getStorageUrl();
//
// String getStorageUser();
//
// String getStoragePassword();
//
// String getStorageDBName();
//
// String getStorageToken();
//
// Diagnostics getDiagnostics();
//
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/diagnose/Diagnostics.java
// public interface Diagnostics {
// Timer getRequestTimer();
// Meter getErrorRate();
// Meter getDelayedRate();
//
// Meter getStorageErrorRate();
// Counter getStorageBufferSize();
// }
//
// Path: src/main/java/org/wildfly/metrics/scheduler/polling/Task.java
// public class Task {
//
// private final String host;
// private final String server;
// private final Address address;
// private final String attribute;
// private final String subref;
// private final Interval interval;
//
// public Task(
// String host, String server,
// Address address,
// String attribute,
// String subref,
// Interval interval
// ) {
// this.host = host;
// this.server = server;
// this.address = address;
// this.attribute = attribute;
// this.subref = subref;
// this.interval = interval;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public String getAttribute() {
// return attribute;
// }
//
// public Interval getInterval() {
// return interval;
// }
//
// public String getSubref() {
// return subref;
// }
//
// public String getHost() {
// return host;
// }
//
// public String getServer() {
// return server;
// }
//
// @Override
// public String toString() {
// return "Task{" +
// "address=" + address +
// ", attribute='" + attribute + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/wildfly/metrics/scheduler/storage/InfluxStorageAdapter.java
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Serie;
import org.wildfly.metrics.scheduler.config.Configuration;
import org.wildfly.metrics.scheduler.diagnose.Diagnostics;
import org.wildfly.metrics.scheduler.polling.Task;
import java.util.Set;
import java.util.concurrent.TimeUnit;
package org.wildfly.metrics.scheduler.storage;
/**
* Pushes the data to Influx.
*
* @author Heiko Braun
* @since 13/10/14
*/
public class InfluxStorageAdapter implements StorageAdapter {
private InfluxDB influxDB;
private String dbName;
private Diagnostics diagnostics;
private Configuration config;
private DefaultKeyResolution keyResolution;
@Override
public void setConfiguration(Configuration config) {
this.config = config;
this.influxDB = InfluxDBFactory.connect(
config.getStorageUrl(),
config.getStorageUser(),
config.getStoragePassword()
);
this.dbName = config.getStorageDBName();
this.keyResolution = new DefaultKeyResolution();
}
@Override
public void setDiagnostics(Diagnostics diag) {
this.diagnostics = diag;
}
@Override
public void store(Set<DataPoint> datapoints) {
try {
Serie[] series = new Serie[datapoints.size()];
int i=0;
for (DataPoint datapoint : datapoints) {
| Task task = datapoint.getTask(); |
darugnaa/apache-camel-examples | camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/AnnotationExclusionStrategy.java | // Path: camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/dto/Greeting.java
// public class Greeting {
//
// @Expose
// private String greeting;
// @Expose
// private LocalDateTime greetingDate;
// @Expose
// private Map<String,Integer> recipients;
//
// // keep away from marshalling
// private String toStringRepr;
//
// public String getGreeting() {
// return greeting;
// }
//
// public void setGreeting(String greeting) {
// this.greeting = greeting;
// }
//
// public LocalDateTime getGreetingDate() {
// return greetingDate;
// }
//
// public void setGreetingDateTime(LocalDateTime greetingDate) {
// this.greetingDate = greetingDate;
// }
//
// public Map<String, Integer> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(Map<String, Integer> recipients) {
// this.recipients = recipients;
// }
//
// public void addRecipient(String recipient, Integer numberOfGreets) {
// if (recipients == null) {
// recipients = new HashMap<>();
// }
// recipients.put(recipient, numberOfGreets);
// }
//
// @Override
// public String toString() {
// if (toStringRepr == null) {
// final StringBuilder sb = new StringBuilder();
// sb.append("On ").append(greetingDate)
// .append(" I said '").append(greeting).append("' to:");
// recipients.keySet().forEach(k -> {
// sb.append(" ").
// append(k).append(" ")
// .append(recipients.get(k))
// .append(" times.");
// });
// toStringRepr = sb.toString();
// }
// return toStringRepr;
// }
//
// }
| import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import java.lang.annotation.Annotation;
import org.darugna.camel.mqtt.dto.Greeting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.darugna.camel.mqtt;
public class AnnotationExclusionStrategy implements ExclusionStrategy {
private final static Logger log = LoggerFactory.getLogger(AnnotationExclusionStrategy.class);
@Override
public boolean shouldSkipField(FieldAttributes fa) {
// On other classes marshal all fields | // Path: camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/dto/Greeting.java
// public class Greeting {
//
// @Expose
// private String greeting;
// @Expose
// private LocalDateTime greetingDate;
// @Expose
// private Map<String,Integer> recipients;
//
// // keep away from marshalling
// private String toStringRepr;
//
// public String getGreeting() {
// return greeting;
// }
//
// public void setGreeting(String greeting) {
// this.greeting = greeting;
// }
//
// public LocalDateTime getGreetingDate() {
// return greetingDate;
// }
//
// public void setGreetingDateTime(LocalDateTime greetingDate) {
// this.greetingDate = greetingDate;
// }
//
// public Map<String, Integer> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(Map<String, Integer> recipients) {
// this.recipients = recipients;
// }
//
// public void addRecipient(String recipient, Integer numberOfGreets) {
// if (recipients == null) {
// recipients = new HashMap<>();
// }
// recipients.put(recipient, numberOfGreets);
// }
//
// @Override
// public String toString() {
// if (toStringRepr == null) {
// final StringBuilder sb = new StringBuilder();
// sb.append("On ").append(greetingDate)
// .append(" I said '").append(greeting).append("' to:");
// recipients.keySet().forEach(k -> {
// sb.append(" ").
// append(k).append(" ")
// .append(recipients.get(k))
// .append(" times.");
// });
// toStringRepr = sb.toString();
// }
// return toStringRepr;
// }
//
// }
// Path: camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/AnnotationExclusionStrategy.java
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import java.lang.annotation.Annotation;
import org.darugna.camel.mqtt.dto.Greeting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.darugna.camel.mqtt;
public class AnnotationExclusionStrategy implements ExclusionStrategy {
private final static Logger log = LoggerFactory.getLogger(AnnotationExclusionStrategy.class);
@Override
public boolean shouldSkipField(FieldAttributes fa) {
// On other classes marshal all fields | if (!fa.getDeclaringClass().equals(Greeting.class)) { |
darugnaa/apache-camel-examples | camel-standalone-http/src/main/java/org/darugna/camel/StandaloneLauncher.java | // Path: camel-standalone-http/src/main/java/org/darugna/camel/http/HttpRouteBuilder.java
// public class HttpRouteBuilder extends RouteBuilder {
//
// /**
// * Let's configure the Camel routing rules using Java code...
// */
// @Override
// public void configure() {
// from("file:data/input?noop=true")
// .process(new CustomTokenizer())
// .split(body(), new DefinitionAggregationStrategy())
// .setHeader("WORD", body())
// .to("direct:httprequest")
// .process(new HtmlProcessor())
// .end()
// .convertBodyTo(String.class) // From StringBuilder to String
// .setHeader(Exchange.FILE_NAME, constant("definitions.txt"))
// .to("file:data/output?fileExist=Append")
// .log("Finished processing file ${header.CamelFileName}");
//
//
// from("direct:httprequest")
// .log("Requesting page '${body}'")
// .recipientList(simple("http://www.merriam-webster.com/dictionary/${body}"));
//
// }
// }
| import org.apache.camel.main.Main;
import org.darugna.camel.http.HttpRouteBuilder; | package org.darugna.camel;
public class StandaloneLauncher {
public static void main(String... args) throws Exception {
Main main = new Main(); | // Path: camel-standalone-http/src/main/java/org/darugna/camel/http/HttpRouteBuilder.java
// public class HttpRouteBuilder extends RouteBuilder {
//
// /**
// * Let's configure the Camel routing rules using Java code...
// */
// @Override
// public void configure() {
// from("file:data/input?noop=true")
// .process(new CustomTokenizer())
// .split(body(), new DefinitionAggregationStrategy())
// .setHeader("WORD", body())
// .to("direct:httprequest")
// .process(new HtmlProcessor())
// .end()
// .convertBodyTo(String.class) // From StringBuilder to String
// .setHeader(Exchange.FILE_NAME, constant("definitions.txt"))
// .to("file:data/output?fileExist=Append")
// .log("Finished processing file ${header.CamelFileName}");
//
//
// from("direct:httprequest")
// .log("Requesting page '${body}'")
// .recipientList(simple("http://www.merriam-webster.com/dictionary/${body}"));
//
// }
// }
// Path: camel-standalone-http/src/main/java/org/darugna/camel/StandaloneLauncher.java
import org.apache.camel.main.Main;
import org.darugna.camel.http.HttpRouteBuilder;
package org.darugna.camel;
public class StandaloneLauncher {
public static void main(String... args) throws Exception {
Main main = new Main(); | main.addRouteBuilder(new HttpRouteBuilder()); |
darugnaa/apache-camel-examples | camel-blueprint-csv/src/main/java/org/darugna/camel/csv/Stats.java | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java
// @CsvRecord(separator = ",", skipFirstLine = true)
// public class Company {
//
// @DataField(pos = 1)
// String symbol;
//
// @DataField(pos = 2)
// String name;
//
// @DataField(pos = 3)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal lastSale;
//
// @DataField(pos = 4)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal marketCap;
//
// @DataField(pos = 5)
// String tso;
//
// @DataField(pos = 6)
// String ipoYear;
//
// @DataField(pos = 7)
// @BindyConverter(SectionFormatter.class)
// Sector sector;
//
// @DataField(pos = 8)
// String industry;
//
// @DataField(pos = 9)
// String url;
//
// @DataField(pos = 10)
// String empty;
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public BigDecimal getLastSale() {
// return lastSale;
// }
//
// public void setLastSale(BigDecimal lastSale) {
// this.lastSale = lastSale;
// }
//
// public BigDecimal getMarketCap() {
// return marketCap;
// }
//
// public void setMarketCap(BigDecimal marketCap) {
// this.marketCap = marketCap;
// }
//
// public String getTso() {
// return tso;
// }
//
// public void setTso(String tso) {
// this.tso = tso;
// }
//
// public String getIpoYear() {
// return ipoYear;
// }
//
// public void setIpoYear(String ipoYear) {
// this.ipoYear = ipoYear;
// }
//
// public Sector getSector() {
// return sector;
// }
//
// public void setSector(Sector sector) {
// this.sector = sector;
// }
//
// public String getIndustry() {
// return industry;
// }
//
// public void setIndustry(String industry) {
// this.industry = industry;
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Sector.java
// public enum Sector {
//
// Technology,
// HealthCare,
// ConsumerServices,
// CapitalGoods,
// ConsumerDurables,
// Finance,
// Miscellaneous,
// ConsumerNonDurables,
// PublicUtilities,
// BasicIndustries,
// Energy,
// Transportation,
// NotAvailable;
//
// }
| import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.darugna.camel.csv.dto.Company;
import org.darugna.camel.csv.dto.Sector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.darugna.camel.csv;
public class Stats {
private final static Logger LOGGER = LoggerFactory.getLogger(Stats.class);
| // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java
// @CsvRecord(separator = ",", skipFirstLine = true)
// public class Company {
//
// @DataField(pos = 1)
// String symbol;
//
// @DataField(pos = 2)
// String name;
//
// @DataField(pos = 3)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal lastSale;
//
// @DataField(pos = 4)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal marketCap;
//
// @DataField(pos = 5)
// String tso;
//
// @DataField(pos = 6)
// String ipoYear;
//
// @DataField(pos = 7)
// @BindyConverter(SectionFormatter.class)
// Sector sector;
//
// @DataField(pos = 8)
// String industry;
//
// @DataField(pos = 9)
// String url;
//
// @DataField(pos = 10)
// String empty;
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public BigDecimal getLastSale() {
// return lastSale;
// }
//
// public void setLastSale(BigDecimal lastSale) {
// this.lastSale = lastSale;
// }
//
// public BigDecimal getMarketCap() {
// return marketCap;
// }
//
// public void setMarketCap(BigDecimal marketCap) {
// this.marketCap = marketCap;
// }
//
// public String getTso() {
// return tso;
// }
//
// public void setTso(String tso) {
// this.tso = tso;
// }
//
// public String getIpoYear() {
// return ipoYear;
// }
//
// public void setIpoYear(String ipoYear) {
// this.ipoYear = ipoYear;
// }
//
// public Sector getSector() {
// return sector;
// }
//
// public void setSector(Sector sector) {
// this.sector = sector;
// }
//
// public String getIndustry() {
// return industry;
// }
//
// public void setIndustry(String industry) {
// this.industry = industry;
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Sector.java
// public enum Sector {
//
// Technology,
// HealthCare,
// ConsumerServices,
// CapitalGoods,
// ConsumerDurables,
// Finance,
// Miscellaneous,
// ConsumerNonDurables,
// PublicUtilities,
// BasicIndustries,
// Energy,
// Transportation,
// NotAvailable;
//
// }
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/Stats.java
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.darugna.camel.csv.dto.Company;
import org.darugna.camel.csv.dto.Sector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.darugna.camel.csv;
public class Stats {
private final static Logger LOGGER = LoggerFactory.getLogger(Stats.class);
| public void printStats(List<Company> companies) { |
darugnaa/apache-camel-examples | camel-blueprint-csv/src/main/java/org/darugna/camel/csv/Stats.java | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java
// @CsvRecord(separator = ",", skipFirstLine = true)
// public class Company {
//
// @DataField(pos = 1)
// String symbol;
//
// @DataField(pos = 2)
// String name;
//
// @DataField(pos = 3)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal lastSale;
//
// @DataField(pos = 4)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal marketCap;
//
// @DataField(pos = 5)
// String tso;
//
// @DataField(pos = 6)
// String ipoYear;
//
// @DataField(pos = 7)
// @BindyConverter(SectionFormatter.class)
// Sector sector;
//
// @DataField(pos = 8)
// String industry;
//
// @DataField(pos = 9)
// String url;
//
// @DataField(pos = 10)
// String empty;
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public BigDecimal getLastSale() {
// return lastSale;
// }
//
// public void setLastSale(BigDecimal lastSale) {
// this.lastSale = lastSale;
// }
//
// public BigDecimal getMarketCap() {
// return marketCap;
// }
//
// public void setMarketCap(BigDecimal marketCap) {
// this.marketCap = marketCap;
// }
//
// public String getTso() {
// return tso;
// }
//
// public void setTso(String tso) {
// this.tso = tso;
// }
//
// public String getIpoYear() {
// return ipoYear;
// }
//
// public void setIpoYear(String ipoYear) {
// this.ipoYear = ipoYear;
// }
//
// public Sector getSector() {
// return sector;
// }
//
// public void setSector(Sector sector) {
// this.sector = sector;
// }
//
// public String getIndustry() {
// return industry;
// }
//
// public void setIndustry(String industry) {
// this.industry = industry;
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Sector.java
// public enum Sector {
//
// Technology,
// HealthCare,
// ConsumerServices,
// CapitalGoods,
// ConsumerDurables,
// Finance,
// Miscellaneous,
// ConsumerNonDurables,
// PublicUtilities,
// BasicIndustries,
// Energy,
// Transportation,
// NotAvailable;
//
// }
| import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.darugna.camel.csv.dto.Company;
import org.darugna.camel.csv.dto.Sector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.darugna.camel.csv;
public class Stats {
private final static Logger LOGGER = LoggerFactory.getLogger(Stats.class);
public void printStats(List<Company> companies) {
countBySector(companies);
marketCaps(companies);
}
private void countBySector(List<Company> companies) { | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java
// @CsvRecord(separator = ",", skipFirstLine = true)
// public class Company {
//
// @DataField(pos = 1)
// String symbol;
//
// @DataField(pos = 2)
// String name;
//
// @DataField(pos = 3)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal lastSale;
//
// @DataField(pos = 4)
// @BindyConverter(BigDecimalFormatter.class)
// BigDecimal marketCap;
//
// @DataField(pos = 5)
// String tso;
//
// @DataField(pos = 6)
// String ipoYear;
//
// @DataField(pos = 7)
// @BindyConverter(SectionFormatter.class)
// Sector sector;
//
// @DataField(pos = 8)
// String industry;
//
// @DataField(pos = 9)
// String url;
//
// @DataField(pos = 10)
// String empty;
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public BigDecimal getLastSale() {
// return lastSale;
// }
//
// public void setLastSale(BigDecimal lastSale) {
// this.lastSale = lastSale;
// }
//
// public BigDecimal getMarketCap() {
// return marketCap;
// }
//
// public void setMarketCap(BigDecimal marketCap) {
// this.marketCap = marketCap;
// }
//
// public String getTso() {
// return tso;
// }
//
// public void setTso(String tso) {
// this.tso = tso;
// }
//
// public String getIpoYear() {
// return ipoYear;
// }
//
// public void setIpoYear(String ipoYear) {
// this.ipoYear = ipoYear;
// }
//
// public Sector getSector() {
// return sector;
// }
//
// public void setSector(Sector sector) {
// this.sector = sector;
// }
//
// public String getIndustry() {
// return industry;
// }
//
// public void setIndustry(String industry) {
// this.industry = industry;
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Sector.java
// public enum Sector {
//
// Technology,
// HealthCare,
// ConsumerServices,
// CapitalGoods,
// ConsumerDurables,
// Finance,
// Miscellaneous,
// ConsumerNonDurables,
// PublicUtilities,
// BasicIndustries,
// Energy,
// Transportation,
// NotAvailable;
//
// }
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/Stats.java
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.darugna.camel.csv.dto.Company;
import org.darugna.camel.csv.dto.Sector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.darugna.camel.csv;
public class Stats {
private final static Logger LOGGER = LoggerFactory.getLogger(Stats.class);
public void printStats(List<Company> companies) {
countBySector(companies);
marketCaps(companies);
}
private void countBySector(List<Company> companies) { | Map<Sector,Long> countBySector = companies |
darugnaa/apache-camel-examples | camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/BigDecimalFormatter.java
// public class BigDecimalFormatter implements Format<BigDecimal> {
//
// private final MathContext mathContext = new MathContext(4);
//
// @Override
// public String format(BigDecimal object) throws Exception {
// return object.toPlainString();
// }
//
// @Override
// public BigDecimal parse(String string) throws Exception {
// // handle special case: value not available
// if ("n/a".equals(string)) {
// return null;
// }
//
// return new BigDecimal(string, mathContext);
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/SectionFormatter.java
// public class SectionFormatter implements Format<Sector> {
//
// private final Map<String, Sector> stringToSector;
// private final Map<Sector, String> sectorToString;
//
// public SectionFormatter() {
// stringToSector = new HashMap<>();
// sectorToString = new HashMap<>();
// addMapping("n/a", Sector.NotAvailable);
// addMapping("Technology", Sector.Technology);
// addMapping("Health Care", Sector.HealthCare);
// addMapping("Consumer Services", Sector.ConsumerServices);
// addMapping("Capital Goods", Sector.CapitalGoods);
// addMapping("Consumer Durables", Sector.ConsumerDurables);
// addMapping("Finance", Sector.Finance);
// addMapping("Consumer Non-Durables", Sector.ConsumerNonDurables);
// addMapping("Public Utilities", Sector.PublicUtilities);
// addMapping("Basic Industries", Sector.BasicIndustries);
// addMapping("Energy", Sector.Energy);
// addMapping("Miscellaneous", Sector.Miscellaneous);
// addMapping("Transportation", Sector.Transportation);
// }
//
// @Override
// public String format(Sector t) throws Exception {
// String sectorString = sectorToString.get(t);
// if (sectorString == null) {
// throw new IllegalArgumentException("Cannot format Sector '" + t.toString() + "'");
// }
// return sectorString;
// }
//
// @Override
// public Sector parse(String string) throws Exception {
// Sector sector = stringToSector.get(string);
// if (sector == null) {
// throw new IllegalArgumentException("Cannot parse Sector '" + string + "'");
// }
// return sector;
// }
//
// private void addMapping(String name, Sector sector) {
// stringToSector.put(name, sector);
// sectorToString.put(sector, name);
// }
//
// }
| import java.math.BigDecimal;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.darugna.camel.csv.formatters.BigDecimalFormatter;
import org.darugna.camel.csv.formatters.SectionFormatter; | package org.darugna.camel.csv.dto;
@CsvRecord(separator = ",", skipFirstLine = true)
public class Company {
@DataField(pos = 1)
String symbol;
@DataField(pos = 2)
String name;
@DataField(pos = 3) | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/BigDecimalFormatter.java
// public class BigDecimalFormatter implements Format<BigDecimal> {
//
// private final MathContext mathContext = new MathContext(4);
//
// @Override
// public String format(BigDecimal object) throws Exception {
// return object.toPlainString();
// }
//
// @Override
// public BigDecimal parse(String string) throws Exception {
// // handle special case: value not available
// if ("n/a".equals(string)) {
// return null;
// }
//
// return new BigDecimal(string, mathContext);
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/SectionFormatter.java
// public class SectionFormatter implements Format<Sector> {
//
// private final Map<String, Sector> stringToSector;
// private final Map<Sector, String> sectorToString;
//
// public SectionFormatter() {
// stringToSector = new HashMap<>();
// sectorToString = new HashMap<>();
// addMapping("n/a", Sector.NotAvailable);
// addMapping("Technology", Sector.Technology);
// addMapping("Health Care", Sector.HealthCare);
// addMapping("Consumer Services", Sector.ConsumerServices);
// addMapping("Capital Goods", Sector.CapitalGoods);
// addMapping("Consumer Durables", Sector.ConsumerDurables);
// addMapping("Finance", Sector.Finance);
// addMapping("Consumer Non-Durables", Sector.ConsumerNonDurables);
// addMapping("Public Utilities", Sector.PublicUtilities);
// addMapping("Basic Industries", Sector.BasicIndustries);
// addMapping("Energy", Sector.Energy);
// addMapping("Miscellaneous", Sector.Miscellaneous);
// addMapping("Transportation", Sector.Transportation);
// }
//
// @Override
// public String format(Sector t) throws Exception {
// String sectorString = sectorToString.get(t);
// if (sectorString == null) {
// throw new IllegalArgumentException("Cannot format Sector '" + t.toString() + "'");
// }
// return sectorString;
// }
//
// @Override
// public Sector parse(String string) throws Exception {
// Sector sector = stringToSector.get(string);
// if (sector == null) {
// throw new IllegalArgumentException("Cannot parse Sector '" + string + "'");
// }
// return sector;
// }
//
// private void addMapping(String name, Sector sector) {
// stringToSector.put(name, sector);
// sectorToString.put(sector, name);
// }
//
// }
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java
import java.math.BigDecimal;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.darugna.camel.csv.formatters.BigDecimalFormatter;
import org.darugna.camel.csv.formatters.SectionFormatter;
package org.darugna.camel.csv.dto;
@CsvRecord(separator = ",", skipFirstLine = true)
public class Company {
@DataField(pos = 1)
String symbol;
@DataField(pos = 2)
String name;
@DataField(pos = 3) | @BindyConverter(BigDecimalFormatter.class) |
darugnaa/apache-camel-examples | camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/BigDecimalFormatter.java
// public class BigDecimalFormatter implements Format<BigDecimal> {
//
// private final MathContext mathContext = new MathContext(4);
//
// @Override
// public String format(BigDecimal object) throws Exception {
// return object.toPlainString();
// }
//
// @Override
// public BigDecimal parse(String string) throws Exception {
// // handle special case: value not available
// if ("n/a".equals(string)) {
// return null;
// }
//
// return new BigDecimal(string, mathContext);
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/SectionFormatter.java
// public class SectionFormatter implements Format<Sector> {
//
// private final Map<String, Sector> stringToSector;
// private final Map<Sector, String> sectorToString;
//
// public SectionFormatter() {
// stringToSector = new HashMap<>();
// sectorToString = new HashMap<>();
// addMapping("n/a", Sector.NotAvailable);
// addMapping("Technology", Sector.Technology);
// addMapping("Health Care", Sector.HealthCare);
// addMapping("Consumer Services", Sector.ConsumerServices);
// addMapping("Capital Goods", Sector.CapitalGoods);
// addMapping("Consumer Durables", Sector.ConsumerDurables);
// addMapping("Finance", Sector.Finance);
// addMapping("Consumer Non-Durables", Sector.ConsumerNonDurables);
// addMapping("Public Utilities", Sector.PublicUtilities);
// addMapping("Basic Industries", Sector.BasicIndustries);
// addMapping("Energy", Sector.Energy);
// addMapping("Miscellaneous", Sector.Miscellaneous);
// addMapping("Transportation", Sector.Transportation);
// }
//
// @Override
// public String format(Sector t) throws Exception {
// String sectorString = sectorToString.get(t);
// if (sectorString == null) {
// throw new IllegalArgumentException("Cannot format Sector '" + t.toString() + "'");
// }
// return sectorString;
// }
//
// @Override
// public Sector parse(String string) throws Exception {
// Sector sector = stringToSector.get(string);
// if (sector == null) {
// throw new IllegalArgumentException("Cannot parse Sector '" + string + "'");
// }
// return sector;
// }
//
// private void addMapping(String name, Sector sector) {
// stringToSector.put(name, sector);
// sectorToString.put(sector, name);
// }
//
// }
| import java.math.BigDecimal;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.darugna.camel.csv.formatters.BigDecimalFormatter;
import org.darugna.camel.csv.formatters.SectionFormatter; | package org.darugna.camel.csv.dto;
@CsvRecord(separator = ",", skipFirstLine = true)
public class Company {
@DataField(pos = 1)
String symbol;
@DataField(pos = 2)
String name;
@DataField(pos = 3)
@BindyConverter(BigDecimalFormatter.class)
BigDecimal lastSale;
@DataField(pos = 4)
@BindyConverter(BigDecimalFormatter.class)
BigDecimal marketCap;
@DataField(pos = 5)
String tso;
@DataField(pos = 6)
String ipoYear;
@DataField(pos = 7) | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/BigDecimalFormatter.java
// public class BigDecimalFormatter implements Format<BigDecimal> {
//
// private final MathContext mathContext = new MathContext(4);
//
// @Override
// public String format(BigDecimal object) throws Exception {
// return object.toPlainString();
// }
//
// @Override
// public BigDecimal parse(String string) throws Exception {
// // handle special case: value not available
// if ("n/a".equals(string)) {
// return null;
// }
//
// return new BigDecimal(string, mathContext);
// }
//
// }
//
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/SectionFormatter.java
// public class SectionFormatter implements Format<Sector> {
//
// private final Map<String, Sector> stringToSector;
// private final Map<Sector, String> sectorToString;
//
// public SectionFormatter() {
// stringToSector = new HashMap<>();
// sectorToString = new HashMap<>();
// addMapping("n/a", Sector.NotAvailable);
// addMapping("Technology", Sector.Technology);
// addMapping("Health Care", Sector.HealthCare);
// addMapping("Consumer Services", Sector.ConsumerServices);
// addMapping("Capital Goods", Sector.CapitalGoods);
// addMapping("Consumer Durables", Sector.ConsumerDurables);
// addMapping("Finance", Sector.Finance);
// addMapping("Consumer Non-Durables", Sector.ConsumerNonDurables);
// addMapping("Public Utilities", Sector.PublicUtilities);
// addMapping("Basic Industries", Sector.BasicIndustries);
// addMapping("Energy", Sector.Energy);
// addMapping("Miscellaneous", Sector.Miscellaneous);
// addMapping("Transportation", Sector.Transportation);
// }
//
// @Override
// public String format(Sector t) throws Exception {
// String sectorString = sectorToString.get(t);
// if (sectorString == null) {
// throw new IllegalArgumentException("Cannot format Sector '" + t.toString() + "'");
// }
// return sectorString;
// }
//
// @Override
// public Sector parse(String string) throws Exception {
// Sector sector = stringToSector.get(string);
// if (sector == null) {
// throw new IllegalArgumentException("Cannot parse Sector '" + string + "'");
// }
// return sector;
// }
//
// private void addMapping(String name, Sector sector) {
// stringToSector.put(name, sector);
// sectorToString.put(sector, name);
// }
//
// }
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/Company.java
import java.math.BigDecimal;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.darugna.camel.csv.formatters.BigDecimalFormatter;
import org.darugna.camel.csv.formatters.SectionFormatter;
package org.darugna.camel.csv.dto;
@CsvRecord(separator = ",", skipFirstLine = true)
public class Company {
@DataField(pos = 1)
String symbol;
@DataField(pos = 2)
String name;
@DataField(pos = 3)
@BindyConverter(BigDecimalFormatter.class)
BigDecimal lastSale;
@DataField(pos = 4)
@BindyConverter(BigDecimalFormatter.class)
BigDecimal marketCap;
@DataField(pos = 5)
String tso;
@DataField(pos = 6)
String ipoYear;
@DataField(pos = 7) | @BindyConverter(SectionFormatter.class) |
darugnaa/apache-camel-examples | camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/SimpleCompany.java | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/SectionFormatter.java
// public class SectionFormatter implements Format<Sector> {
//
// private final Map<String, Sector> stringToSector;
// private final Map<Sector, String> sectorToString;
//
// public SectionFormatter() {
// stringToSector = new HashMap<>();
// sectorToString = new HashMap<>();
// addMapping("n/a", Sector.NotAvailable);
// addMapping("Technology", Sector.Technology);
// addMapping("Health Care", Sector.HealthCare);
// addMapping("Consumer Services", Sector.ConsumerServices);
// addMapping("Capital Goods", Sector.CapitalGoods);
// addMapping("Consumer Durables", Sector.ConsumerDurables);
// addMapping("Finance", Sector.Finance);
// addMapping("Consumer Non-Durables", Sector.ConsumerNonDurables);
// addMapping("Public Utilities", Sector.PublicUtilities);
// addMapping("Basic Industries", Sector.BasicIndustries);
// addMapping("Energy", Sector.Energy);
// addMapping("Miscellaneous", Sector.Miscellaneous);
// addMapping("Transportation", Sector.Transportation);
// }
//
// @Override
// public String format(Sector t) throws Exception {
// String sectorString = sectorToString.get(t);
// if (sectorString == null) {
// throw new IllegalArgumentException("Cannot format Sector '" + t.toString() + "'");
// }
// return sectorString;
// }
//
// @Override
// public Sector parse(String string) throws Exception {
// Sector sector = stringToSector.get(string);
// if (sector == null) {
// throw new IllegalArgumentException("Cannot parse Sector '" + string + "'");
// }
// return sector;
// }
//
// private void addMapping(String name, Sector sector) {
// stringToSector.put(name, sector);
// sectorToString.put(sector, name);
// }
//
// }
| import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.darugna.camel.csv.formatters.SectionFormatter; | package org.darugna.camel.csv.dto;
@XmlAccessorType(XmlAccessType.FIELD)
@CsvRecord(separator = ",")
public class SimpleCompany {
@XmlElement
@DataField(pos = 1)
String symbol;
@XmlAttribute
@DataField(pos = 2)
String name;
@XmlAttribute
@DataField(pos = 3) | // Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/formatters/SectionFormatter.java
// public class SectionFormatter implements Format<Sector> {
//
// private final Map<String, Sector> stringToSector;
// private final Map<Sector, String> sectorToString;
//
// public SectionFormatter() {
// stringToSector = new HashMap<>();
// sectorToString = new HashMap<>();
// addMapping("n/a", Sector.NotAvailable);
// addMapping("Technology", Sector.Technology);
// addMapping("Health Care", Sector.HealthCare);
// addMapping("Consumer Services", Sector.ConsumerServices);
// addMapping("Capital Goods", Sector.CapitalGoods);
// addMapping("Consumer Durables", Sector.ConsumerDurables);
// addMapping("Finance", Sector.Finance);
// addMapping("Consumer Non-Durables", Sector.ConsumerNonDurables);
// addMapping("Public Utilities", Sector.PublicUtilities);
// addMapping("Basic Industries", Sector.BasicIndustries);
// addMapping("Energy", Sector.Energy);
// addMapping("Miscellaneous", Sector.Miscellaneous);
// addMapping("Transportation", Sector.Transportation);
// }
//
// @Override
// public String format(Sector t) throws Exception {
// String sectorString = sectorToString.get(t);
// if (sectorString == null) {
// throw new IllegalArgumentException("Cannot format Sector '" + t.toString() + "'");
// }
// return sectorString;
// }
//
// @Override
// public Sector parse(String string) throws Exception {
// Sector sector = stringToSector.get(string);
// if (sector == null) {
// throw new IllegalArgumentException("Cannot parse Sector '" + string + "'");
// }
// return sector;
// }
//
// private void addMapping(String name, Sector sector) {
// stringToSector.put(name, sector);
// sectorToString.put(sector, name);
// }
//
// }
// Path: camel-blueprint-csv/src/main/java/org/darugna/camel/csv/dto/SimpleCompany.java
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.darugna.camel.csv.formatters.SectionFormatter;
package org.darugna.camel.csv.dto;
@XmlAccessorType(XmlAccessType.FIELD)
@CsvRecord(separator = ",")
public class SimpleCompany {
@XmlElement
@DataField(pos = 1)
String symbol;
@XmlAttribute
@DataField(pos = 2)
String name;
@XmlAttribute
@DataField(pos = 3) | @BindyConverter(SectionFormatter.class) |
darugnaa/apache-camel-examples | camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/GreetingProducerBean.java | // Path: camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/dto/Greeting.java
// public class Greeting {
//
// @Expose
// private String greeting;
// @Expose
// private LocalDateTime greetingDate;
// @Expose
// private Map<String,Integer> recipients;
//
// // keep away from marshalling
// private String toStringRepr;
//
// public String getGreeting() {
// return greeting;
// }
//
// public void setGreeting(String greeting) {
// this.greeting = greeting;
// }
//
// public LocalDateTime getGreetingDate() {
// return greetingDate;
// }
//
// public void setGreetingDateTime(LocalDateTime greetingDate) {
// this.greetingDate = greetingDate;
// }
//
// public Map<String, Integer> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(Map<String, Integer> recipients) {
// this.recipients = recipients;
// }
//
// public void addRecipient(String recipient, Integer numberOfGreets) {
// if (recipients == null) {
// recipients = new HashMap<>();
// }
// recipients.put(recipient, numberOfGreets);
// }
//
// @Override
// public String toString() {
// if (toStringRepr == null) {
// final StringBuilder sb = new StringBuilder();
// sb.append("On ").append(greetingDate)
// .append(" I said '").append(greeting).append("' to:");
// recipients.keySet().forEach(k -> {
// sb.append(" ").
// append(k).append(" ")
// .append(recipients.get(k))
// .append(" times.");
// });
// toStringRepr = sb.toString();
// }
// return toStringRepr;
// }
//
// }
| import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Random;
import java.util.stream.IntStream;
import org.darugna.camel.mqtt.dto.Greeting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.darugna.camel.mqtt;
public class GreetingProducerBean {
private final static Logger log = LoggerFactory.getLogger(GreetingProducerBean.class);
private final Random random = new Random();
// List of greetings. Original writings taken from Wikipedia.
private final String[] GREETINGS = {
"Hello!",
"Good morning",
"Ciao",
"Salaam (سَلَام)",
"Namaste (नमस्ते)",
"Konnichiwa (今日は)"
};
private final String[] NAMES = {
"Alessandro",
"Pete",
"Amit",
"Dracula"
};
| // Path: camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/dto/Greeting.java
// public class Greeting {
//
// @Expose
// private String greeting;
// @Expose
// private LocalDateTime greetingDate;
// @Expose
// private Map<String,Integer> recipients;
//
// // keep away from marshalling
// private String toStringRepr;
//
// public String getGreeting() {
// return greeting;
// }
//
// public void setGreeting(String greeting) {
// this.greeting = greeting;
// }
//
// public LocalDateTime getGreetingDate() {
// return greetingDate;
// }
//
// public void setGreetingDateTime(LocalDateTime greetingDate) {
// this.greetingDate = greetingDate;
// }
//
// public Map<String, Integer> getRecipients() {
// return recipients;
// }
//
// public void setRecipients(Map<String, Integer> recipients) {
// this.recipients = recipients;
// }
//
// public void addRecipient(String recipient, Integer numberOfGreets) {
// if (recipients == null) {
// recipients = new HashMap<>();
// }
// recipients.put(recipient, numberOfGreets);
// }
//
// @Override
// public String toString() {
// if (toStringRepr == null) {
// final StringBuilder sb = new StringBuilder();
// sb.append("On ").append(greetingDate)
// .append(" I said '").append(greeting).append("' to:");
// recipients.keySet().forEach(k -> {
// sb.append(" ").
// append(k).append(" ")
// .append(recipients.get(k))
// .append(" times.");
// });
// toStringRepr = sb.toString();
// }
// return toStringRepr;
// }
//
// }
// Path: camel-spring-mqtt/src/main/java/org/darugna/camel/mqtt/GreetingProducerBean.java
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Random;
import java.util.stream.IntStream;
import org.darugna.camel.mqtt.dto.Greeting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.darugna.camel.mqtt;
public class GreetingProducerBean {
private final static Logger log = LoggerFactory.getLogger(GreetingProducerBean.class);
private final Random random = new Random();
// List of greetings. Original writings taken from Wikipedia.
private final String[] GREETINGS = {
"Hello!",
"Good morning",
"Ciao",
"Salaam (سَلَام)",
"Namaste (नमस्ते)",
"Konnichiwa (今日は)"
};
private final String[] NAMES = {
"Alessandro",
"Pete",
"Amit",
"Dracula"
};
| public Greeting produce() { |
darugnaa/apache-camel-examples | camel-blueprint-route-as-a-service/raas-service-consumer/src/main/java/org/darugna/camel/raas/consumer/ConsumerBeanThatUsesService.java | // Path: camel-blueprint-route-as-a-service/raas-service-provider/src/main/java/org/darugna/camel/raas/CamelRaas.java
// public interface CamelRaas {
//
// Integer methodOne(@Body String arg0);
//
// Integer methodTwo(@Header("ARG0")String arg0,
// @Header("ARG1") String arg1);
//
// }
| import org.darugna.camel.raas.CamelRaas;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.darugna.camel.raas.consumer;
/**
* This bean as a reference to CamelRaas interface. It is injected in this context
* as an OSGi service. Each method call to this interface will invoke a Camel
* route.
*
* @author Alessandro Da Rugna ([email protected])
*/
public class ConsumerBeanThatUsesService {
private final static Logger log = LoggerFactory.getLogger(ConsumerBeanThatUsesService.class);
| // Path: camel-blueprint-route-as-a-service/raas-service-provider/src/main/java/org/darugna/camel/raas/CamelRaas.java
// public interface CamelRaas {
//
// Integer methodOne(@Body String arg0);
//
// Integer methodTwo(@Header("ARG0")String arg0,
// @Header("ARG1") String arg1);
//
// }
// Path: camel-blueprint-route-as-a-service/raas-service-consumer/src/main/java/org/darugna/camel/raas/consumer/ConsumerBeanThatUsesService.java
import org.darugna.camel.raas.CamelRaas;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.darugna.camel.raas.consumer;
/**
* This bean as a reference to CamelRaas interface. It is injected in this context
* as an OSGi service. Each method call to this interface will invoke a Camel
* route.
*
* @author Alessandro Da Rugna ([email protected])
*/
public class ConsumerBeanThatUsesService {
private final static Logger log = LoggerFactory.getLogger(ConsumerBeanThatUsesService.class);
| private CamelRaas camelRaas; |
fengyouchao/sockslib | src/main/java/sockslib/server/msg/MethodSelectionResponseMessage.java | // Path: src/main/java/sockslib/common/methods/SocksMethod.java
// public interface SocksMethod {
//
// /**
// * method byte.
// *
// * @return byte.
// */
// int getByte();
//
// /**
// * Gets method's name.
// *
// * @return Name of the method.
// */
// String getMethodName();
//
// /**
// * Do method job. This method will be called by SOCKS client.
// *
// * @param socksProxy SocksProxy instance.
// * @throws SocksException If there are any errors about SOCKS protocol.
// * @throws IOException if there are any IO errors.
// */
// void doMethod(SocksProxy socksProxy) throws SocksException, IOException;
//
// /**
// * Do method job. This method will be called by SOCKS server.
// *
// * @param session Session.
// * @throws SocksException TODO
// * @throws IOException TODO
// */
// void doMethod(Session session) throws SocksException, IOException;
//
// }
| import sockslib.common.methods.SocksMethod; | /*
* Copyright 2015-2025 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 sockslib.server.msg;
/**
* The class <code>MethodSelectionResponseMessage</code> represents response message for method
* selection message. This message is always sent by SOCKS server.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 6, 2015 11:10:05 AM
*/
public class MethodSelectionResponseMessage implements WritableMessage {
/**
* Version. 5 is default.
*/
private int version = 5;
/**
* Selected method. 0xFF is default.
*/
private int method = 0xFF;
/**
* Constructs an instance of {@link MethodSelectionResponseMessage}
*/
public MethodSelectionResponseMessage() {
}
/**
* Constructs an instance of {@link MethodSelectionResponseMessage} with a method.
*
* @param socksMethod Selected method.
*/ | // Path: src/main/java/sockslib/common/methods/SocksMethod.java
// public interface SocksMethod {
//
// /**
// * method byte.
// *
// * @return byte.
// */
// int getByte();
//
// /**
// * Gets method's name.
// *
// * @return Name of the method.
// */
// String getMethodName();
//
// /**
// * Do method job. This method will be called by SOCKS client.
// *
// * @param socksProxy SocksProxy instance.
// * @throws SocksException If there are any errors about SOCKS protocol.
// * @throws IOException if there are any IO errors.
// */
// void doMethod(SocksProxy socksProxy) throws SocksException, IOException;
//
// /**
// * Do method job. This method will be called by SOCKS server.
// *
// * @param session Session.
// * @throws SocksException TODO
// * @throws IOException TODO
// */
// void doMethod(Session session) throws SocksException, IOException;
//
// }
// Path: src/main/java/sockslib/server/msg/MethodSelectionResponseMessage.java
import sockslib.common.methods.SocksMethod;
/*
* Copyright 2015-2025 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 sockslib.server.msg;
/**
* The class <code>MethodSelectionResponseMessage</code> represents response message for method
* selection message. This message is always sent by SOCKS server.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 6, 2015 11:10:05 AM
*/
public class MethodSelectionResponseMessage implements WritableMessage {
/**
* Version. 5 is default.
*/
private int version = 5;
/**
* Selected method. 0xFF is default.
*/
private int method = 0xFF;
/**
* Constructs an instance of {@link MethodSelectionResponseMessage}
*/
public MethodSelectionResponseMessage() {
}
/**
* Constructs an instance of {@link MethodSelectionResponseMessage} with a method.
*
* @param socksMethod Selected method.
*/ | public MethodSelectionResponseMessage(SocksMethod socksMethod) { |
fengyouchao/sockslib | src/main/java/sockslib/server/SSLSocksProxyServer.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
| import sockslib.common.SSLConfiguration;
import sockslib.common.SocksException;
import javax.net.ssl.SSLServerSocket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | /*
* Copyright 2015-2025 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 sockslib.server;
/**
* The class <code>SSLSocksProxyServer</code> represents a SSL based SOCKS proxy server.
*
* @author Youchao Feng
* @version 1.0
* @date May 17, 2015 4:08:06 PM
*/
public class SSLSocksProxyServer extends BasicSocksProxyServer {
private SSLConfiguration configuration;
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, ExecutorService
executorService, SSLConfiguration configuration) {
this(socketHandlerClass, DEFAULT_SOCKS_PORT, executorService, configuration);
}
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, int port,
ExecutorService executorService, SSLConfiguration configuration) {
super(socketHandlerClass, port, executorService);
this.configuration = configuration;
}
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, int port,
SSLConfiguration configuration) {
this(socketHandlerClass, port, Executors.newFixedThreadPool(THREAD_NUMBER), configuration);
}
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, SSLConfiguration
configuration) {
this(socketHandlerClass, DEFAULT_SOCKS_PORT, Executors.newFixedThreadPool(THREAD_NUMBER),
configuration);
}
@Override
protected ServerSocket createServerSocket(int bindPort, InetAddress bindAddr) throws IOException {
try {
return createSSLServer(bindPort, bindAddr);
} catch (Exception e) { | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
// Path: src/main/java/sockslib/server/SSLSocksProxyServer.java
import sockslib.common.SSLConfiguration;
import sockslib.common.SocksException;
import javax.net.ssl.SSLServerSocket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* Copyright 2015-2025 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 sockslib.server;
/**
* The class <code>SSLSocksProxyServer</code> represents a SSL based SOCKS proxy server.
*
* @author Youchao Feng
* @version 1.0
* @date May 17, 2015 4:08:06 PM
*/
public class SSLSocksProxyServer extends BasicSocksProxyServer {
private SSLConfiguration configuration;
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, ExecutorService
executorService, SSLConfiguration configuration) {
this(socketHandlerClass, DEFAULT_SOCKS_PORT, executorService, configuration);
}
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, int port,
ExecutorService executorService, SSLConfiguration configuration) {
super(socketHandlerClass, port, executorService);
this.configuration = configuration;
}
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, int port,
SSLConfiguration configuration) {
this(socketHandlerClass, port, Executors.newFixedThreadPool(THREAD_NUMBER), configuration);
}
public SSLSocksProxyServer(Class<? extends SocksHandler> socketHandlerClass, SSLConfiguration
configuration) {
this(socketHandlerClass, DEFAULT_SOCKS_PORT, Executors.newFixedThreadPool(THREAD_NUMBER),
configuration);
}
@Override
protected ServerSocket createServerSocket(int bindPort, InetAddress bindAddr) throws IOException {
try {
return createSSLServer(bindPort, bindAddr);
} catch (Exception e) { | throw new SocksException(e.getMessage()); |
fengyouchao/sockslib | src/main/java/sockslib/client/SocksProxyFactory.java | // Path: src/main/java/sockslib/common/KeyStoreInfo.java
// public class KeyStoreInfo {
//
// private String keyStorePath;
// private String password;
// private String type = "JKS";
//
// public KeyStoreInfo() {
// }
//
// public KeyStoreInfo(String keyStorePath, String password, String type) {
// this.keyStorePath = checkNotNull(keyStorePath, "Argument [keyStorePath] may not be null");
// this.password = checkNotNull(password, "Argument [password] may not be null");
// this.type = checkNotNull(type, "Argument [type] may not be null");
// }
//
// public KeyStoreInfo(String keyStorePath, String password) {
// this(keyStorePath, password, "JKS");
// }
//
// public String getKeyStorePath() {
// return keyStorePath;
// }
//
// public KeyStoreInfo setKeyStorePath(String keyStorePath) {
// this.keyStorePath = checkNotNull(keyStorePath);
// return this;
// }
//
// public String getPassword() {
// return password;
// }
//
// public KeyStoreInfo setPassword(String password) {
// this.password = password;
// return this;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = checkNotNull(type);
// }
//
// @Override
// public String toString() {
// return "[KEY STORE] PATH:" + keyStorePath + " PASSWORD:" + password + " TYPE:" + type;
// }
//
// }
| import com.google.common.base.Strings;
import sockslib.common.Credentials;
import sockslib.common.KeyStoreInfo;
import sockslib.common.SSLConfiguration;
import sockslib.common.UsernamePasswordCredentials;
import sockslib.utils.PathUtil;
import java.io.FileNotFoundException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException; | /*
* Copyright 2015-2025 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 sockslib.client;
/**
* The class <code>SocksFactory</code> represents a factory that can build {@link SocksProxy}
* instance.
*
* @author Youchao Feng
* @version 1.0
* @since 1.0
*/
public class SocksProxyFactory {
/**
* Creates a {@link SocksProxy} instance with a string.<br>
* For example:<br>
* <ul>
* <li>host,1080 = {@link Socks5#Socks5(String, int)}</li>
* <li>host,1080,root,123456 = {@link Socks5#Socks5(String, int, Credentials)}</li>
* <li>host,1080,root,123456,trustKeyStorePath,trustKeyStorePassword = Creates a
* {@link SSLSocks5} instance</li>
* <li>host,1080,root,123456,trustKeyStorePath,trustKeyStorePassword,keyStorePath,
* keystorePathPassword = Creates a {@link SSLSocks5} instance which supports client
* authentication</li>
* </ul>
*
* @param value a string.
* @return a {@link SocksProxy} instance.
* @throws UnknownHostException if the host is unknown.
* @throws FileNotFoundException if file not found.
*/
public static SocksProxy parse(String value) throws UnknownHostException, FileNotFoundException {
SocksProxy socks = null;
String host;
int port;
String username;
String password; | // Path: src/main/java/sockslib/common/KeyStoreInfo.java
// public class KeyStoreInfo {
//
// private String keyStorePath;
// private String password;
// private String type = "JKS";
//
// public KeyStoreInfo() {
// }
//
// public KeyStoreInfo(String keyStorePath, String password, String type) {
// this.keyStorePath = checkNotNull(keyStorePath, "Argument [keyStorePath] may not be null");
// this.password = checkNotNull(password, "Argument [password] may not be null");
// this.type = checkNotNull(type, "Argument [type] may not be null");
// }
//
// public KeyStoreInfo(String keyStorePath, String password) {
// this(keyStorePath, password, "JKS");
// }
//
// public String getKeyStorePath() {
// return keyStorePath;
// }
//
// public KeyStoreInfo setKeyStorePath(String keyStorePath) {
// this.keyStorePath = checkNotNull(keyStorePath);
// return this;
// }
//
// public String getPassword() {
// return password;
// }
//
// public KeyStoreInfo setPassword(String password) {
// this.password = password;
// return this;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = checkNotNull(type);
// }
//
// @Override
// public String toString() {
// return "[KEY STORE] PATH:" + keyStorePath + " PASSWORD:" + password + " TYPE:" + type;
// }
//
// }
// Path: src/main/java/sockslib/client/SocksProxyFactory.java
import com.google.common.base.Strings;
import sockslib.common.Credentials;
import sockslib.common.KeyStoreInfo;
import sockslib.common.SSLConfiguration;
import sockslib.common.UsernamePasswordCredentials;
import sockslib.utils.PathUtil;
import java.io.FileNotFoundException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
/*
* Copyright 2015-2025 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 sockslib.client;
/**
* The class <code>SocksFactory</code> represents a factory that can build {@link SocksProxy}
* instance.
*
* @author Youchao Feng
* @version 1.0
* @since 1.0
*/
public class SocksProxyFactory {
/**
* Creates a {@link SocksProxy} instance with a string.<br>
* For example:<br>
* <ul>
* <li>host,1080 = {@link Socks5#Socks5(String, int)}</li>
* <li>host,1080,root,123456 = {@link Socks5#Socks5(String, int, Credentials)}</li>
* <li>host,1080,root,123456,trustKeyStorePath,trustKeyStorePassword = Creates a
* {@link SSLSocks5} instance</li>
* <li>host,1080,root,123456,trustKeyStorePath,trustKeyStorePassword,keyStorePath,
* keystorePathPassword = Creates a {@link SSLSocks5} instance which supports client
* authentication</li>
* </ul>
*
* @param value a string.
* @return a {@link SocksProxy} instance.
* @throws UnknownHostException if the host is unknown.
* @throws FileNotFoundException if file not found.
*/
public static SocksProxy parse(String value) throws UnknownHostException, FileNotFoundException {
SocksProxy socks = null;
String host;
int port;
String username;
String password; | KeyStoreInfo trustKeyStoreInfo; |
fengyouchao/sockslib | src/main/java/sockslib/client/SocksSocket.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import sockslib.common.SocksException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright 2015-2025 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 sockslib.client;
/**
* The class <code>SocksSocket</code> is proxy class that help developers use {@link SocksProxy} as
* same as a java.net.Socket.<br>
* For example:<br>
* <pre>
* SocksProxy proxy = new Socks5(new InetSocketAddress("127.0.0.1", 1080));
* // Setting proxy...
* Socket socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net",
* 43));
* InputStream inputStream = socket.getInputStream();
* OutputStream outStream = socket.getOutputStream();
* // Just use the socket as normal java.net.Socket now.
* </pre>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 18, 2015 5:02:31 PM
*/
public class SocksSocket extends Socket {
protected static final Logger logger = LoggerFactory.getLogger(SocksSocket.class);
private SocksProxy proxy;
private String remoteServerHost;
private int remoteServerPort;
/**
* Socket that will connect to SOCKS server.
*/
private Socket proxySocket;
/**
* Create a socket and connect SOCKS Server.
*
* @param proxy Socks proxy.
* @param remoteServerHost Remote sever host.
* @param remoteServerPort Remote server port.
* @throws SocksException If any errors about SOCKS protocol occurred.
* @throws IOException If any IO errors occurred.
*/
public SocksSocket(SocksProxy proxy, String remoteServerHost, int remoteServerPort) throws | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
// Path: src/main/java/sockslib/client/SocksSocket.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import sockslib.common.SocksException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright 2015-2025 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 sockslib.client;
/**
* The class <code>SocksSocket</code> is proxy class that help developers use {@link SocksProxy} as
* same as a java.net.Socket.<br>
* For example:<br>
* <pre>
* SocksProxy proxy = new Socks5(new InetSocketAddress("127.0.0.1", 1080));
* // Setting proxy...
* Socket socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net",
* 43));
* InputStream inputStream = socket.getInputStream();
* OutputStream outStream = socket.getOutputStream();
* // Just use the socket as normal java.net.Socket now.
* </pre>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 18, 2015 5:02:31 PM
*/
public class SocksSocket extends Socket {
protected static final Logger logger = LoggerFactory.getLogger(SocksSocket.class);
private SocksProxy proxy;
private String remoteServerHost;
private int remoteServerPort;
/**
* Socket that will connect to SOCKS server.
*/
private Socket proxySocket;
/**
* Create a socket and connect SOCKS Server.
*
* @param proxy Socks proxy.
* @param remoteServerHost Remote sever host.
* @param remoteServerPort Remote server port.
* @throws SocksException If any errors about SOCKS protocol occurred.
* @throws IOException If any IO errors occurred.
*/
public SocksSocket(SocksProxy proxy, String remoteServerHost, int remoteServerPort) throws | SocksException, IOException { |
fengyouchao/sockslib | src/main/java/sockslib/common/methods/NoAcceptableMethod.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
| import sockslib.client.SocksProxy;
import sockslib.common.SocksException;
import sockslib.server.Session;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull; | /*
* Copyright 2015-2025 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 sockslib.common.methods;
/**
* The class <code>NoAcceptableMethod</code> represents a method which indicates none of the methods
* listed by the client are acceptable.
* <p>
* When server replies this method, the client should disconnect SOCKS server and throw
* {@link SocksException}.
* </p>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 18, 2015 11:15:46 AM
* @see AbstractSocksMethod
* @see <a href="http://www.ietf.org/rfc/rfc1928.txt">SOCKS Protocol Version 5</a>
*/
public class NoAcceptableMethod extends AbstractSocksMethod {
@Override
public final int getByte() {
return 0xFF;
}
@Override | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
// Path: src/main/java/sockslib/common/methods/NoAcceptableMethod.java
import sockslib.client.SocksProxy;
import sockslib.common.SocksException;
import sockslib.server.Session;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
/*
* Copyright 2015-2025 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 sockslib.common.methods;
/**
* The class <code>NoAcceptableMethod</code> represents a method which indicates none of the methods
* listed by the client are acceptable.
* <p>
* When server replies this method, the client should disconnect SOCKS server and throw
* {@link SocksException}.
* </p>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 18, 2015 11:15:46 AM
* @see AbstractSocksMethod
* @see <a href="http://www.ietf.org/rfc/rfc1928.txt">SOCKS Protocol Version 5</a>
*/
public class NoAcceptableMethod extends AbstractSocksMethod {
@Override
public final int getByte() {
return 0xFF;
}
@Override | public void doMethod(SocksProxy socksProxy) throws SocksException, IOException { |
fengyouchao/sockslib | src/main/java/sockslib/server/msg/MethodSelectionMessage.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
//
// Path: src/main/java/sockslib/utils/StreamUtil.java
// public static int checkEnd(int b) throws IOException {
// if (b < 0) {
// throw new IOException("End of stream");
// } else {
// return b;
// }
// }
| import sockslib.common.SocksException;
import java.io.IOException;
import java.io.InputStream;
import static sockslib.utils.StreamUtil.checkEnd; | /*
* Copyright 2015-2025 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 sockslib.server.msg;
/**
* The class <code>MethodSelectionMessage</code> represents a method selection message.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 5, 2015 10:47:05 AM
*/
public class MethodSelectionMessage implements ReadableMessage, WritableMessage {
private int version;
private int methodNum;
private int[] methods;
@Override
public byte[] getBytes() {
byte[] bytes = new byte[2 + methodNum];
bytes[0] = (byte) version;
bytes[1] = (byte) methodNum;
for (int i = 0; i < methods.length; i++) {
bytes[i + 2] = (byte) methods[i];
}
return bytes;
}
@Override
public int getLength() {
return getBytes().length;
}
@Override | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
//
// Path: src/main/java/sockslib/utils/StreamUtil.java
// public static int checkEnd(int b) throws IOException {
// if (b < 0) {
// throw new IOException("End of stream");
// } else {
// return b;
// }
// }
// Path: src/main/java/sockslib/server/msg/MethodSelectionMessage.java
import sockslib.common.SocksException;
import java.io.IOException;
import java.io.InputStream;
import static sockslib.utils.StreamUtil.checkEnd;
/*
* Copyright 2015-2025 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 sockslib.server.msg;
/**
* The class <code>MethodSelectionMessage</code> represents a method selection message.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 5, 2015 10:47:05 AM
*/
public class MethodSelectionMessage implements ReadableMessage, WritableMessage {
private int version;
private int methodNum;
private int[] methods;
@Override
public byte[] getBytes() {
byte[] bytes = new byte[2 + methodNum];
bytes[0] = (byte) version;
bytes[1] = (byte) methodNum;
for (int i = 0; i < methods.length; i++) {
bytes[i + 2] = (byte) methods[i];
}
return bytes;
}
@Override
public int getLength() {
return getBytes().length;
}
@Override | public void read(InputStream inputStream) throws SocksException, IOException { |
fengyouchao/sockslib | src/main/java/sockslib/server/msg/MethodSelectionMessage.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
//
// Path: src/main/java/sockslib/utils/StreamUtil.java
// public static int checkEnd(int b) throws IOException {
// if (b < 0) {
// throw new IOException("End of stream");
// } else {
// return b;
// }
// }
| import sockslib.common.SocksException;
import java.io.IOException;
import java.io.InputStream;
import static sockslib.utils.StreamUtil.checkEnd; | /*
* Copyright 2015-2025 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 sockslib.server.msg;
/**
* The class <code>MethodSelectionMessage</code> represents a method selection message.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 5, 2015 10:47:05 AM
*/
public class MethodSelectionMessage implements ReadableMessage, WritableMessage {
private int version;
private int methodNum;
private int[] methods;
@Override
public byte[] getBytes() {
byte[] bytes = new byte[2 + methodNum];
bytes[0] = (byte) version;
bytes[1] = (byte) methodNum;
for (int i = 0; i < methods.length; i++) {
bytes[i + 2] = (byte) methods[i];
}
return bytes;
}
@Override
public int getLength() {
return getBytes().length;
}
@Override
public void read(InputStream inputStream) throws SocksException, IOException { | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
//
// Path: src/main/java/sockslib/utils/StreamUtil.java
// public static int checkEnd(int b) throws IOException {
// if (b < 0) {
// throw new IOException("End of stream");
// } else {
// return b;
// }
// }
// Path: src/main/java/sockslib/server/msg/MethodSelectionMessage.java
import sockslib.common.SocksException;
import java.io.IOException;
import java.io.InputStream;
import static sockslib.utils.StreamUtil.checkEnd;
/*
* Copyright 2015-2025 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 sockslib.server.msg;
/**
* The class <code>MethodSelectionMessage</code> represents a method selection message.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 5, 2015 10:47:05 AM
*/
public class MethodSelectionMessage implements ReadableMessage, WritableMessage {
private int version;
private int methodNum;
private int[] methods;
@Override
public byte[] getBytes() {
byte[] bytes = new byte[2 + methodNum];
bytes[0] = (byte) version;
bytes[1] = (byte) methodNum;
for (int i = 0; i < methods.length; i++) {
bytes[i + 2] = (byte) methods[i];
}
return bytes;
}
@Override
public int getLength() {
return getBytes().length;
}
@Override
public void read(InputStream inputStream) throws SocksException, IOException { | version = checkEnd(inputStream.read()); |
fengyouchao/sockslib | src/test/java/sockslib/example/AnonymousSocks5Server.java | // Path: src/main/java/sockslib/server/SocksProxyServer.java
// public interface SocksProxyServer {
//
// /**
// * SOCKS server default port.
// */
// int DEFAULT_SOCKS_PORT = 1080;
//
// /**
// * Starts a SOCKS server.
// *
// * @throws IOException If any I/O error occurs.
// */
// void start() throws IOException;
//
// /**
// * Shutdown a SOCKS server.
// */
// void shutdown();
//
// /**
// * Create an instance {@link SocksHandler}.
// *
// * @return Instance of {@link SocksHandler}.
// */
// SocksHandler createSocksHandler();
//
// /**
// * Initializes {@link SocksHandler}.
// *
// * @param socksHandler The instance of {@link SocksHandler}.
// */
// void initializeSocksHandler(SocksHandler socksHandler);
//
// /**
// * Sets the methods that socks server supports.
// *
// * @param methods The methods that SOCKS server sports.
// */
// void setSupportMethods(SocksMethod... methods);
//
// /**
// * Gets all sessions that SOCKS server managed.
// *
// * @return All sessions that SOCKS server managed.
// */
// Map<Long, Session> getManagedSessions();
//
// /**
// * Returns buffer size.
// *
// * @return Buffer size.
// */
// int getBufferSize();
//
// /**
// * Sets buffer size.
// *
// * @param bufferSize Buffer size.
// */
// void setBufferSize(int bufferSize);
//
// /**
// * Returns timeout.
// *
// * @return Timeout.
// */
// int getTimeout();
//
// /**
// * Sets timeout.
// *
// * @param timeout timeout.
// */
// void setTimeout(int timeout);
//
// /**
// * Returns server's proxy.
// *
// * @return Server's proxy.
// */
// SocksProxy getProxy();
//
// /**
// * Set server proxy.
// *
// * @param proxy Proxy server will use.
// */
// void setProxy(SocksProxy proxy);
//
// /**
// * Sets thread pool.
// *
// * @param executeService Thread pool.
// */
// void setExecutorService(ExecutorService executeService);
//
// /**
// * Returns server bind addr.
// *
// * @return Server bind addr.
// */
// InetAddress getBindAddr();
//
// /**
// * Returns server bind port.
// *
// * @return Server bind port.
// */
// int getBindPort();
//
// /**
// * Sets server bind addr
// *
// * @param bindAddr Bind addr.
// */
// void setBindAddr(InetAddress bindAddr);
//
// /**
// * Sets server bind port
// *
// * @param bindPort Bind port.
// */
// void setBindPort(int bindPort);
//
// /**
// * Returns <code>true</code> if the server run in daemon thread.
// *
// * @return <code>true</code> if the server run in daemon thread.
// */
// boolean isDaemon();
//
// /**
// * Sets <code>true</code> the server will run in daemon thread.
// *
// * @param daemon Daemon thread
// */
// void setDaemon(boolean daemon);
//
// /**
// * Returns {@link SessionManager}
// *
// * @return {@link SessionManager}
// */
// SessionManager getSessionManager();
//
// /**
// * Sets {@link SessionManager}
// *
// * @param sessionManager {@link SessionManager}
// */
// void setSessionManager(SessionManager sessionManager);
//
// PipeInitializer getPipeInitializer();
//
// void setPipeInitializer(PipeInitializer pipeInitializer);
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sockslib.server.SessionManager;
import sockslib.server.SocksProxyServer;
import sockslib.server.SocksServerBuilder;
import sockslib.server.listener.LoggingListener;
import sockslib.utils.Timer;
import java.io.IOException; | /*
* Copyright 2015-2025 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 sockslib.example;
/**
* The class <code>AnonymousSocks5Server</code> a test class to start a SOCKS5 proxy server.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 19, 2015 11:43:22 PM
*/
public class AnonymousSocks5Server {
private static final Logger logger = LoggerFactory.getLogger(AnonymousSocks5Server.class);
public static void main(String[] args) throws IOException {
Timer.open(); | // Path: src/main/java/sockslib/server/SocksProxyServer.java
// public interface SocksProxyServer {
//
// /**
// * SOCKS server default port.
// */
// int DEFAULT_SOCKS_PORT = 1080;
//
// /**
// * Starts a SOCKS server.
// *
// * @throws IOException If any I/O error occurs.
// */
// void start() throws IOException;
//
// /**
// * Shutdown a SOCKS server.
// */
// void shutdown();
//
// /**
// * Create an instance {@link SocksHandler}.
// *
// * @return Instance of {@link SocksHandler}.
// */
// SocksHandler createSocksHandler();
//
// /**
// * Initializes {@link SocksHandler}.
// *
// * @param socksHandler The instance of {@link SocksHandler}.
// */
// void initializeSocksHandler(SocksHandler socksHandler);
//
// /**
// * Sets the methods that socks server supports.
// *
// * @param methods The methods that SOCKS server sports.
// */
// void setSupportMethods(SocksMethod... methods);
//
// /**
// * Gets all sessions that SOCKS server managed.
// *
// * @return All sessions that SOCKS server managed.
// */
// Map<Long, Session> getManagedSessions();
//
// /**
// * Returns buffer size.
// *
// * @return Buffer size.
// */
// int getBufferSize();
//
// /**
// * Sets buffer size.
// *
// * @param bufferSize Buffer size.
// */
// void setBufferSize(int bufferSize);
//
// /**
// * Returns timeout.
// *
// * @return Timeout.
// */
// int getTimeout();
//
// /**
// * Sets timeout.
// *
// * @param timeout timeout.
// */
// void setTimeout(int timeout);
//
// /**
// * Returns server's proxy.
// *
// * @return Server's proxy.
// */
// SocksProxy getProxy();
//
// /**
// * Set server proxy.
// *
// * @param proxy Proxy server will use.
// */
// void setProxy(SocksProxy proxy);
//
// /**
// * Sets thread pool.
// *
// * @param executeService Thread pool.
// */
// void setExecutorService(ExecutorService executeService);
//
// /**
// * Returns server bind addr.
// *
// * @return Server bind addr.
// */
// InetAddress getBindAddr();
//
// /**
// * Returns server bind port.
// *
// * @return Server bind port.
// */
// int getBindPort();
//
// /**
// * Sets server bind addr
// *
// * @param bindAddr Bind addr.
// */
// void setBindAddr(InetAddress bindAddr);
//
// /**
// * Sets server bind port
// *
// * @param bindPort Bind port.
// */
// void setBindPort(int bindPort);
//
// /**
// * Returns <code>true</code> if the server run in daemon thread.
// *
// * @return <code>true</code> if the server run in daemon thread.
// */
// boolean isDaemon();
//
// /**
// * Sets <code>true</code> the server will run in daemon thread.
// *
// * @param daemon Daemon thread
// */
// void setDaemon(boolean daemon);
//
// /**
// * Returns {@link SessionManager}
// *
// * @return {@link SessionManager}
// */
// SessionManager getSessionManager();
//
// /**
// * Sets {@link SessionManager}
// *
// * @param sessionManager {@link SessionManager}
// */
// void setSessionManager(SessionManager sessionManager);
//
// PipeInitializer getPipeInitializer();
//
// void setPipeInitializer(PipeInitializer pipeInitializer);
// }
// Path: src/test/java/sockslib/example/AnonymousSocks5Server.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sockslib.server.SessionManager;
import sockslib.server.SocksProxyServer;
import sockslib.server.SocksServerBuilder;
import sockslib.server.listener.LoggingListener;
import sockslib.utils.Timer;
import java.io.IOException;
/*
* Copyright 2015-2025 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 sockslib.example;
/**
* The class <code>AnonymousSocks5Server</code> a test class to start a SOCKS5 proxy server.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 19, 2015 11:43:22 PM
*/
public class AnonymousSocks5Server {
private static final Logger logger = LoggerFactory.getLogger(AnonymousSocks5Server.class);
public static void main(String[] args) throws IOException {
Timer.open(); | SocksProxyServer proxyServer = SocksServerBuilder.buildAnonymousSocks5Server(); |
fengyouchao/sockslib | src/main/java/sockslib/server/SocksProxyServer.java | // Path: src/main/java/sockslib/common/methods/SocksMethod.java
// public interface SocksMethod {
//
// /**
// * method byte.
// *
// * @return byte.
// */
// int getByte();
//
// /**
// * Gets method's name.
// *
// * @return Name of the method.
// */
// String getMethodName();
//
// /**
// * Do method job. This method will be called by SOCKS client.
// *
// * @param socksProxy SocksProxy instance.
// * @throws SocksException If there are any errors about SOCKS protocol.
// * @throws IOException if there are any IO errors.
// */
// void doMethod(SocksProxy socksProxy) throws SocksException, IOException;
//
// /**
// * Do method job. This method will be called by SOCKS server.
// *
// * @param session Session.
// * @throws SocksException TODO
// * @throws IOException TODO
// */
// void doMethod(Session session) throws SocksException, IOException;
//
// }
| import sockslib.client.SocksProxy;
import sockslib.common.methods.SocksMethod;
import sockslib.server.listener.PipeInitializer;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ExecutorService; | /*
* Copyright 2015-2025 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 sockslib.server;
/**
* The interface <code>SocksProxyServer</code> represents a SOCKS server.
*
* @author Youchao Feng
* @version 1.0
* @date Mar 25, 2015 10:07:29 AM
*/
public interface SocksProxyServer {
/**
* SOCKS server default port.
*/
int DEFAULT_SOCKS_PORT = 1080;
/**
* Starts a SOCKS server.
*
* @throws IOException If any I/O error occurs.
*/
void start() throws IOException;
/**
* Shutdown a SOCKS server.
*/
void shutdown();
/**
* Create an instance {@link SocksHandler}.
*
* @return Instance of {@link SocksHandler}.
*/
SocksHandler createSocksHandler();
/**
* Initializes {@link SocksHandler}.
*
* @param socksHandler The instance of {@link SocksHandler}.
*/
void initializeSocksHandler(SocksHandler socksHandler);
/**
* Sets the methods that socks server supports.
*
* @param methods The methods that SOCKS server sports.
*/ | // Path: src/main/java/sockslib/common/methods/SocksMethod.java
// public interface SocksMethod {
//
// /**
// * method byte.
// *
// * @return byte.
// */
// int getByte();
//
// /**
// * Gets method's name.
// *
// * @return Name of the method.
// */
// String getMethodName();
//
// /**
// * Do method job. This method will be called by SOCKS client.
// *
// * @param socksProxy SocksProxy instance.
// * @throws SocksException If there are any errors about SOCKS protocol.
// * @throws IOException if there are any IO errors.
// */
// void doMethod(SocksProxy socksProxy) throws SocksException, IOException;
//
// /**
// * Do method job. This method will be called by SOCKS server.
// *
// * @param session Session.
// * @throws SocksException TODO
// * @throws IOException TODO
// */
// void doMethod(Session session) throws SocksException, IOException;
//
// }
// Path: src/main/java/sockslib/server/SocksProxyServer.java
import sockslib.client.SocksProxy;
import sockslib.common.methods.SocksMethod;
import sockslib.server.listener.PipeInitializer;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ExecutorService;
/*
* Copyright 2015-2025 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 sockslib.server;
/**
* The interface <code>SocksProxyServer</code> represents a SOCKS server.
*
* @author Youchao Feng
* @version 1.0
* @date Mar 25, 2015 10:07:29 AM
*/
public interface SocksProxyServer {
/**
* SOCKS server default port.
*/
int DEFAULT_SOCKS_PORT = 1080;
/**
* Starts a SOCKS server.
*
* @throws IOException If any I/O error occurs.
*/
void start() throws IOException;
/**
* Shutdown a SOCKS server.
*/
void shutdown();
/**
* Create an instance {@link SocksHandler}.
*
* @return Instance of {@link SocksHandler}.
*/
SocksHandler createSocksHandler();
/**
* Initializes {@link SocksHandler}.
*
* @param socksHandler The instance of {@link SocksHandler}.
*/
void initializeSocksHandler(SocksHandler socksHandler);
/**
* Sets the methods that socks server supports.
*
* @param methods The methods that SOCKS server sports.
*/ | void setSupportMethods(SocksMethod... methods); |
fengyouchao/sockslib | src/main/java/sockslib/common/methods/SocksMethod.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
| import sockslib.client.SocksProxy;
import sockslib.common.SocksException;
import sockslib.server.Session;
import java.io.IOException; | /*
* Copyright 2015-2025 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 sockslib.common.methods;
/**
* The interface <code>SocksMethod</code> define a socks method in SOCKS4 or SOCKS5 protocol.<br>
* <br>
* SOCKS5 protocol in RFC 1928:<br>
* The values currently defined for METHOD are:
* <ul>
* <li>X’00’ NO AUTHENTICATION REQUIRED</li>
* <li>X’01’ GSSAPI</li>
* <li>X’02’ USERNAME/PASSWORD</li>
* <li>X’03’ to X’7F’ IANA ASSIGNED</li>
* <li>X’80’ to X’FE’ RESERVED FOR PRIVATE METHODS</li>
* <li>X’FF’ NO ACCEPTABLE METHODS</li>
* </ul>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 17, 2015 11:12:16 AM
* @see AbstractSocksMethod
* @see GssApiMethod
* @see NoAcceptableMethod
* @see NoAuthenticationRequiredMethod
* @see UsernamePasswordMethod
* @see <a href="http://www.ietf.org/rfc/rfc1928.txt">SOCKS Protocol Version 5</a>
*/
public interface SocksMethod {
/**
* method byte.
*
* @return byte.
*/
int getByte();
/**
* Gets method's name.
*
* @return Name of the method.
*/
String getMethodName();
/**
* Do method job. This method will be called by SOCKS client.
*
* @param socksProxy SocksProxy instance.
* @throws SocksException If there are any errors about SOCKS protocol.
* @throws IOException if there are any IO errors.
*/ | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
// Path: src/main/java/sockslib/common/methods/SocksMethod.java
import sockslib.client.SocksProxy;
import sockslib.common.SocksException;
import sockslib.server.Session;
import java.io.IOException;
/*
* Copyright 2015-2025 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 sockslib.common.methods;
/**
* The interface <code>SocksMethod</code> define a socks method in SOCKS4 or SOCKS5 protocol.<br>
* <br>
* SOCKS5 protocol in RFC 1928:<br>
* The values currently defined for METHOD are:
* <ul>
* <li>X’00’ NO AUTHENTICATION REQUIRED</li>
* <li>X’01’ GSSAPI</li>
* <li>X’02’ USERNAME/PASSWORD</li>
* <li>X’03’ to X’7F’ IANA ASSIGNED</li>
* <li>X’80’ to X’FE’ RESERVED FOR PRIVATE METHODS</li>
* <li>X’FF’ NO ACCEPTABLE METHODS</li>
* </ul>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 17, 2015 11:12:16 AM
* @see AbstractSocksMethod
* @see GssApiMethod
* @see NoAcceptableMethod
* @see NoAuthenticationRequiredMethod
* @see UsernamePasswordMethod
* @see <a href="http://www.ietf.org/rfc/rfc1928.txt">SOCKS Protocol Version 5</a>
*/
public interface SocksMethod {
/**
* method byte.
*
* @return byte.
*/
int getByte();
/**
* Gets method's name.
*
* @return Name of the method.
*/
String getMethodName();
/**
* Do method job. This method will be called by SOCKS client.
*
* @param socksProxy SocksProxy instance.
* @throws SocksException If there are any errors about SOCKS protocol.
* @throws IOException if there are any IO errors.
*/ | void doMethod(SocksProxy socksProxy) throws SocksException, IOException; |
fengyouchao/sockslib | src/main/java/sockslib/client/SocksServerSocket.java | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
| import sockslib.common.SocksException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress; | /*
* Copyright 2015-2025 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 sockslib.client;
/**
* The class <code>SocksServerSocket</code> is server socket that can bind a port at SOCKS server
* and accept a connection. This server socket can only accept one connection from specified IP
* address and port.<br>
* <p>
* You can build a TCP server in SOCKS server easily by using following codes:
* </p>
* <pre>
* SocksProxy proxy = new Socks5(new InetSocketAddress("foo.com", 1080));
* //Create SOCKS5 proxy.
*
* ServerSocket serverSocket = new SocksServerSocket(proxy, inetAddress, 8080);
* // Get bind address in SOCKS server.
* InetAddress bindAddress = ((SocksServerSocket) serverSocket).getBindAddress();
* // Get bind port in SOKCS server.
* int bindPort = ((SocksServerSocket) serverSocket).getBindPort();
* Socket socket = serverSocket.accept();
* </pre>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 25, 2015 11:40:36 AM
*/
public class SocksServerSocket extends ServerSocket {
/**
* Logger.
*/
protected static final Logger logger = LoggerFactory.getLogger(SocksServerSocket.class);
/**
* SOCKS proxy.
*/
private SocksProxy proxy;
/**
* The remote host's IP address that will connect the server.
*/
private InetAddress incomeAddress;
/**
* The remote host's port that will connect the server.
*/
private int incomePort;
/**
* Server's IP address.
*/
private InetAddress bindAddress;
/**
* Server's port.
*/
private int bindPort;
/**
* If {@link #accept()} is called, it will be <code>true</code>.
*/
private boolean alreadyAccepted = false;
/**
* Constructs a server socket. This server socket will established in SOCKS server.
*
* @param proxy SOCKS proxy.
* @param inetAddress The IP address that server socket will accept.
* @param port The port that server socket will accept.
* @throws SocksException If any error about SOCKS protocol occurs.
* @throws IOException If any I/O error occurs.
*/
public SocksServerSocket(SocksProxy proxy, InetAddress inetAddress, int port) throws | // Path: src/main/java/sockslib/common/SocksException.java
// public class SocksException extends IOException {
//
// /**
// * Serial version UID.
// */
// private static final long serialVersionUID = 1L;
//
// private static final String NO_ACCEPTABLE_METHODS = "NO ACCEPTABLE METHODS";
// /**
// * Messages that server will reply.
// */
// private static final String serverReplyMessage[] =
// {"General SOCKS server failure", "Connection not allowed by ruleset",
// "Network " + "unreachable", "Host unreachable", "Connection refused", "TTL expired",
// "Command not " + "supported", "Address type not supported"};
// /**
// * Reply from SOCKS server.
// */
// private ServerReply serverReply;
//
// /**
// * Constructs an instance of {@link SocksException} with a message.
// *
// * @param msg Message.
// */
// public SocksException(String msg) {
// super(msg);
// }
//
// /**
// * Constructs an instance of {@link SocksException} with a code.
// *
// * @param replyCode The code that server Replied.
// */
// public SocksException(int replyCode) {
//
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "NO ACCEPTABLE METHODS".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException noAcceptableMethods() {
// return new SocksException(NO_ACCEPTABLE_METHODS);
// }
//
// /**
// * Returns a {@link SocksException} instance with a message "Protocol not supported".
// *
// * @return An instance of {@link SocksException}.
// */
// public static SocksException protocolNotSupported() {
// return new SocksException("Protocol not supported");
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(ServerReply reply) {
// SocksException ex = serverReplyException(reply.getValue());
// ex.setServerReply(reply);
// return ex;
// }
//
// /**
// * Returns a {@link SocksException} instance with a message of reply.
// *
// * @param reply Code of server's reply.
// * @return An instance of {@link SocksException}.
// */
// public static SocksException serverReplyException(byte reply) {
// int code = reply;
// code = code & 0xff;
// if (code < 0 || code > 0x08) {
// return new SocksException("Unknown reply");
// }
// code = code - 1;
// return new SocksException(serverReplyMessage[code]);
// }
//
// /**
// * Returns server's reply.
// *
// * @return Server's reply.
// */
// public ServerReply getServerReply() {
// return serverReply;
// }
//
// /**
// * Sets server's reply.
// *
// * @param serverReply Reply of the server.
// */
// public void setServerReply(ServerReply serverReply) {
// this.serverReply = serverReply;
// }
//
// }
// Path: src/main/java/sockslib/client/SocksServerSocket.java
import sockslib.common.SocksException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
/*
* Copyright 2015-2025 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 sockslib.client;
/**
* The class <code>SocksServerSocket</code> is server socket that can bind a port at SOCKS server
* and accept a connection. This server socket can only accept one connection from specified IP
* address and port.<br>
* <p>
* You can build a TCP server in SOCKS server easily by using following codes:
* </p>
* <pre>
* SocksProxy proxy = new Socks5(new InetSocketAddress("foo.com", 1080));
* //Create SOCKS5 proxy.
*
* ServerSocket serverSocket = new SocksServerSocket(proxy, inetAddress, 8080);
* // Get bind address in SOCKS server.
* InetAddress bindAddress = ((SocksServerSocket) serverSocket).getBindAddress();
* // Get bind port in SOKCS server.
* int bindPort = ((SocksServerSocket) serverSocket).getBindPort();
* Socket socket = serverSocket.accept();
* </pre>
*
* @author Youchao Feng
* @version 1.0
* @date Mar 25, 2015 11:40:36 AM
*/
public class SocksServerSocket extends ServerSocket {
/**
* Logger.
*/
protected static final Logger logger = LoggerFactory.getLogger(SocksServerSocket.class);
/**
* SOCKS proxy.
*/
private SocksProxy proxy;
/**
* The remote host's IP address that will connect the server.
*/
private InetAddress incomeAddress;
/**
* The remote host's port that will connect the server.
*/
private int incomePort;
/**
* Server's IP address.
*/
private InetAddress bindAddress;
/**
* Server's port.
*/
private int bindPort;
/**
* If {@link #accept()} is called, it will be <code>true</code>.
*/
private boolean alreadyAccepted = false;
/**
* Constructs a server socket. This server socket will established in SOCKS server.
*
* @param proxy SOCKS proxy.
* @param inetAddress The IP address that server socket will accept.
* @param port The port that server socket will accept.
* @throws SocksException If any error about SOCKS protocol occurs.
* @throws IOException If any I/O error occurs.
*/
public SocksServerSocket(SocksProxy proxy, InetAddress inetAddress, int port) throws | SocksException, IOException { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java | // Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.converters.path;
public interface IPathToProjectNameConverter {
public abstract String convert(String toParse) | // Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.converters.path;
public interface IPathToProjectNameConverter {
public abstract String convert(String toParse) | throws UnparsableProjectException; |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
| public void execute(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | Properties config, AuthorizationLevel authorizationLevel) { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
| final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
| will(throwException(new BadCommandException()));
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
| assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
| final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
| final IProjectAuthorizer mockProjAuth = context.mock(IProjectAuthorizer.class);
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
final IProjectAuthorizer mockProjAuth = context.mock(IProjectAuthorizer.class);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
final IProjectAuthorizer mockProjAuth = context.mock(IProjectAuthorizer.class);
| final IPathToProjectNameConverter mockPathConverter = context.mock(IPathToProjectNameConverter.class);
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/JavaxNamingProvider.java | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
| import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory; | package com.asolutions.scmsshd.ldap;
public class JavaxNamingProvider implements IJavaxNamingProvider {
private String url;
private boolean promiscuous;
public JavaxNamingProvider(String url, boolean promiscuous) {
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding(String userDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, userDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/JavaxNamingProvider.java
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory;
package com.asolutions.scmsshd.ldap;
public class JavaxNamingProvider implements IJavaxNamingProvider {
private String url;
private boolean promiscuous;
public JavaxNamingProvider(String url, boolean promiscuous) {
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding(String userDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, userDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | properties.setProperty("java.naming.ldap.factory.socket", PromiscuousSSLSocketFactory.class.getName()); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.authorizors;
public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
public AuthorizationLevel userIsAuthorizedForProject(String username, | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.authorizors;
public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
public AuthorizationLevel userIsAuthorizedForProject(String username, | String project) throws UnparsableProjectException { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{ | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{ | new AsynchronyPathToProjectNameConverter().convert(""); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{
new AsynchronyPathToProjectNameConverter().convert("");
fail("Did not throw");
} | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{
new AsynchronyPathToProjectNameConverter().convert("");
fail("Did not throw");
} | catch (UnparsableProjectException e){ |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandlerTest extends MockTestCase {
@Test
public void testReceivePackPassesCorrectStuffToJGIT() throws Exception {
final String pathtobasedir = "pathtobasedir"; | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandlerTest extends MockTestCase {
@Test
public void testReceivePackPassesCorrectStuffToJGIT() throws Exception {
final String pathtobasedir = "pathtobasedir"; | final FilteredCommand filteredCommand = new FilteredCommand( |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final Repository mockRepoistory = context.mock(Repository.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty( | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final Repository mockRepoistory = context.mock(Repository.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty( | GitSCMCommandFactory.REPOSITORY_BASE); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
will(returnValue(pathtobasedir));
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
handler.runCommand(filteredCommand, mockInputStream, mockOutputStream,
mockErrorStream, mockExitCallback, mockConfig, | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
will(returnValue(pathtobasedir));
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
handler.runCommand(filteredCommand, mockInputStream, mockOutputStream,
mockErrorStream, mockExitCallback, mockConfig, | AuthorizationLevel.AUTH_LEVEL_READ_WRITE); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw"); | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw"); | } catch (Failure e) { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | "mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw");
} catch (Failure e) { | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw");
} catch (Failure e) { | assertEquals(MustHaveWritePrivilagesToPushFailure.class, e |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory; | package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override | protected void runCommand(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory; | package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | Properties config, AuthorizationLevel authorizationLevel) |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory; | package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel)
throws IOException {
log.info("Starting Upload Pack Of: " + filteredCommand.getArgument());
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel)
throws IOException {
log.info("Starting Upload Pack Of: " + filteredCommand.getArgument());
| String strRepoBase = config.getProperty(GitSCMCommandFactory.REPOSITORY_BASE); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/PushTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spearce.jgit.lib.Ref;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | }
@After
public void closeRepos()
{
fromRepository.close();
}
@Test
public void testPush() throws Exception {
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
assertPushOfMaster(fromRefMaster);
}
@Test
public void testRoundTrip() throws Exception {
File gitDir = new File(".git");
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, ORIGIN);
FetchResult r = cloneFromRemote(db, ORIGIN);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testPushSCuMD() throws Exception { | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/PushTest.java
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spearce.jgit.lib.Ref;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
}
@After
public void closeRepos()
{
fromRepository.close();
}
@Test
public void testPush() throws Exception {
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
assertPushOfMaster(fromRefMaster);
}
@Test
public void testRoundTrip() throws Exception {
File gitDir = new File(".git");
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, ORIGIN);
FetchResult r = cloneFromRemote(db, ORIGIN);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testPushSCuMD() throws Exception { | final SCuMD sshd = new SCuMD(); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
| private IProjectAuthorizer projectAuthorizer;
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
| private IBadCommandFilter badCommandFilter;
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
| private IPathToProjectNameConverter pathToProjectNameConverter;
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
| FilteredCommand fc = badCommandFilter.filterOrThrow(command);
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
| } catch (BadCommandException e) {
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
} catch (BadCommandException e) {
log.error("Got Bad Command Exception For Command: [" + command
+ "]", e);
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
} catch (BadCommandException e) {
log.error("Got Bad Command Exception For Command: [" + command
+ "]", e);
| return new NoOpCommand();
|
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java | // Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.test.integration.util;
public class ConstantProjectNameConverter implements
IPathToProjectNameConverter {
public ConstantProjectNameConverter() {
}
| // Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.test.integration.util;
public class ConstantProjectNameConverter implements
IPathToProjectNameConverter {
public ConstantProjectNameConverter() {
}
| public String convert(String toParse) throws UnparsableProjectException { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizorTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.*;
import java.util.ArrayList;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer; | package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizorTest extends MockTestCase {
private static final String PROJECT = "project";
private static final String USERNAME = "username";
@Test
public void testAuthingWithEmptyChainFails() throws Exception {
assertNull(new PassIfAnyInCollectionPassAuthorizor().userIsAuthorizedForProject(USERNAME, PROJECT));
}
@Test
public void testIfAnyPassItPasses() throws Exception { | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizorTest.java
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizorTest extends MockTestCase {
private static final String PROJECT = "project";
private static final String USERNAME = "username";
@Test
public void testAuthingWithEmptyChainFails() throws Exception {
assertNull(new PassIfAnyInCollectionPassAuthorizor().userIsAuthorizedForProject(USERNAME, PROJECT));
}
@Test
public void testIfAnyPassItPasses() throws Exception { | final IProjectAuthorizer failsAuth = context.mock(IProjectAuthorizer.class, "failsAuth"); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
| public void execute(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties configuration, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties configuration, | AuthorizationLevel authorizationLevel) { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizor.java | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import java.util.ArrayList;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizor implements IProjectAuthorizer {
private ArrayList<IProjectAuthorizer> authList = new ArrayList<IProjectAuthorizer>();
public AuthorizationLevel userIsAuthorizedForProject(String username, String project) | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizor.java
import java.util.ArrayList;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizor implements IProjectAuthorizer {
private ArrayList<IProjectAuthorizer> authList = new ArrayList<IProjectAuthorizer>();
public AuthorizationLevel userIsAuthorizedForProject(String username, String project) | throws UnparsableProjectException { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPBindingProvider.java | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
| import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory; | /**
*
*/
package com.asolutions.scmsshd.ldap;
public class LDAPBindingProvider {
private String lookupUserDN;
private String lookupUserPassword;
private String url;
private boolean promiscuous;
public LDAPBindingProvider(String lookupUserDN, String lookupUserPassword,
String url, boolean promiscuous) {
this.lookupUserDN = lookupUserDN;
this.lookupUserPassword = lookupUserPassword;
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding() throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public InitialDirContext getBinding(String lookupUserDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPBindingProvider.java
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory;
/**
*
*/
package com.asolutions.scmsshd.ldap;
public class LDAPBindingProvider {
private String lookupUserDN;
private String lookupUserPassword;
private String url;
private boolean promiscuous;
public LDAPBindingProvider(String lookupUserDN, String lookupUserPassword,
String url, boolean promiscuous) {
this.lookupUserDN = lookupUserDN;
this.lookupUserPassword = lookupUserPassword;
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding() throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public InitialDirContext getBinding(String lookupUserDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | properties.setProperty("java.naming.ldap.factory.socket", PromiscuousSSLSocketFactory.class.getName()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception { | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception { | final SCuMD sshd = new SCuMD(); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" })); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" })); | sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
| // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
| GitCommandFactory factory = new GitCommandFactory(); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory(); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory(); | factory.setPathToProjectNameConverter(new ConstantProjectNameConverter()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter()); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter()); | factory.setProjectAuthorizor(new AlwaysPassProjectAuthorizer()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter());
factory.setProjectAuthorizor(new AlwaysPassProjectAuthorizer());
Properties config = new Properties(); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter());
factory.setProjectAuthorizor(new AlwaysPassProjectAuthorizer());
Properties config = new Properties(); | config.setProperty(GitSCMCommandFactory.REPOSITORY_BASE, System.getProperty("user.dir")); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/AllowedCommandCheckerTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
| import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.filters.BadCommandException; | package com.asolutions.scmsshd.commands;
public class AllowedCommandCheckerTest {
@Test
public void testParsesGitCommands() throws Exception {
new AllowedCommandChecker("git-upload-pack");
new AllowedCommandChecker("git upload-pack");
new AllowedCommandChecker("git-receive-pack");
new AllowedCommandChecker("git receive-pack");
}
@Test
public void testFailsOnUnknownCommand() throws Exception {
try{
new AllowedCommandChecker("git receive-packs");
fail("Didn't Throw");
} | // Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/AllowedCommandCheckerTest.java
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
package com.asolutions.scmsshd.commands;
public class AllowedCommandCheckerTest {
@Test
public void testParsesGitCommands() throws Exception {
new AllowedCommandChecker("git-upload-pack");
new AllowedCommandChecker("git upload-pack");
new AllowedCommandChecker("git-receive-pack");
new AllowedCommandChecker("git receive-pack");
}
@Test
public void testFailsOnUnknownCommand() throws Exception {
try{
new AllowedCommandChecker("git receive-packs");
fail("Didn't Throw");
} | catch (BadCommandException e){ |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
| protected void runCommand(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | Properties config, AuthorizationLevel authorizationLevel) throws IOException { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){ | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){ | throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument()); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){
throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument());
}
try{
String strRepoBase = config | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){
throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument());
}
try{
String strRepoBase = config | .getProperty(GitSCMCommandFactory.REPOSITORY_BASE); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter; | package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception { | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter;
package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception { | GitBadCommandFilter filter = new GitBadCommandFilter(); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter; | package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception {
GitBadCommandFilter filter = new GitBadCommandFilter(); | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter;
package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception {
GitBadCommandFilter filter = new GitBadCommandFilter(); | FilteredCommand fc = filter.filterOrThrow("git-upload-pack 'bob'"); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter; | public void testNoArgs() throws Exception {
assertThrows("git-upload-pack");
}
@Test
public void test2Args() throws Exception {
assertThrows("git-upload-pack bob tom");
}
@Test
public void testUnquoted() throws Exception {
assertThrows("git-upload-pack bob");
}
@Test
public void testWithUnsafeBang() throws Exception {
assertThrows("git-upload-pack 'ev!l'");
}
@Test
public void testWithUnsafeDotDot() throws Exception {
assertThrows("git-upload-pack 'something/../evil'");
}
private void assertThrows(String toCheck) {
try{
GitBadCommandFilter filter = new GitBadCommandFilter();
filter.filterOrThrow(toCheck);
fail("didn't throw");
} | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter;
public void testNoArgs() throws Exception {
assertThrows("git-upload-pack");
}
@Test
public void test2Args() throws Exception {
assertThrows("git-upload-pack bob tom");
}
@Test
public void testUnquoted() throws Exception {
assertThrows("git-upload-pack bob");
}
@Test
public void testWithUnsafeBang() throws Exception {
assertThrows("git-upload-pack 'ev!l'");
}
@Test
public void testWithUnsafeDotDot() throws Exception {
assertThrows("git-upload-pack 'something/../evil'");
}
private void assertThrows(String toCheck) {
try{
GitBadCommandFilter filter = new GitBadCommandFilter();
filter.filterOrThrow(toCheck);
fail("didn't throw");
} | catch (BadCommandException e){ |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix; | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix; | private AuthorizationLevel authorizationLevel; |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix;
private AuthorizationLevel authorizationLevel;
private LDAPBindingProvider binding; | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix;
private AuthorizationLevel authorizationLevel;
private LDAPBindingProvider binding; | private LDAPUsernameResolver resolver; |