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
SleepyTrousers/EnderZoo
src/main/java/crazypants/enderzoo/EnderZooTab.java
// Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MODID = "enderzoo"; // // Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MOD_NAME = "Ender Zoo";
import static crazypants.enderzoo.EnderZoo.MODID; import static crazypants.enderzoo.EnderZoo.MOD_NAME; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package crazypants.enderzoo; public class EnderZooTab extends CreativeTabs { public static final CreativeTabs tabEnderZoo = new EnderZooTab(); public EnderZooTab() {
// Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MODID = "enderzoo"; // // Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MOD_NAME = "Ender Zoo"; // Path: src/main/java/crazypants/enderzoo/EnderZooTab.java import static crazypants.enderzoo.EnderZoo.MODID; import static crazypants.enderzoo.EnderZoo.MOD_NAME; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package crazypants.enderzoo; public class EnderZooTab extends CreativeTabs { public static final CreativeTabs tabEnderZoo = new EnderZooTab(); public EnderZooTab() {
super(MODID);
SleepyTrousers/EnderZoo
src/main/java/crazypants/enderzoo/EnderZooTab.java
// Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MODID = "enderzoo"; // // Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MOD_NAME = "Ender Zoo";
import static crazypants.enderzoo.EnderZoo.MODID; import static crazypants.enderzoo.EnderZoo.MOD_NAME; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package crazypants.enderzoo; public class EnderZooTab extends CreativeTabs { public static final CreativeTabs tabEnderZoo = new EnderZooTab(); public EnderZooTab() { super(MODID); } @Override @SideOnly(Side.CLIENT) public String getTabLabel() { return MODID; } @Override @SideOnly(Side.CLIENT) public String getTranslatedTabLabel() {
// Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MODID = "enderzoo"; // // Path: src/main/java/crazypants/enderzoo/EnderZoo.java // public static final String MOD_NAME = "Ender Zoo"; // Path: src/main/java/crazypants/enderzoo/EnderZooTab.java import static crazypants.enderzoo.EnderZoo.MODID; import static crazypants.enderzoo.EnderZoo.MOD_NAME; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package crazypants.enderzoo; public class EnderZooTab extends CreativeTabs { public static final CreativeTabs tabEnderZoo = new EnderZooTab(); public EnderZooTab() { super(MODID); } @Override @SideOnly(Side.CLIENT) public String getTabLabel() { return MODID; } @Override @SideOnly(Side.CLIENT) public String getTranslatedTabLabel() {
return MOD_NAME;
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/bug77/Bug77NoHeaderRecordTerminatorTest.java
// Path: src/test/java/com/linuxense/javadbf/ReadDBFAssert.java // public class ReadDBFAssert { // // private ReadDBFAssert() { // throw new AssertionError("No instances"); // } // // public static void testReadDBFFile(String fileName, int expectedColumns, int expectedRows) throws DBFException, IOException { // testReadDBFFile(fileName, expectedColumns, expectedRows, false); // } // // public static void testReadDBFFile(String fileName, int expectedColumns, int expectedRows, Boolean showDeletedRows) throws DBFException, IOException { // testReadDBFFile(new File("src/test/resources/" + fileName + ".dbf"), expectedColumns, expectedRows, showDeletedRows); // } // // public static void testReadDBFFile(File file, int expectedColumns, int expectedRows, Boolean showDeletedRows) throws DBFException, IOException { // DBFReader reader = null; // try { // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file)), showDeletedRows); // testReadDBFFile(reader, expectedColumns, expectedRows); // } finally { // DBFUtils.close(reader); // } // // } // public static void testReadDBFFile(InputStream is, int expectedColumns, int expectedRows) throws DBFException { // testReadDBFFile(new DBFReader(is), expectedColumns, expectedRows); // } // // public static void testReadDBFFile(DBFReader reader, int expectedColumns, int expectedRows) throws DBFException { // // // int numberOfFields = reader.getFieldCount(); // Assert.assertEquals(expectedColumns, numberOfFields); // for (int i = 0; i < numberOfFields; i++) { // DBFField field = reader.getField(i); // Assert.assertNotNull(field.getName()); // } // Object[] rowObject; // int countedRows = 0; // while ((rowObject = reader.nextRecord()) != null) { // Assert.assertEquals(numberOfFields, rowObject.length); // countedRows++; // } // Assert.assertEquals(expectedRows, countedRows); // Assert.assertEquals(expectedRows, reader.getRecordCount()); // } // // public static void testReadDBFFileDeletedRecords(String fileName, int expectedRows, int expectedDeleted) throws DBFException, IOException { // // DBFReader reader = null; // try { // reader = new DBFReader(new BufferedInputStream(new FileInputStream(new File("src/test/resources/" + fileName + ".dbf"))), true); // Object[] rowObject; // // int countedRows = 0; // int countedDeletes = 0; // int headerStoredRows = reader.getHeader().numberOfRecords; // while ((rowObject = reader.nextRecord()) != null) { // if(rowObject[0] == Boolean.TRUE) { // countedDeletes++; // } // countedRows++; // } // // Assert.assertEquals(expectedRows, countedRows); // Assert.assertEquals(expectedDeleted, countedDeletes); // Assert.assertEquals(expectedRows, headerStoredRows); // } finally { // DBFUtils.close(reader); // } // // // } // }
import java.io.File; import java.io.IOException; import org.junit.Test; import com.linuxense.javadbf.ReadDBFAssert;
package com.linuxense.javadbf.bug77; public class Bug77NoHeaderRecordTerminatorTest { public Bug77NoHeaderRecordTerminatorTest() { super(); } @Test public void testReadCountriesNoTerminator() throws IOException { // This file is original continents.dbf tunned by hand to reproduce the bug File f = new File("src/test/resources/bug-77-no-header-record-terminator/continents_no_header_record_terminator.dbf");
// Path: src/test/java/com/linuxense/javadbf/ReadDBFAssert.java // public class ReadDBFAssert { // // private ReadDBFAssert() { // throw new AssertionError("No instances"); // } // // public static void testReadDBFFile(String fileName, int expectedColumns, int expectedRows) throws DBFException, IOException { // testReadDBFFile(fileName, expectedColumns, expectedRows, false); // } // // public static void testReadDBFFile(String fileName, int expectedColumns, int expectedRows, Boolean showDeletedRows) throws DBFException, IOException { // testReadDBFFile(new File("src/test/resources/" + fileName + ".dbf"), expectedColumns, expectedRows, showDeletedRows); // } // // public static void testReadDBFFile(File file, int expectedColumns, int expectedRows, Boolean showDeletedRows) throws DBFException, IOException { // DBFReader reader = null; // try { // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file)), showDeletedRows); // testReadDBFFile(reader, expectedColumns, expectedRows); // } finally { // DBFUtils.close(reader); // } // // } // public static void testReadDBFFile(InputStream is, int expectedColumns, int expectedRows) throws DBFException { // testReadDBFFile(new DBFReader(is), expectedColumns, expectedRows); // } // // public static void testReadDBFFile(DBFReader reader, int expectedColumns, int expectedRows) throws DBFException { // // // int numberOfFields = reader.getFieldCount(); // Assert.assertEquals(expectedColumns, numberOfFields); // for (int i = 0; i < numberOfFields; i++) { // DBFField field = reader.getField(i); // Assert.assertNotNull(field.getName()); // } // Object[] rowObject; // int countedRows = 0; // while ((rowObject = reader.nextRecord()) != null) { // Assert.assertEquals(numberOfFields, rowObject.length); // countedRows++; // } // Assert.assertEquals(expectedRows, countedRows); // Assert.assertEquals(expectedRows, reader.getRecordCount()); // } // // public static void testReadDBFFileDeletedRecords(String fileName, int expectedRows, int expectedDeleted) throws DBFException, IOException { // // DBFReader reader = null; // try { // reader = new DBFReader(new BufferedInputStream(new FileInputStream(new File("src/test/resources/" + fileName + ".dbf"))), true); // Object[] rowObject; // // int countedRows = 0; // int countedDeletes = 0; // int headerStoredRows = reader.getHeader().numberOfRecords; // while ((rowObject = reader.nextRecord()) != null) { // if(rowObject[0] == Boolean.TRUE) { // countedDeletes++; // } // countedRows++; // } // // Assert.assertEquals(expectedRows, countedRows); // Assert.assertEquals(expectedDeleted, countedDeletes); // Assert.assertEquals(expectedRows, headerStoredRows); // } finally { // DBFUtils.close(reader); // } // // // } // } // Path: src/test/java/com/linuxense/javadbf/bug77/Bug77NoHeaderRecordTerminatorTest.java import java.io.File; import java.io.IOException; import org.junit.Test; import com.linuxense.javadbf.ReadDBFAssert; package com.linuxense.javadbf.bug77; public class Bug77NoHeaderRecordTerminatorTest { public Bug77NoHeaderRecordTerminatorTest() { super(); } @Test public void testReadCountriesNoTerminator() throws IOException { // This file is original continents.dbf tunned by hand to reproduce the bug File f = new File("src/test/resources/bug-77-no-header-record-terminator/continents_no_header_record_terminator.dbf");
ReadDBFAssert.testReadDBFFile(f, 1, 7, false);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/BinaryImageTest.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class BinaryImageTest { @Test public void testBinaryImage() throws Exception { File file = new File("src/test/resources/inventory.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file)); reader.setMemoFile(new File("src/test/resources/inventory.dbt")); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(6, header.fieldArray.length); Assert.assertEquals(12, header.numberOfRecords); DBFField[] fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/BinaryImageTest.java import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class BinaryImageTest { @Test public void testBinaryImage() throws Exception { File file = new File("src/test/resources/inventory.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file)); reader.setMemoFile(new File("src/test/resources/inventory.dbt")); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(6, header.fieldArray.length); Assert.assertEquals(12, header.numberOfRecords); DBFField[] fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "Item ID", DBFDataType.AUTOINCREMENT, 4, 0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase30Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase30Test { @Test public void test30 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_30.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file)); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(145, header.fieldArray.length); Assert.assertEquals(34, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase30Test.java import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase30Test { @Test public void test30 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_30.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file)); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(145, header.fieldArray.length); Assert.assertEquals(34, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "ACCESSNO", DBFDataType.fromCode((byte) 'C'), 15 , 0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/EncodingTest.java
// Path: src/test/java/com/linuxense/javadbf/mocks/NullOutputStream.java // public class NullOutputStream extends OutputStream { // // private long count = 0; // // // /** // * Constructor // */ // public NullOutputStream() { // super(); // } // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @param off The start offset // * @param len The number of bytes to write // */ // @Override // public void write(byte[] b, int off, int len) { // this.count+= len; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The byte to write // */ // @Override // public void write(int b) { // this.count++; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @throws IOException never // */ // @Override // public void write(byte[] b) throws IOException { // if (b != null) { // this.count += b.length; // } // } // // public long getCount() { // return this.count; // } // // }
import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.mocks.NullOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List;
DBFUtils.close(wr); byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); List<String> names = new ArrayList<String>(); reader = new DBFReader(bais); reader.setCharset(StandardCharsets.UTF_8); Object[] rowObject; while ((rowObject = reader.nextRecord()) != null) { names.add((String) rowObject[0]); } assertNotNull(names.get(0)); assertEquals("Simón", names.get(0).trim()); assertNotNull(names.get(1)); assertEquals("Julián", names.get(1).trim()); } finally { DBFUtils.close(reader); DBFUtils.close(wr); } } @Test public void testSetEncoding() throws DBFException { DBFWriter writer = null; try {
// Path: src/test/java/com/linuxense/javadbf/mocks/NullOutputStream.java // public class NullOutputStream extends OutputStream { // // private long count = 0; // // // /** // * Constructor // */ // public NullOutputStream() { // super(); // } // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @param off The start offset // * @param len The number of bytes to write // */ // @Override // public void write(byte[] b, int off, int len) { // this.count+= len; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The byte to write // */ // @Override // public void write(int b) { // this.count++; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @throws IOException never // */ // @Override // public void write(byte[] b) throws IOException { // if (b != null) { // this.count += b.length; // } // } // // public long getCount() { // return this.count; // } // // } // Path: src/test/java/com/linuxense/javadbf/EncodingTest.java import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.mocks.NullOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; DBFUtils.close(wr); byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); List<String> names = new ArrayList<String>(); reader = new DBFReader(bais); reader.setCharset(StandardCharsets.UTF_8); Object[] rowObject; while ((rowObject = reader.nextRecord()) != null) { names.add((String) rowObject[0]); } assertNotNull(names.get(0)); assertEquals("Simón", names.get(0).trim()); assertNotNull(names.get(1)); assertEquals("Julián", names.get(1).trim()); } finally { DBFUtils.close(reader); DBFUtils.close(wr); } } @Test public void testSetEncoding() throws DBFException { DBFWriter writer = null; try {
writer = new DBFWriter(new NullOutputStream());
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase31Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase31Test { @Test public void test31 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_31.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(11, header.fieldArray.length); Assert.assertEquals(77, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase31Test.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase31Test { @Test public void test31 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_31.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(11, header.fieldArray.length); Assert.assertEquals(77, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "PRODUCTID", DBFDataType.fromCode((byte) 'I'), 4 ,0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/DBFWriterStreamTest.java
// Path: src/test/java/com/linuxense/javadbf/mocks/NullOutputStream.java // public class NullOutputStream extends OutputStream { // // private long count = 0; // // // /** // * Constructor // */ // public NullOutputStream() { // super(); // } // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @param off The start offset // * @param len The number of bytes to write // */ // @Override // public void write(byte[] b, int off, int len) { // this.count+= len; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The byte to write // */ // @Override // public void write(int b) { // this.count++; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @throws IOException never // */ // @Override // public void write(byte[] b) throws IOException { // if (b != null) { // this.count += b.length; // } // } // // public long getCount() { // return this.count; // } // // }
import java.io.IOException; import java.util.Date; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.mocks.NullOutputStream;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class DBFWriterStreamTest { @Test public void testAllDataTypes() throws IOException {
// Path: src/test/java/com/linuxense/javadbf/mocks/NullOutputStream.java // public class NullOutputStream extends OutputStream { // // private long count = 0; // // // /** // * Constructor // */ // public NullOutputStream() { // super(); // } // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @param off The start offset // * @param len The number of bytes to write // */ // @Override // public void write(byte[] b, int off, int len) { // this.count+= len; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The byte to write // */ // @Override // public void write(int b) { // this.count++; // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param b The bytes to write // * @throws IOException never // */ // @Override // public void write(byte[] b) throws IOException { // if (b != null) { // this.count += b.length; // } // } // // public long getCount() { // return this.count; // } // // } // Path: src/test/java/com/linuxense/javadbf/DBFWriterStreamTest.java import java.io.IOException; import java.util.Date; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.mocks.NullOutputStream; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class DBFWriterStreamTest { @Test public void testAllDataTypes() throws IOException {
NullOutputStream output = new NullOutputStream();
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/NullFlagsTest.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
package com.linuxense.javadbf; public class NullFlagsTest { @Test public void testNullFlags() throws Exception { File file = new File("src/test/resources/fixtures/dbase_31.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(11, header.fieldArray.length); Assert.assertEquals(77, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/NullFlagsTest.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; package com.linuxense.javadbf; public class NullFlagsTest { @Test public void testNullFlags() throws Exception { File file = new File("src/test/resources/fixtures/dbase_31.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(11, header.fieldArray.length); Assert.assertEquals(77, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "PRODUCTID", DBFDataType.fromCode((byte) 'I'), 4 ,0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/NullFlagsTest.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
AssertUtils.assertColumnDefinition(fieldArray[i++], "PRODUCTNAM", DBFDataType.fromCode((byte) 'C'), 40 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "SUPPLIERID", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "CATEGORYID", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "QUANTITYPE", DBFDataType.fromCode((byte) 'C'), 20 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "UNITPRICE", DBFDataType.fromCode((byte) 'Y'), 8 ,4); AssertUtils.assertColumnDefinition(fieldArray[i++], "UNITSINSTO", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "UNITSONORD", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "REORDERLEV", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "DISCONTINU", DBFDataType.fromCode((byte) 'L'), 1 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "_NullFlags", DBFDataType.NULL_FLAGS, 1 ,0); DBFField nullFlagsField = fieldArray[fieldArray.length -1]; Assert.assertTrue(nullFlagsField.isSystem()); Assert.assertEquals(10, reader.getFieldCount()); // for (DBFField field: fieldArray) { // System.out.println(field.getName() + ":" + field.isNullable()+ ":" + field.isSystem() + ":" + field.isBinary()); // } Object[] row = null; while ((row = reader.nextRecord()) != null) { Assert.assertEquals(10, row.length); // Object o = row[row.length-1]; // System.out.println(o); }
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/NullFlagsTest.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; AssertUtils.assertColumnDefinition(fieldArray[i++], "PRODUCTNAM", DBFDataType.fromCode((byte) 'C'), 40 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "SUPPLIERID", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "CATEGORYID", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "QUANTITYPE", DBFDataType.fromCode((byte) 'C'), 20 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "UNITPRICE", DBFDataType.fromCode((byte) 'Y'), 8 ,4); AssertUtils.assertColumnDefinition(fieldArray[i++], "UNITSINSTO", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "UNITSONORD", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "REORDERLEV", DBFDataType.fromCode((byte) 'I'), 4 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "DISCONTINU", DBFDataType.fromCode((byte) 'L'), 1 ,0); AssertUtils.assertColumnDefinition(fieldArray[i++], "_NullFlags", DBFDataType.NULL_FLAGS, 1 ,0); DBFField nullFlagsField = fieldArray[fieldArray.length -1]; Assert.assertTrue(nullFlagsField.isSystem()); Assert.assertEquals(10, reader.getFieldCount()); // for (DBFField field: fieldArray) { // System.out.println(field.getName() + ":" + field.isNullable()+ ":" + field.isSystem() + ":" + field.isBinary()); // } Object[] row = null; while ((row = reader.nextRecord()) != null) { Assert.assertEquals(10, row.length); // Object o = row[row.length-1]; // System.out.println(o); }
DbfToTxtTest.export(reader, File.createTempFile("javadbf-test", ".txt"));
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/DBFReaderTest.java
// Path: src/test/java/com/linuxense/javadbf/mocks/FailInputStream.java // public class FailInputStream extends InputStream{ // // @Override // public int read() throws IOException { // throw new IOException ("fail to read"); // } // // }
import static org.junit.Assert.assertNull; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.mocks.FailInputStream;
"TOPIC_ID\n" + "COPYRIGHT_\n" + "ISBN_NUMBE\n" + "PUBLISHER_\n" + "PURCHASE_P\n" + "COVERTYPE\n" + "DATE_PURCH\n" + "PAGES\n" + "NOTES\n"; Assert.assertEquals(expected, reader.toString()); } finally { DBFUtils.close(reader); } } @Test public void testReadBooksAddedDeleteField() throws IOException { ReadDBFAssert.testReadDBFFile("books", 12, 10, true); } @Test public void testReadDBFFileDeletedRecords() throws IOException { ReadDBFAssert.testReadDBFFileDeletedRecords("test_delete",3,1); } @Test(expected=DBFException.class) public void testFailStream() throws DBFException, IOException{ DBFReader reader = null; try {
// Path: src/test/java/com/linuxense/javadbf/mocks/FailInputStream.java // public class FailInputStream extends InputStream{ // // @Override // public int read() throws IOException { // throw new IOException ("fail to read"); // } // // } // Path: src/test/java/com/linuxense/javadbf/DBFReaderTest.java import static org.junit.Assert.assertNull; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.mocks.FailInputStream; "TOPIC_ID\n" + "COPYRIGHT_\n" + "ISBN_NUMBE\n" + "PUBLISHER_\n" + "PURCHASE_P\n" + "COVERTYPE\n" + "DATE_PURCH\n" + "PAGES\n" + "NOTES\n"; Assert.assertEquals(expected, reader.toString()); } finally { DBFUtils.close(reader); } } @Test public void testReadBooksAddedDeleteField() throws IOException { ReadDBFAssert.testReadDBFFile("books", 12, 10, true); } @Test public void testReadDBFFileDeletedRecords() throws IOException { ReadDBFAssert.testReadDBFFileDeletedRecords("test_delete",3,1); } @Test(expected=DBFException.class) public void testFailStream() throws DBFException, IOException{ DBFReader reader = null; try {
reader = new DBFReader(new FailInputStream());
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase03Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase03Test { @Test public void test8b() throws Exception { File file = new File("src/test/resources/fixtures/dbase_03.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file)); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(31, header.fieldArray.length); Assert.assertEquals(14, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase03Test.java import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase03Test { @Test public void test8b() throws Exception { File file = new File("src/test/resources/fixtures/dbase_03.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file)); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(31, header.fieldArray.length); Assert.assertEquals(14, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "Point_ID" , DBFDataType.fromCode((byte) 'C'), 12, 0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase7Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/DateUtils.java // public static Date createDate(int year, int month, int day) { // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, year); // c.set(Calendar.MONTH, month - 1); // c.set(Calendar.DAY_OF_MONTH, day); // c.set(Calendar.HOUR_OF_DAY, 0); // c.set(Calendar.MINUTE, 0); // c.set(Calendar.SECOND, 0); // c.set(Calendar.MILLISECOND, 0); // return c.getTime(); // } // // Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // }
import static com.linuxense.javadbf.testutils.DateUtils.createDate; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase7Test { @Test public void test7 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_7.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(4, header.fieldArray.length); Assert.assertEquals(3, header.numberOfRecords); DBFField []fieldArray = header.fieldArray;
// Path: src/test/java/com/linuxense/javadbf/testutils/DateUtils.java // public static Date createDate(int year, int month, int day) { // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, year); // c.set(Calendar.MONTH, month - 1); // c.set(Calendar.DAY_OF_MONTH, day); // c.set(Calendar.HOUR_OF_DAY, 0); // c.set(Calendar.MINUTE, 0); // c.set(Calendar.SECOND, 0); // c.set(Calendar.MILLISECOND, 0); // return c.getTime(); // } // // Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase7Test.java import static com.linuxense.javadbf.testutils.DateUtils.createDate; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase7Test { @Test public void test7 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_7.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(4, header.fieldArray.length); Assert.assertEquals(3, header.numberOfRecords); DBFField []fieldArray = header.fieldArray;
AssertUtils.assertColumnDefinition(fieldArray[0], "ACTION", DBFDataType.MEMO, 10, 0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase7Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/DateUtils.java // public static Date createDate(int year, int month, int day) { // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, year); // c.set(Calendar.MONTH, month - 1); // c.set(Calendar.DAY_OF_MONTH, day); // c.set(Calendar.HOUR_OF_DAY, 0); // c.set(Calendar.MINUTE, 0); // c.set(Calendar.SECOND, 0); // c.set(Calendar.MILLISECOND, 0); // return c.getTime(); // } // // Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // }
import static com.linuxense.javadbf.testutils.DateUtils.createDate; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase7Test { @Test public void test7 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_7.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(4, header.fieldArray.length); Assert.assertEquals(3, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; AssertUtils.assertColumnDefinition(fieldArray[0], "ACTION", DBFDataType.MEMO, 10, 0); AssertUtils.assertColumnDefinition(fieldArray[1], "DATE", DBFDataType.DATE, 8, 0); AssertUtils.assertColumnDefinition(fieldArray[2], "USER", DBFDataType.CHARACTER, 20, 0); AssertUtils.assertColumnDefinition(fieldArray[3], "ID", DBFDataType.CHARACTER, 12, 0); Object[] row = null; row = reader.nextRecord();
// Path: src/test/java/com/linuxense/javadbf/testutils/DateUtils.java // public static Date createDate(int year, int month, int day) { // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, year); // c.set(Calendar.MONTH, month - 1); // c.set(Calendar.DAY_OF_MONTH, day); // c.set(Calendar.HOUR_OF_DAY, 0); // c.set(Calendar.MINUTE, 0); // c.set(Calendar.SECOND, 0); // c.set(Calendar.MILLISECOND, 0); // return c.getTime(); // } // // Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase7Test.java import static com.linuxense.javadbf.testutils.DateUtils.createDate; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase7Test { @Test public void test7 () throws Exception { File file = new File("src/test/resources/fixtures/dbase_7.dbf"); DBFReader reader = null; try { reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(4, header.fieldArray.length); Assert.assertEquals(3, header.numberOfRecords); DBFField []fieldArray = header.fieldArray; AssertUtils.assertColumnDefinition(fieldArray[0], "ACTION", DBFDataType.MEMO, 10, 0); AssertUtils.assertColumnDefinition(fieldArray[1], "DATE", DBFDataType.DATE, 8, 0); AssertUtils.assertColumnDefinition(fieldArray[2], "USER", DBFDataType.CHARACTER, 20, 0); AssertUtils.assertColumnDefinition(fieldArray[3], "ID", DBFDataType.CHARACTER, 12, 0); Object[] row = null; row = reader.nextRecord();
Assert.assertEquals(createDate(2015,2,23), row[1]);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase83Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase83Test { @Test public void test8b() throws Exception { File file = new File("src/test/resources/fixtures/dbase_83.dbf"); InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); DBFReader reader = new DBFReader(inputStream); reader.setMemoFile(new File("src/test/resources/fixtures/dbase_83.dbt")); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(15, header.fieldArray.length); Assert.assertEquals(67, header.numberOfRecords); DBFField[] fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase83Test.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBase83Test { @Test public void test8b() throws Exception { File file = new File("src/test/resources/fixtures/dbase_83.dbf"); InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); DBFReader reader = new DBFReader(inputStream); reader.setMemoFile(new File("src/test/resources/fixtures/dbase_83.dbt")); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(15, header.fieldArray.length); Assert.assertEquals(67, header.numberOfRecords); DBFField[] fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "ID", DBFDataType.fromCode('N'), 19, 0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/bug85float/Bug85Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.File; import java.io.FileNotFoundException; import org.junit.Assume; import org.junit.Test; import com.linuxense.javadbf.testutils.DbfToTxtTest;
package com.linuxense.javadbf.bug85float; public class Bug85Test { public Bug85Test() { super(); } @Test public void printFile() throws FileNotFoundException { File home = new File(System.getProperty("user.home")); File f = new File(home, "javadbf/PRODUTOS.DBF"); Assume.assumeTrue(f.exists());
// Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/bug85float/Bug85Test.java import java.io.File; import java.io.FileNotFoundException; import org.junit.Assume; import org.junit.Test; import com.linuxense.javadbf.testutils.DbfToTxtTest; package com.linuxense.javadbf.bug85float; public class Bug85Test { public Bug85Test() { super(); } @Test public void printFile() throws FileNotFoundException { File home = new File(System.getProperty("user.home")); File f = new File(home, "javadbf/PRODUTOS.DBF"); Assume.assumeTrue(f.exists());
int records = DbfToTxtTest.parseFileCountRecords(f);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBaseF5Test.java
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBaseF5Test { @Test public void test31() throws Exception { File file = new File("src/test/resources/fixtures/dbase_f5.dbf"); InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); DBFReader reader = new DBFReader(inputStream); reader.setMemoFile(new File("src/test/resources/fixtures/dbase_f5.fpt")); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(59, header.fieldArray.length); Assert.assertEquals(975, header.numberOfRecords); DBFField[] fieldArray = header.fieldArray; int i = 0;
// Path: src/test/java/com/linuxense/javadbf/testutils/AssertUtils.java // public class AssertUtils { // // public static void assertColumnDefinition(DBFField field, String columnName, DBFDataType type, int length, int decimal) { // Assert.assertEquals(columnName, field.getName()); // Assert.assertEquals(type, field.getType()); // Assert.assertEquals(length, field.getLength()); // Assert.assertEquals(decimal, field.getDecimalCount()); // } // // } // // Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBaseF5Test.java import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.junit.Assert; import org.junit.Test; import com.linuxense.javadbf.testutils.AssertUtils; import com.linuxense.javadbf.testutils.DbfToTxtTest; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class FixtureDBaseF5Test { @Test public void test31() throws Exception { File file = new File("src/test/resources/fixtures/dbase_f5.dbf"); InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); DBFReader reader = new DBFReader(inputStream); reader.setMemoFile(new File("src/test/resources/fixtures/dbase_f5.fpt")); DBFHeader header = reader.getHeader(); Assert.assertNotNull(header); Assert.assertEquals(59, header.fieldArray.length); Assert.assertEquals(975, header.numberOfRecords); DBFField[] fieldArray = header.fieldArray; int i = 0;
AssertUtils.assertColumnDefinition(fieldArray[i++], "NF", DBFDataType.fromCode((byte) 'N'), 5, 0);
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/DBFReaderPrintTest.java
// Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // }
import com.linuxense.javadbf.testutils.DbfToTxtTest; import java.io.File; import java.io.FileInputStream; import org.junit.Test;
/* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class DBFReaderPrintTest { @Test public void printFile() throws Exception { File file = new File("src/test/resources/books.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file));
// Path: src/test/java/com/linuxense/javadbf/testutils/DbfToTxtTest.java // public final class DbfToTxtTest { // // private DbfToTxtTest() { // throw new AssertionError("no instances"); // } // // public static void export(DBFReader reader, File file) { // // PrintWriter writer = null; // try { // writer = new PrintWriter(file, "UTF-8"); // Object[] row = null; // // while ((row = reader.nextRecord()) != null) { // for (Object o : row) { // writer.print(o + ";"); // } // writer.println(""); // } // } // catch (IOException e) { // // nop // } // finally { // DBFUtils.close(writer); // } // } // // public static void writeToConsole(File file) throws FileNotFoundException { // DBFReader reader = null; // try { // // // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // // // get the field count if you want for some reasons like the following // // int numberOfFields = reader.getFieldCount(); // // // use this count to fetch all field information // // if required // // for (int i = 0; i < numberOfFields; i++) { // // DBFField field = reader.getField(i); // // // // do something with it if you want // // // refer the JavaDoc API reference for more details // // // // System.out.println(field.getType() + " (" + field.getLength() + ") "+ field.getName()); // } // // // Now, lets us start reading the rows // // Object[] rowObjects; // // int count = 0; // System.out.println("-------------------"); // // // while ((rowObjects = reader.nextRecord()) != null) { // count++; // for (int i = 0; i < rowObjects.length; i++) { // System.out.println(rowObjects[i]); // } // System.out.println("-------------------"); // } // System.out.println(file.getName() + " count=" + count); // // // By now, we have iterated through all of the rows // } // finally { // DBFUtils.close(reader); // } // } // // public static int parseFileCountRecords(File file) throws FileNotFoundException { // DBFReader reader = null; // int count=0; // try { // // create a DBFReader object // reader = new DBFReader(new BufferedInputStream(new FileInputStream(file))); // while(reader.nextRow() != null) { // count++; // } // } // finally { // DBFUtils.close(reader); // } // return count; // } // // public static void main(String[] args) throws Exception { // File f = new File(args[0]); // writeToConsole(f); // } // } // Path: src/test/java/com/linuxense/javadbf/DBFReaderPrintTest.java import com.linuxense.javadbf.testutils.DbfToTxtTest; import java.io.File; import java.io.FileInputStream; import org.junit.Test; /* (C) Copyright 2017 Alberto Fernández <infjaf@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.linuxense.javadbf; public class DBFReaderPrintTest { @Test public void printFile() throws Exception { File file = new File("src/test/resources/books.dbf"); DBFReader reader = null; try { reader = new DBFReader(new FileInputStream(file));
DbfToTxtTest.export(reader, File.createTempFile("javadbf-test", ".txt"));
albfernandez/javadbf
src/test/java/com/linuxense/javadbf/FixtureDBase8bTest.java
// Path: src/test/java/com/linuxense/javadbf/testutils/DateUtils.java // public static Date createDate(int year, int month, int day) { // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, year); // c.set(Calendar.MONTH, month - 1); // c.set(Calendar.DAY_OF_MONTH, day); // c.set(Calendar.HOUR_OF_DAY, 0); // c.set(Calendar.MINUTE, 0); // c.set(Calendar.SECOND, 0); // c.set(Calendar.MILLISECOND, 0); // return c.getTime(); // }
import static com.linuxense.javadbf.testutils.DateUtils.createDate; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.Date; import org.junit.Assert; import org.junit.Test;
Assert.assertEquals(DBFDataType.DATE, header.fieldArray[2].getType()); Assert.assertEquals(0, header.fieldArray[2].getDecimalCount()); Assert.assertEquals(8, header.fieldArray[2].getLength()); Assert.assertEquals("LOGICAL", header.fieldArray[3].getName()); Assert.assertEquals(DBFDataType.LOGICAL, header.fieldArray[3].getType()); Assert.assertEquals(0, header.fieldArray[3].getDecimalCount()); Assert.assertEquals(1, header.fieldArray[3].getLength()); Assert.assertEquals("FLOAT", header.fieldArray[4].getName()); Assert.assertEquals(DBFDataType.FLOATING_POINT, header.fieldArray[4].getType()); Assert.assertEquals(18, header.fieldArray[4].getDecimalCount()); Assert.assertEquals(20, header.fieldArray[4].getLength()); Assert.assertEquals("MEMO", header.fieldArray[5].getName()); Assert.assertEquals(DBFDataType.MEMO, header.fieldArray[5].getType()); Assert.assertEquals(0, header.fieldArray[5].getDecimalCount()); Assert.assertEquals(10, header.fieldArray[5].getLength()); Assert.assertEquals(10, header.numberOfRecords); Object[] row = null; row = reader.nextRecord(); Assert.assertEquals("One", row[0]); Assert.assertTrue(row[1] instanceof Number); Assert.assertEquals(1, ((Number)row[1]).intValue()); Assert.assertTrue(row[2] instanceof Date);
// Path: src/test/java/com/linuxense/javadbf/testutils/DateUtils.java // public static Date createDate(int year, int month, int day) { // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, year); // c.set(Calendar.MONTH, month - 1); // c.set(Calendar.DAY_OF_MONTH, day); // c.set(Calendar.HOUR_OF_DAY, 0); // c.set(Calendar.MINUTE, 0); // c.set(Calendar.SECOND, 0); // c.set(Calendar.MILLISECOND, 0); // return c.getTime(); // } // Path: src/test/java/com/linuxense/javadbf/FixtureDBase8bTest.java import static com.linuxense.javadbf.testutils.DateUtils.createDate; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.Date; import org.junit.Assert; import org.junit.Test; Assert.assertEquals(DBFDataType.DATE, header.fieldArray[2].getType()); Assert.assertEquals(0, header.fieldArray[2].getDecimalCount()); Assert.assertEquals(8, header.fieldArray[2].getLength()); Assert.assertEquals("LOGICAL", header.fieldArray[3].getName()); Assert.assertEquals(DBFDataType.LOGICAL, header.fieldArray[3].getType()); Assert.assertEquals(0, header.fieldArray[3].getDecimalCount()); Assert.assertEquals(1, header.fieldArray[3].getLength()); Assert.assertEquals("FLOAT", header.fieldArray[4].getName()); Assert.assertEquals(DBFDataType.FLOATING_POINT, header.fieldArray[4].getType()); Assert.assertEquals(18, header.fieldArray[4].getDecimalCount()); Assert.assertEquals(20, header.fieldArray[4].getLength()); Assert.assertEquals("MEMO", header.fieldArray[5].getName()); Assert.assertEquals(DBFDataType.MEMO, header.fieldArray[5].getType()); Assert.assertEquals(0, header.fieldArray[5].getDecimalCount()); Assert.assertEquals(10, header.fieldArray[5].getLength()); Assert.assertEquals(10, header.numberOfRecords); Object[] row = null; row = reader.nextRecord(); Assert.assertEquals("One", row[0]); Assert.assertTrue(row[1] instanceof Number); Assert.assertEquals(1, ((Number)row[1]).intValue()); Assert.assertTrue(row[2] instanceof Date);
Assert.assertEquals(createDate(1970,1,1), row[2]);
mkl-public/testarea-pdfbox1
src/test/java/mkl/testarea/pdfbox1/content/RenderEndorsement.java
// Path: src/main/java/mkl/testarea/pdfbox1/content/PdfRenderingEndorsementAlternative.java // static public class BandColumn // { // public enum Layout // { // headerText(150, TEXT_WIDTH, 0, 10), // leftHalfPageField(LEFT_MARGIN, FIELD_WIDTH, HALF_WIDTH - 2 * FIELD_WIDTH - 10, 10), // rightHalfPageField(HALF_WIDTH, FIELD_WIDTH, HALF_WIDTH - 2 * FIELD_WIDTH - 10, 10); // // Layout(float x, int fieldWidth, int valueWidth, int space) // { // this.x = x; // this.fieldWidth = fieldWidth; // this.valueWidth = valueWidth; // this.space = space; // } // // final float x; // final int fieldWidth, valueWidth, space; // } // // public BandColumn(Layout layout, String labelField, String value) // { // this(layout.x, layout.space, labelField, value, layout.fieldWidth, layout.valueWidth); // } // // public BandColumn(float x, int space, String labelField, String value, int fieldWidth, int valueWidth) // { // this.x = x; // this.space = space; // this.labelField = labelField; // this.value = value; // this.fieldWidth = fieldWidth; // this.valueWidth = valueWidth; // } // // List<Chunk> toChunks() throws IOException // { // final List<Chunk> result = new ArrayList<Chunk>(); // result.addAll(toChunks(0, fieldWidth, PDType1Font.TIMES_BOLD, labelField)); // result.addAll(toChunks(10 + fieldWidth, valueWidth, PDType1Font.TIMES_ROMAN, value)); // return result; // } // // List<Chunk> toChunks(int offset, int width, PDFont font, String text) throws IOException // { // if (text == null || text.length() == 0) // return Collections.emptyList(); // // final List<Chunk> result = new ArrayList<Chunk>(); // float y = -space; // List<String> rows = getRows(text, width, font); // for (String row: rows) // { // result.add(new Chunk(x+offset, y, space, font, row)); // y-= space; // } // return result; // } // // final float x; // final int space, fieldWidth, valueWidth; // final String labelField, value; // }
import static mkl.testarea.pdfbox1.content.PdfRenderingEndorsementAlternative.BandColumn.Layout.leftHalfPageField; import static mkl.testarea.pdfbox1.content.PdfRenderingEndorsementAlternative.BandColumn.Layout.rightHalfPageField; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import mkl.testarea.pdfbox1.content.PdfRenderingEndorsementAlternative.BandColumn; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.junit.BeforeClass; import org.junit.Test;
package mkl.testarea.pdfbox1.content; /** * <a href="http://stackoverflow.com/questions/30767643/pdfbox-issue-while-changing-page"> * PdfBox issue while changing page * </a> * <p> * This test tests the rendering code in {@link PdfRenderingEndorsementAlternative} (which * is an alternative approach to the OP's {@link PdfRenderingEndorsement}) using the data * from the OP's sample file <a href="https://drive.google.com/file/d/0B-z424N1EYicR1BxUUtUSkw4V1U/view?usp=sharing">Endoso-44-17.pdf</a>. * </p> * @author mkl */ public class RenderEndorsement { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } @Test public void testAlternativeQuick() throws IOException, COSVisitorException { String[] header = new String[] { "Daños - Agrícola y de animales", "2015-06-05 / 2016-01-31", "FONDO DE ASEGURAMIENTO AGRÍCOLA 21 DE OCTUBRE", "FNP-00004408003772000" }; try ( InputStream logo = getClass().getResourceAsStream("Logo.jpg") ) { PDDocument document = new PDDocument(); PdfRenderingEndorsementAlternative renderer = new PdfRenderingEndorsementAlternative(document, logo, header); renderer.render(
// Path: src/main/java/mkl/testarea/pdfbox1/content/PdfRenderingEndorsementAlternative.java // static public class BandColumn // { // public enum Layout // { // headerText(150, TEXT_WIDTH, 0, 10), // leftHalfPageField(LEFT_MARGIN, FIELD_WIDTH, HALF_WIDTH - 2 * FIELD_WIDTH - 10, 10), // rightHalfPageField(HALF_WIDTH, FIELD_WIDTH, HALF_WIDTH - 2 * FIELD_WIDTH - 10, 10); // // Layout(float x, int fieldWidth, int valueWidth, int space) // { // this.x = x; // this.fieldWidth = fieldWidth; // this.valueWidth = valueWidth; // this.space = space; // } // // final float x; // final int fieldWidth, valueWidth, space; // } // // public BandColumn(Layout layout, String labelField, String value) // { // this(layout.x, layout.space, labelField, value, layout.fieldWidth, layout.valueWidth); // } // // public BandColumn(float x, int space, String labelField, String value, int fieldWidth, int valueWidth) // { // this.x = x; // this.space = space; // this.labelField = labelField; // this.value = value; // this.fieldWidth = fieldWidth; // this.valueWidth = valueWidth; // } // // List<Chunk> toChunks() throws IOException // { // final List<Chunk> result = new ArrayList<Chunk>(); // result.addAll(toChunks(0, fieldWidth, PDType1Font.TIMES_BOLD, labelField)); // result.addAll(toChunks(10 + fieldWidth, valueWidth, PDType1Font.TIMES_ROMAN, value)); // return result; // } // // List<Chunk> toChunks(int offset, int width, PDFont font, String text) throws IOException // { // if (text == null || text.length() == 0) // return Collections.emptyList(); // // final List<Chunk> result = new ArrayList<Chunk>(); // float y = -space; // List<String> rows = getRows(text, width, font); // for (String row: rows) // { // result.add(new Chunk(x+offset, y, space, font, row)); // y-= space; // } // return result; // } // // final float x; // final int space, fieldWidth, valueWidth; // final String labelField, value; // } // Path: src/test/java/mkl/testarea/pdfbox1/content/RenderEndorsement.java import static mkl.testarea.pdfbox1.content.PdfRenderingEndorsementAlternative.BandColumn.Layout.leftHalfPageField; import static mkl.testarea.pdfbox1.content.PdfRenderingEndorsementAlternative.BandColumn.Layout.rightHalfPageField; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import mkl.testarea.pdfbox1.content.PdfRenderingEndorsementAlternative.BandColumn; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.junit.BeforeClass; import org.junit.Test; package mkl.testarea.pdfbox1.content; /** * <a href="http://stackoverflow.com/questions/30767643/pdfbox-issue-while-changing-page"> * PdfBox issue while changing page * </a> * <p> * This test tests the rendering code in {@link PdfRenderingEndorsementAlternative} (which * is an alternative approach to the OP's {@link PdfRenderingEndorsement}) using the data * from the OP's sample file <a href="https://drive.google.com/file/d/0B-z424N1EYicR1BxUUtUSkw4V1U/view?usp=sharing">Endoso-44-17.pdf</a>. * </p> * @author mkl */ public class RenderEndorsement { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } @Test public void testAlternativeQuick() throws IOException, COSVisitorException { String[] header = new String[] { "Daños - Agrícola y de animales", "2015-06-05 / 2016-01-31", "FONDO DE ASEGURAMIENTO AGRÍCOLA 21 DE OCTUBRE", "FNP-00004408003772000" }; try ( InputStream logo = getClass().getResourceAsStream("Logo.jpg") ) { PDDocument document = new PDDocument(); PdfRenderingEndorsementAlternative renderer = new PdfRenderingEndorsementAlternative(document, logo, header); renderer.render(
new BandColumn(leftHalfPageField, "Nombre del contrato/asegurado:", "Prueba Jesus Fac No Prop"),
mkl-public/testarea-pdfbox1
src/test/java/mkl/testarea/pdfbox1/content/OverwriteImage.java
// Path: src/main/java/mkl/testarea/pdfbox1/content/ImageLocator.java // public class ImageLocation // { // public ImageLocation(PDPage page, Matrix matrix, PDXObjectImage image) // { // this.page = page; // this.matrix = matrix; // this.image = image; // } // // public PDPage getPage() // { // return page; // } // // public Matrix getMatrix() // { // return matrix; // } // // public PDXObjectImage getImage() // { // return image; // } // // final PDPage page; // final Matrix matrix; // final PDXObjectImage image; // }
import java.awt.geom.AffineTransform; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.imageio.ImageIO; import mkl.testarea.pdfbox1.content.ImageLocator.ImageLocation; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.exceptions.CryptographyException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg; import org.junit.BeforeClass; import org.junit.Test;
package mkl.testarea.pdfbox1.content; /** * <a href="http://stackoverflow.com/questions/31009949/replacing-images-with-same-resource-in-pdfbox"> * Replacing images with same resource in PDFBox * </a> * <p> * Sample code showing how to overwrite images.. * </p> * * @author mkl */ public class OverwriteImage { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } /** * Applying the code to the OP's sample file from a former question. * * @throws IOException * @throws CryptographyException * @throws COSVisitorException */ @Test public void testDrunkenFistSample() throws IOException, CryptographyException, COSVisitorException { try ( InputStream resource = getClass().getResourceAsStream("sample.pdf"); InputStream left = getClass().getResourceAsStream("left.png"); InputStream right = getClass().getResourceAsStream("right.png"); PDDocument document = PDDocument.load(resource) ) { if (document.isEncrypted()) { document.decrypt(""); } PDJpeg leftImage = new PDJpeg(document, ImageIO.read(left)); PDJpeg rightImage = new PDJpeg(document, ImageIO.read(right)); ImageLocator locator = new ImageLocator(); List<?> allPages = document.getDocumentCatalog().getAllPages(); for (int i = 0; i < allPages.size(); i++) { PDPage page = (PDPage) allPages.get(i); locator.processStream(page, page.findResources(), page.getContents().getStream()); }
// Path: src/main/java/mkl/testarea/pdfbox1/content/ImageLocator.java // public class ImageLocation // { // public ImageLocation(PDPage page, Matrix matrix, PDXObjectImage image) // { // this.page = page; // this.matrix = matrix; // this.image = image; // } // // public PDPage getPage() // { // return page; // } // // public Matrix getMatrix() // { // return matrix; // } // // public PDXObjectImage getImage() // { // return image; // } // // final PDPage page; // final Matrix matrix; // final PDXObjectImage image; // } // Path: src/test/java/mkl/testarea/pdfbox1/content/OverwriteImage.java import java.awt.geom.AffineTransform; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.imageio.ImageIO; import mkl.testarea.pdfbox1.content.ImageLocator.ImageLocation; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.exceptions.CryptographyException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg; import org.junit.BeforeClass; import org.junit.Test; package mkl.testarea.pdfbox1.content; /** * <a href="http://stackoverflow.com/questions/31009949/replacing-images-with-same-resource-in-pdfbox"> * Replacing images with same resource in PDFBox * </a> * <p> * Sample code showing how to overwrite images.. * </p> * * @author mkl */ public class OverwriteImage { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } /** * Applying the code to the OP's sample file from a former question. * * @throws IOException * @throws CryptographyException * @throws COSVisitorException */ @Test public void testDrunkenFistSample() throws IOException, CryptographyException, COSVisitorException { try ( InputStream resource = getClass().getResourceAsStream("sample.pdf"); InputStream left = getClass().getResourceAsStream("left.png"); InputStream right = getClass().getResourceAsStream("right.png"); PDDocument document = PDDocument.load(resource) ) { if (document.isEncrypted()) { document.decrypt(""); } PDJpeg leftImage = new PDJpeg(document, ImageIO.read(left)); PDJpeg rightImage = new PDJpeg(document, ImageIO.read(right)); ImageLocator locator = new ImageLocator(); List<?> allPages = document.getDocumentCatalog().getAllPages(); for (int i = 0; i < allPages.size(); i++) { PDPage page = (PDPage) allPages.get(i); locator.processStream(page, page.findResources(), page.getContents().getStream()); }
for (ImageLocation location : locator.getLocations())
NightscoutFoundation/xDrip
wear/src/main/java/com/eveningoutpost/dexdrip/NFCReaderX.java
// Path: wear/src/main/java/com/eveningoutpost/dexdrip/Models/GlucoseData.java // public class GlucoseData implements Comparable<GlucoseData> { // // public long realDate; // public String sensorId; // public long sensorTime; // public int glucoseLevel = -1; // public int glucoseLevelRaw = -1; // public long phoneDatabaseId; // public int glucoseLevelRawSmoothed; // // public GlucoseData(){} // // // jamorham added constructor // public GlucoseData(int glucoseLevelRaw, long timestamp) { // this.glucoseLevelRaw = glucoseLevelRaw; // this.realDate = timestamp; // } // // public String glucose(boolean mmol) { // return glucose(glucoseLevel, mmol); // } // // public static String glucose(int mgdl, boolean mmol) { // return mmol ? new DecimalFormat("##.0").format(mgdl/18f) : String.valueOf(mgdl); // } // // @Override // public int compareTo(GlucoseData another) { // return (int) (realDate - another.realDate); // } // }
import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.nfc.NfcAdapter; import android.nfc.NfcManager; import android.nfc.Tag; import android.nfc.tech.NfcV; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.Vibrator; import android.view.View; import com.eveningoutpost.dexdrip.ImportedLibraries.usbserial.util.HexDump; import com.eveningoutpost.dexdrip.Models.GlucoseData; import com.eveningoutpost.dexdrip.Models.JoH; import com.eveningoutpost.dexdrip.Models.LibreBlock; import com.eveningoutpost.dexdrip.Models.LibreOOPAlgorithm; import com.eveningoutpost.dexdrip.Models.ReadingData; import com.eveningoutpost.dexdrip.Models.UserError.Log; import com.eveningoutpost.dexdrip.UtilityModels.LibreUtils; import com.eveningoutpost.dexdrip.UtilityModels.PersistentStore; import com.eveningoutpost.dexdrip.UtilityModels.Pref; import com.eveningoutpost.dexdrip.utils.DexCollectionType; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static com.eveningoutpost.dexdrip.xdrip.gs;
} if (d) Log.d(TAG, "Tag data reader exiting"); return tag; } finally { read_lock.unlock(); Home.staticBlockUI(context, false); } } else { Log.d(TAG, "Already read_locked! - skipping"); return null; } } } public static ReadingData parseData(int attempt, String tagId, byte[] data, Long CaptureDateTime) { int indexTrend = data[26] & 0xFF; int indexHistory = data[27] & 0xFF; // double check this bitmask? should be lower? final int sensorTime = 256 * (data[317] & 0xFF) + (data[316] & 0xFF); long sensorStartTime = CaptureDateTime - sensorTime * MINUTE; // option to use 13 bit mask //final boolean thirteen_bit_mask = Pref.getBooleanDefaultFalse("testing_use_thirteen_bit_mask"); final boolean thirteen_bit_mask = true;
// Path: wear/src/main/java/com/eveningoutpost/dexdrip/Models/GlucoseData.java // public class GlucoseData implements Comparable<GlucoseData> { // // public long realDate; // public String sensorId; // public long sensorTime; // public int glucoseLevel = -1; // public int glucoseLevelRaw = -1; // public long phoneDatabaseId; // public int glucoseLevelRawSmoothed; // // public GlucoseData(){} // // // jamorham added constructor // public GlucoseData(int glucoseLevelRaw, long timestamp) { // this.glucoseLevelRaw = glucoseLevelRaw; // this.realDate = timestamp; // } // // public String glucose(boolean mmol) { // return glucose(glucoseLevel, mmol); // } // // public static String glucose(int mgdl, boolean mmol) { // return mmol ? new DecimalFormat("##.0").format(mgdl/18f) : String.valueOf(mgdl); // } // // @Override // public int compareTo(GlucoseData another) { // return (int) (realDate - another.realDate); // } // } // Path: wear/src/main/java/com/eveningoutpost/dexdrip/NFCReaderX.java import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.nfc.NfcAdapter; import android.nfc.NfcManager; import android.nfc.Tag; import android.nfc.tech.NfcV; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.Vibrator; import android.view.View; import com.eveningoutpost.dexdrip.ImportedLibraries.usbserial.util.HexDump; import com.eveningoutpost.dexdrip.Models.GlucoseData; import com.eveningoutpost.dexdrip.Models.JoH; import com.eveningoutpost.dexdrip.Models.LibreBlock; import com.eveningoutpost.dexdrip.Models.LibreOOPAlgorithm; import com.eveningoutpost.dexdrip.Models.ReadingData; import com.eveningoutpost.dexdrip.Models.UserError.Log; import com.eveningoutpost.dexdrip.UtilityModels.LibreUtils; import com.eveningoutpost.dexdrip.UtilityModels.PersistentStore; import com.eveningoutpost.dexdrip.UtilityModels.Pref; import com.eveningoutpost.dexdrip.utils.DexCollectionType; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static com.eveningoutpost.dexdrip.xdrip.gs; } if (d) Log.d(TAG, "Tag data reader exiting"); return tag; } finally { read_lock.unlock(); Home.staticBlockUI(context, false); } } else { Log.d(TAG, "Already read_locked! - skipping"); return null; } } } public static ReadingData parseData(int attempt, String tagId, byte[] data, Long CaptureDateTime) { int indexTrend = data[26] & 0xFF; int indexHistory = data[27] & 0xFF; // double check this bitmask? should be lower? final int sensorTime = 256 * (data[317] & 0xFF) + (data[316] & 0xFF); long sensorStartTime = CaptureDateTime - sensorTime * MINUTE; // option to use 13 bit mask //final boolean thirteen_bit_mask = Pref.getBooleanDefaultFalse("testing_use_thirteen_bit_mask"); final boolean thirteen_bit_mask = true;
ArrayList<GlucoseData> historyList = new ArrayList<>();
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/Structure/ItemStructure.java
// Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemObject.java // public enum OBJECT_TYPE // { // OBJECT, // BOOLEAN, // STRING, // INTEGER, // ELEMENT, // NODELIST // };
import java.util.HashMap; import java.util.Map; import com.ibm.datapower.er.Analytics.Structure.ItemObject.OBJECT_TYPE;
/** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class ItemStructure { public ItemStructure() { } public ItemObject getItem(String name) { ItemObject val = (ItemObject) mItems.get(name); return val; }
// Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemObject.java // public enum OBJECT_TYPE // { // OBJECT, // BOOLEAN, // STRING, // INTEGER, // ELEMENT, // NODELIST // }; // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemStructure.java import java.util.HashMap; import java.util.Map; import com.ibm.datapower.er.Analytics.Structure.ItemObject.OBJECT_TYPE; /** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class ItemStructure { public ItemStructure() { } public ItemObject getItem(String name) { ItemObject val = (ItemObject) mItems.get(name); return val; }
public void addItem(String name, Object obj, OBJECT_TYPE type)
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/AnalyticsResults.java
// Path: framework/src/com/ibm/datapower/er/Analytics/AnalyticsProcessor.java // public enum PRINT_MET_CONDITIONS { // HIDEALL, HIDEDEFAULT, SHOWALL // } // // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java // public enum LogLevelType { // INFO, WARNING, ERROR, CRITICAL // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import com.ibm.datapower.er.Analytics.AnalyticsProcessor.PRINT_MET_CONDITIONS; import com.ibm.datapower.er.Analytics.ConditionsNode.LogLevelType;
/** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics; public class AnalyticsResults { public static void PrintResultsXML(AnalyticsProcessor analytics, ArrayList<ConditionsNode> formulaConditionsMet,
// Path: framework/src/com/ibm/datapower/er/Analytics/AnalyticsProcessor.java // public enum PRINT_MET_CONDITIONS { // HIDEALL, HIDEDEFAULT, SHOWALL // } // // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java // public enum LogLevelType { // INFO, WARNING, ERROR, CRITICAL // } // Path: framework/src/com/ibm/datapower/er/Analytics/AnalyticsResults.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import com.ibm.datapower.er.Analytics.AnalyticsProcessor.PRINT_MET_CONDITIONS; import com.ibm.datapower.er.Analytics.ConditionsNode.LogLevelType; /** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics; public class AnalyticsResults { public static void PrintResultsXML(AnalyticsProcessor analytics, ArrayList<ConditionsNode> formulaConditionsMet,
PRINT_MET_CONDITIONS printConditions, PrintStream stream, String versionAttrib, String outFile,
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/AnalyticsResults.java
// Path: framework/src/com/ibm/datapower/er/Analytics/AnalyticsProcessor.java // public enum PRINT_MET_CONDITIONS { // HIDEALL, HIDEDEFAULT, SHOWALL // } // // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java // public enum LogLevelType { // INFO, WARNING, ERROR, CRITICAL // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import com.ibm.datapower.er.Analytics.AnalyticsProcessor.PRINT_MET_CONDITIONS; import com.ibm.datapower.er.Analytics.ConditionsNode.LogLevelType;
e.printStackTrace(); } } private static ArrayList<ConditionsNode> reorderMetConditions(AnalyticsProcessor analytics, String outFile, ArrayList<ConditionsNode> inNodes) { ArrayList<ConditionsNode> overrideList = new ArrayList<ConditionsNode>(); // general categories ArrayList<ConditionsNode> infoList = new ArrayList<ConditionsNode>(); ArrayList<ConditionsNode> warnList = new ArrayList<ConditionsNode>(); ArrayList<ConditionsNode> errorList = new ArrayList<ConditionsNode>(); ArrayList<ConditionsNode> criticalList = new ArrayList<ConditionsNode>(); for (int i = 0; i < inNodes.size(); i++) { ConditionsNode node = inNodes.get(i); if (node.getPopupFileName().length() > 0) { File file = new File(outFile); File parentDir = file.getParentFile(); // get parent dir String dir = parentDir.getPath(); if (dir.contains(":\\")) dir += "\\"; else dir += "/"; CreateSubFile(analytics, dir, node.getPopupFileName()); } if (node.isTopCondition()) overrideList.add(node);
// Path: framework/src/com/ibm/datapower/er/Analytics/AnalyticsProcessor.java // public enum PRINT_MET_CONDITIONS { // HIDEALL, HIDEDEFAULT, SHOWALL // } // // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java // public enum LogLevelType { // INFO, WARNING, ERROR, CRITICAL // } // Path: framework/src/com/ibm/datapower/er/Analytics/AnalyticsResults.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import com.ibm.datapower.er.Analytics.AnalyticsProcessor.PRINT_MET_CONDITIONS; import com.ibm.datapower.er.Analytics.ConditionsNode.LogLevelType; e.printStackTrace(); } } private static ArrayList<ConditionsNode> reorderMetConditions(AnalyticsProcessor analytics, String outFile, ArrayList<ConditionsNode> inNodes) { ArrayList<ConditionsNode> overrideList = new ArrayList<ConditionsNode>(); // general categories ArrayList<ConditionsNode> infoList = new ArrayList<ConditionsNode>(); ArrayList<ConditionsNode> warnList = new ArrayList<ConditionsNode>(); ArrayList<ConditionsNode> errorList = new ArrayList<ConditionsNode>(); ArrayList<ConditionsNode> criticalList = new ArrayList<ConditionsNode>(); for (int i = 0; i < inNodes.size(); i++) { ConditionsNode node = inNodes.get(i); if (node.getPopupFileName().length() > 0) { File file = new File(outFile); File parentDir = file.getParentFile(); // get parent dir String dir = parentDir.getPath(); if (dir.contains(":\\")) dir += "\\"; else dir += "/"; CreateSubFile(analytics, dir, node.getPopupFileName()); } if (node.isTopCondition()) overrideList.add(node);
else if (node.getLogLevel() == LogLevelType.INFO)
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/Structure/DSCacheEntry.java
// Path: framework/src/com/ibm/datapower/er/Analytics/DocumentSection.java // public class DocumentSection { // public DocumentSection(Document doc, String cidName, String outFileExtension, ERFramework framework, int phase, // String phaseFileName) { // mCidDoc = doc; // // need to remove the tags so it shows up in HTML // mOrigCidName = cidName; // mCidName = cidName.replace("<", "[").replace(">", "]"); // // if (outFileExtension != null) // mOutExtension = outFileExtension; // // NodeList nl = doc.getElementsByTagName("Root"); // if (nl.getLength() == 0) // mIsXML = true; // // mFramework = framework; // // mPhase = phase; // // mPhaseFileName = phaseFileName; // } // // public Document GetDocument() { // return mCidDoc; // } // // public String GetSectionName() { // return mCidName; // } // // public String GetOriginalSectionName() { // return mOrigCidName; // } // // public boolean IsXMLSection() { // return mIsXML; // } // // public int GetCacheHits() { // return mCacheHits; // } // // public void HitCache() { // mCacheHits++; // } // // public String GetOutExtension() { // return mOutExtension; // } // // public ERFramework GetFramework() { // return mFramework; // } // // public int GetPhase() { // return mPhase; // } // // public String GetPhaseFileName() { // return mPhaseFileName; // } // // private Document mCidDoc = null; // private String mCidName = ""; // private String mOrigCidName = ""; // private boolean mIsXML = false; // private int mCacheHits = 0; // private String mOutExtension = ""; // private ERFramework mFramework = null; // public int mPhase = 0; // private String mPhaseFileName = ""; // }
import java.util.ArrayList; import com.ibm.datapower.er.Analytics.DocumentSection;
/** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class DSCacheEntry { // keeping data quickly accessible so we can pull it out and re-use for formula processing public String cidName = "";
// Path: framework/src/com/ibm/datapower/er/Analytics/DocumentSection.java // public class DocumentSection { // public DocumentSection(Document doc, String cidName, String outFileExtension, ERFramework framework, int phase, // String phaseFileName) { // mCidDoc = doc; // // need to remove the tags so it shows up in HTML // mOrigCidName = cidName; // mCidName = cidName.replace("<", "[").replace(">", "]"); // // if (outFileExtension != null) // mOutExtension = outFileExtension; // // NodeList nl = doc.getElementsByTagName("Root"); // if (nl.getLength() == 0) // mIsXML = true; // // mFramework = framework; // // mPhase = phase; // // mPhaseFileName = phaseFileName; // } // // public Document GetDocument() { // return mCidDoc; // } // // public String GetSectionName() { // return mCidName; // } // // public String GetOriginalSectionName() { // return mOrigCidName; // } // // public boolean IsXMLSection() { // return mIsXML; // } // // public int GetCacheHits() { // return mCacheHits; // } // // public void HitCache() { // mCacheHits++; // } // // public String GetOutExtension() { // return mOutExtension; // } // // public ERFramework GetFramework() { // return mFramework; // } // // public int GetPhase() { // return mPhase; // } // // public String GetPhaseFileName() { // return mPhaseFileName; // } // // private Document mCidDoc = null; // private String mCidName = ""; // private String mOrigCidName = ""; // private boolean mIsXML = false; // private int mCacheHits = 0; // private String mOutExtension = ""; // private ERFramework mFramework = null; // public int mPhase = 0; // private String mPhaseFileName = ""; // } // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/DSCacheEntry.java import java.util.ArrayList; import com.ibm.datapower.er.Analytics.DocumentSection; /** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class DSCacheEntry { // keeping data quickly accessible so we can pull it out and re-use for formula processing public String cidName = "";
public ArrayList<DocumentSection> documentSet = new ArrayList<DocumentSection>();
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java
// Path: framework/src/com/ibm/datapower/er/Analytics/MappedCondition.java // public enum MAPPED_TABLE_POSITION { // NO_SET(-2), // AUTO_SET(-1); // // private final int type; // private MAPPED_TABLE_POSITION(int type) { // this.type = type; // } // // public int getType() { // return type; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.ibm.datapower.er.Analytics.MappedCondition.MAPPED_TABLE_POSITION;
public void appendURI(String attrib) { if (uriArguments.length() > 0) uriArguments += "&"; uriArguments += attrib; }; public String getURIAttributes() { return uriArguments; } public void setPopupFileName(String popup) { mPopupFileName = popup; } public String getPopupFileName() { return mPopupFileName; } public void addCondition(String condName, String value, int forcePosition) { // instead of bothering to check if it exists, just remove if its there // or not // we overwrite entries instead of adding the same name synchronized(mMappedConditions) { mMappedConditions.remove(condName); } // -1 = passed as 'set me' // -2 = passed as 'dont use me for pipe tables in AnalyticsResults' int posToSet = forcePosition;
// Path: framework/src/com/ibm/datapower/er/Analytics/MappedCondition.java // public enum MAPPED_TABLE_POSITION { // NO_SET(-2), // AUTO_SET(-1); // // private final int type; // private MAPPED_TABLE_POSITION(int type) { // this.type = type; // } // // public int getType() { // return type; // } // } // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.ibm.datapower.er.Analytics.MappedCondition.MAPPED_TABLE_POSITION; public void appendURI(String attrib) { if (uriArguments.length() > 0) uriArguments += "&"; uriArguments += attrib; }; public String getURIAttributes() { return uriArguments; } public void setPopupFileName(String popup) { mPopupFileName = popup; } public String getPopupFileName() { return mPopupFileName; } public void addCondition(String condName, String value, int forcePosition) { // instead of bothering to check if it exists, just remove if its there // or not // we overwrite entries instead of adding the same name synchronized(mMappedConditions) { mMappedConditions.remove(condName); } // -1 = passed as 'set me' // -2 = passed as 'dont use me for pipe tables in AnalyticsResults' int posToSet = forcePosition;
if ( posToSet == MAPPED_TABLE_POSITION.AUTO_SET.getType() )
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/Structure/Formula.java
// Path: framework/src/com/ibm/datapower/er/FirmwareInputStream.java // public class FirmwareInputStream extends InputStream { // InputStream mInputStream; // ErrorReportDetails mErrorReportDetails; // ByteArrayOutputStream mByteArrayOut; // ByteArrayInputStream mByteArrayIn; // // /** // * Default constructor. called the InputStream constructor // */ // public FirmwareInputStream() { // super(); // } // // /** // * Constructor that sets the InputStream and ErrorReportDetails // * Will also load the ErrorReportDetails with the appropriate information // * @param is the InputStream to set mInputStream to // * @param erd the ErrorReportDetails to set the mErrorReportDetails to // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public FirmwareInputStream(InputStream is, ErrorReportDetails erd) throws SAXException, IOException, ParserConfigurationException { // mInputStream = is; // mErrorReportDetails = erd; // mByteArrayOut = new ByteArrayOutputStream(); // } // /** // * fills in the mByteArrayInputStream with the information from mInputStream // * uses mByteArrayInputStream in a DOMParser to parse the XML and fill in the ErrorReportDetails // * // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public void loadERD() { // try { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(mByteArrayIn); // doc.getDocumentElement().normalize(); // // // Element eElement = (Element) doc.getElementsByTagName("FirmwareVersion").item(0); // // mErrorReportDetails.setSerial(getValueByTag("Serial", eElement)); // mErrorReportDetails.setVersion(getValueByTag("Version", eElement)); // mErrorReportDetails.setBuild(getValueByTag("Build", eElement)); // mErrorReportDetails.setBuildDate(getValueByTag("BuildDate", eElement)); // mErrorReportDetails.setWatchdogBuild(getValueByTag("WatchdogBuild", eElement)); // mErrorReportDetails.setInstalledDPOS(getValueByTag("InstalledDPOS", eElement)); // mErrorReportDetails.setRunningDPOS(getValueByTag("RunningDPOS", eElement)); // mErrorReportDetails.setXMLAccelerator(getValueByTag("XMLAccelerator", eElement)); // mErrorReportDetails.setMachineType(getValueByTag("MachineType", eElement)); // mErrorReportDetails.setModelType(getValueByTag("ModelType", eElement)); // } catch (SAXException e) { // e.printStackTrace(); // } catch (IOException ioe) { // ioe.printStackTrace(); // } catch (ParserConfigurationException pce){ // pce.printStackTrace(); // } // } // // /** // * Gets Value of an XML element by tag name // * @param sTag the string value representation of the tag name // * @param eElement the element in which to look for the tag nane // * @return String value of the XML element // */ // public static String getValueByTag(String sTag, Element eElement){ // try // { // NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); // Node nValue = (Node) nlList.item(0); // // // null check added May 30th (DisplayMessage was an empty node) // if ( nValue == null ) // return ""; // // return nValue.getNodeValue(); // }catch(Exception ex) // { // } // // return ""; // } // // @Override // public int read() throws IOException { // int b = mInputStream.read(); // //if b is not endoffile // if(b != -1){ // //add b to byte array outputstream; // mByteArrayOut.write(b); // } else { // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // loadERD(); // } // return b; // } // @Override // public int read(byte[] byteArray) throws IOException { // int bytesRead = mInputStream.read(byteArray); // // mByteArrayOut.write(byteArray, 0, bytesRead); // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // // loadERD(); // return bytesRead; // } // // } // // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemObject.java // public enum OBJECT_TYPE // { // OBJECT, // BOOLEAN, // STRING, // INTEGER, // ELEMENT, // NODELIST // };
import org.w3c.dom.Element; import com.ibm.datapower.er.FirmwareInputStream; import com.ibm.datapower.er.Analytics.Structure.ItemObject.OBJECT_TYPE;
/** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class Formula extends ItemStructure { public Formula(Element fElement, int id, boolean multiDocs) {
// Path: framework/src/com/ibm/datapower/er/FirmwareInputStream.java // public class FirmwareInputStream extends InputStream { // InputStream mInputStream; // ErrorReportDetails mErrorReportDetails; // ByteArrayOutputStream mByteArrayOut; // ByteArrayInputStream mByteArrayIn; // // /** // * Default constructor. called the InputStream constructor // */ // public FirmwareInputStream() { // super(); // } // // /** // * Constructor that sets the InputStream and ErrorReportDetails // * Will also load the ErrorReportDetails with the appropriate information // * @param is the InputStream to set mInputStream to // * @param erd the ErrorReportDetails to set the mErrorReportDetails to // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public FirmwareInputStream(InputStream is, ErrorReportDetails erd) throws SAXException, IOException, ParserConfigurationException { // mInputStream = is; // mErrorReportDetails = erd; // mByteArrayOut = new ByteArrayOutputStream(); // } // /** // * fills in the mByteArrayInputStream with the information from mInputStream // * uses mByteArrayInputStream in a DOMParser to parse the XML and fill in the ErrorReportDetails // * // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public void loadERD() { // try { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(mByteArrayIn); // doc.getDocumentElement().normalize(); // // // Element eElement = (Element) doc.getElementsByTagName("FirmwareVersion").item(0); // // mErrorReportDetails.setSerial(getValueByTag("Serial", eElement)); // mErrorReportDetails.setVersion(getValueByTag("Version", eElement)); // mErrorReportDetails.setBuild(getValueByTag("Build", eElement)); // mErrorReportDetails.setBuildDate(getValueByTag("BuildDate", eElement)); // mErrorReportDetails.setWatchdogBuild(getValueByTag("WatchdogBuild", eElement)); // mErrorReportDetails.setInstalledDPOS(getValueByTag("InstalledDPOS", eElement)); // mErrorReportDetails.setRunningDPOS(getValueByTag("RunningDPOS", eElement)); // mErrorReportDetails.setXMLAccelerator(getValueByTag("XMLAccelerator", eElement)); // mErrorReportDetails.setMachineType(getValueByTag("MachineType", eElement)); // mErrorReportDetails.setModelType(getValueByTag("ModelType", eElement)); // } catch (SAXException e) { // e.printStackTrace(); // } catch (IOException ioe) { // ioe.printStackTrace(); // } catch (ParserConfigurationException pce){ // pce.printStackTrace(); // } // } // // /** // * Gets Value of an XML element by tag name // * @param sTag the string value representation of the tag name // * @param eElement the element in which to look for the tag nane // * @return String value of the XML element // */ // public static String getValueByTag(String sTag, Element eElement){ // try // { // NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); // Node nValue = (Node) nlList.item(0); // // // null check added May 30th (DisplayMessage was an empty node) // if ( nValue == null ) // return ""; // // return nValue.getNodeValue(); // }catch(Exception ex) // { // } // // return ""; // } // // @Override // public int read() throws IOException { // int b = mInputStream.read(); // //if b is not endoffile // if(b != -1){ // //add b to byte array outputstream; // mByteArrayOut.write(b); // } else { // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // loadERD(); // } // return b; // } // @Override // public int read(byte[] byteArray) throws IOException { // int bytesRead = mInputStream.read(byteArray); // // mByteArrayOut.write(byteArray, 0, bytesRead); // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // // loadERD(); // return bytesRead; // } // // } // // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemObject.java // public enum OBJECT_TYPE // { // OBJECT, // BOOLEAN, // STRING, // INTEGER, // ELEMENT, // NODELIST // }; // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/Formula.java import org.w3c.dom.Element; import com.ibm.datapower.er.FirmwareInputStream; import com.ibm.datapower.er.Analytics.Structure.ItemObject.OBJECT_TYPE; /** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class Formula extends ItemStructure { public Formula(Element fElement, int id, boolean multiDocs) {
addItem("ID", id, OBJECT_TYPE.INTEGER);
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/Structure/Formula.java
// Path: framework/src/com/ibm/datapower/er/FirmwareInputStream.java // public class FirmwareInputStream extends InputStream { // InputStream mInputStream; // ErrorReportDetails mErrorReportDetails; // ByteArrayOutputStream mByteArrayOut; // ByteArrayInputStream mByteArrayIn; // // /** // * Default constructor. called the InputStream constructor // */ // public FirmwareInputStream() { // super(); // } // // /** // * Constructor that sets the InputStream and ErrorReportDetails // * Will also load the ErrorReportDetails with the appropriate information // * @param is the InputStream to set mInputStream to // * @param erd the ErrorReportDetails to set the mErrorReportDetails to // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public FirmwareInputStream(InputStream is, ErrorReportDetails erd) throws SAXException, IOException, ParserConfigurationException { // mInputStream = is; // mErrorReportDetails = erd; // mByteArrayOut = new ByteArrayOutputStream(); // } // /** // * fills in the mByteArrayInputStream with the information from mInputStream // * uses mByteArrayInputStream in a DOMParser to parse the XML and fill in the ErrorReportDetails // * // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public void loadERD() { // try { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(mByteArrayIn); // doc.getDocumentElement().normalize(); // // // Element eElement = (Element) doc.getElementsByTagName("FirmwareVersion").item(0); // // mErrorReportDetails.setSerial(getValueByTag("Serial", eElement)); // mErrorReportDetails.setVersion(getValueByTag("Version", eElement)); // mErrorReportDetails.setBuild(getValueByTag("Build", eElement)); // mErrorReportDetails.setBuildDate(getValueByTag("BuildDate", eElement)); // mErrorReportDetails.setWatchdogBuild(getValueByTag("WatchdogBuild", eElement)); // mErrorReportDetails.setInstalledDPOS(getValueByTag("InstalledDPOS", eElement)); // mErrorReportDetails.setRunningDPOS(getValueByTag("RunningDPOS", eElement)); // mErrorReportDetails.setXMLAccelerator(getValueByTag("XMLAccelerator", eElement)); // mErrorReportDetails.setMachineType(getValueByTag("MachineType", eElement)); // mErrorReportDetails.setModelType(getValueByTag("ModelType", eElement)); // } catch (SAXException e) { // e.printStackTrace(); // } catch (IOException ioe) { // ioe.printStackTrace(); // } catch (ParserConfigurationException pce){ // pce.printStackTrace(); // } // } // // /** // * Gets Value of an XML element by tag name // * @param sTag the string value representation of the tag name // * @param eElement the element in which to look for the tag nane // * @return String value of the XML element // */ // public static String getValueByTag(String sTag, Element eElement){ // try // { // NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); // Node nValue = (Node) nlList.item(0); // // // null check added May 30th (DisplayMessage was an empty node) // if ( nValue == null ) // return ""; // // return nValue.getNodeValue(); // }catch(Exception ex) // { // } // // return ""; // } // // @Override // public int read() throws IOException { // int b = mInputStream.read(); // //if b is not endoffile // if(b != -1){ // //add b to byte array outputstream; // mByteArrayOut.write(b); // } else { // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // loadERD(); // } // return b; // } // @Override // public int read(byte[] byteArray) throws IOException { // int bytesRead = mInputStream.read(byteArray); // // mByteArrayOut.write(byteArray, 0, bytesRead); // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // // loadERD(); // return bytesRead; // } // // } // // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemObject.java // public enum OBJECT_TYPE // { // OBJECT, // BOOLEAN, // STRING, // INTEGER, // ELEMENT, // NODELIST // };
import org.w3c.dom.Element; import com.ibm.datapower.er.FirmwareInputStream; import com.ibm.datapower.er.Analytics.Structure.ItemObject.OBJECT_TYPE;
/** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class Formula extends ItemStructure { public Formula(Element fElement, int id, boolean multiDocs) { addItem("ID", id, OBJECT_TYPE.INTEGER); addItem("Element", fElement, OBJECT_TYPE.ELEMENT); // the header 'name' of the formula, this will require parsing of { // } tag sections which denote XML sections we pull from // expressions // <Name>This is an error!</Name>
// Path: framework/src/com/ibm/datapower/er/FirmwareInputStream.java // public class FirmwareInputStream extends InputStream { // InputStream mInputStream; // ErrorReportDetails mErrorReportDetails; // ByteArrayOutputStream mByteArrayOut; // ByteArrayInputStream mByteArrayIn; // // /** // * Default constructor. called the InputStream constructor // */ // public FirmwareInputStream() { // super(); // } // // /** // * Constructor that sets the InputStream and ErrorReportDetails // * Will also load the ErrorReportDetails with the appropriate information // * @param is the InputStream to set mInputStream to // * @param erd the ErrorReportDetails to set the mErrorReportDetails to // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public FirmwareInputStream(InputStream is, ErrorReportDetails erd) throws SAXException, IOException, ParserConfigurationException { // mInputStream = is; // mErrorReportDetails = erd; // mByteArrayOut = new ByteArrayOutputStream(); // } // /** // * fills in the mByteArrayInputStream with the information from mInputStream // * uses mByteArrayInputStream in a DOMParser to parse the XML and fill in the ErrorReportDetails // * // * @throws SAXException // * @throws IOException // * @throws ParserConfigurationException // */ // public void loadERD() { // try { // DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Document doc = dBuilder.parse(mByteArrayIn); // doc.getDocumentElement().normalize(); // // // Element eElement = (Element) doc.getElementsByTagName("FirmwareVersion").item(0); // // mErrorReportDetails.setSerial(getValueByTag("Serial", eElement)); // mErrorReportDetails.setVersion(getValueByTag("Version", eElement)); // mErrorReportDetails.setBuild(getValueByTag("Build", eElement)); // mErrorReportDetails.setBuildDate(getValueByTag("BuildDate", eElement)); // mErrorReportDetails.setWatchdogBuild(getValueByTag("WatchdogBuild", eElement)); // mErrorReportDetails.setInstalledDPOS(getValueByTag("InstalledDPOS", eElement)); // mErrorReportDetails.setRunningDPOS(getValueByTag("RunningDPOS", eElement)); // mErrorReportDetails.setXMLAccelerator(getValueByTag("XMLAccelerator", eElement)); // mErrorReportDetails.setMachineType(getValueByTag("MachineType", eElement)); // mErrorReportDetails.setModelType(getValueByTag("ModelType", eElement)); // } catch (SAXException e) { // e.printStackTrace(); // } catch (IOException ioe) { // ioe.printStackTrace(); // } catch (ParserConfigurationException pce){ // pce.printStackTrace(); // } // } // // /** // * Gets Value of an XML element by tag name // * @param sTag the string value representation of the tag name // * @param eElement the element in which to look for the tag nane // * @return String value of the XML element // */ // public static String getValueByTag(String sTag, Element eElement){ // try // { // NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); // Node nValue = (Node) nlList.item(0); // // // null check added May 30th (DisplayMessage was an empty node) // if ( nValue == null ) // return ""; // // return nValue.getNodeValue(); // }catch(Exception ex) // { // } // // return ""; // } // // @Override // public int read() throws IOException { // int b = mInputStream.read(); // //if b is not endoffile // if(b != -1){ // //add b to byte array outputstream; // mByteArrayOut.write(b); // } else { // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // loadERD(); // } // return b; // } // @Override // public int read(byte[] byteArray) throws IOException { // int bytesRead = mInputStream.read(byteArray); // // mByteArrayOut.write(byteArray, 0, bytesRead); // mByteArrayIn = new ByteArrayInputStream(mByteArrayOut.toByteArray()); // // loadERD(); // return bytesRead; // } // // } // // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/ItemObject.java // public enum OBJECT_TYPE // { // OBJECT, // BOOLEAN, // STRING, // INTEGER, // ELEMENT, // NODELIST // }; // Path: framework/src/com/ibm/datapower/er/Analytics/Structure/Formula.java import org.w3c.dom.Element; import com.ibm.datapower.er.FirmwareInputStream; import com.ibm.datapower.er.Analytics.Structure.ItemObject.OBJECT_TYPE; /** * Copyright 2014-2020 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.datapower.er.Analytics.Structure; public class Formula extends ItemStructure { public Formula(Element fElement, int id, boolean multiDocs) { addItem("ID", id, OBJECT_TYPE.INTEGER); addItem("Element", fElement, OBJECT_TYPE.ELEMENT); // the header 'name' of the formula, this will require parsing of { // } tag sections which denote XML sections we pull from // expressions // <Name>This is an error!</Name>
String dispName = FirmwareInputStream.getValueByTag("Name", fElement);
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/ConditionField.java
// Path: framework/src/com/ibm/datapower/er/Analytics/MappedCondition.java // public enum MAPPED_TABLE_POSITION { // NO_SET(-2), // AUTO_SET(-1); // // private final int type; // private MAPPED_TABLE_POSITION(int type) { // this.type = type; // } // // public int getType() { // return type; // } // }
import com.ibm.datapower.er.Analytics.MappedCondition.MAPPED_TABLE_POSITION;
MATCH_ENUMERATION(0), MATCH_ALLREGGROUP(1), MATCH_ORDERED(2), MATCH_ALL_RESULT(3), // ALL_RESULT and ORDERED inherit ALLREGGROUP, COUNT and NONE do not use regular expression grouping MATCH_COUNT(4), MATCH_SUM(5), MATCH_NONE(6); private final int type; private REG_GROUP_TYPE(int type) { this.type = type; } public int getType() { return type; } } private String mRegGroup = ""; private REG_GROUP_TYPE mRegGroupType = REG_GROUP_TYPE.MATCH_NONE; private String mConditionName = ""; private String mOperation = ""; private String mValue = ""; private String mCondRegExp = ""; private String mCondNextOperation = ""; private boolean mConditionOperAnd = false; private String mConversionType = ""; private String mOverrideValue = "";
// Path: framework/src/com/ibm/datapower/er/Analytics/MappedCondition.java // public enum MAPPED_TABLE_POSITION { // NO_SET(-2), // AUTO_SET(-1); // // private final int type; // private MAPPED_TABLE_POSITION(int type) { // this.type = type; // } // // public int getType() { // return type; // } // } // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionField.java import com.ibm.datapower.er.Analytics.MappedCondition.MAPPED_TABLE_POSITION; MATCH_ENUMERATION(0), MATCH_ALLREGGROUP(1), MATCH_ORDERED(2), MATCH_ALL_RESULT(3), // ALL_RESULT and ORDERED inherit ALLREGGROUP, COUNT and NONE do not use regular expression grouping MATCH_COUNT(4), MATCH_SUM(5), MATCH_NONE(6); private final int type; private REG_GROUP_TYPE(int type) { this.type = type; } public int getType() { return type; } } private String mRegGroup = ""; private REG_GROUP_TYPE mRegGroupType = REG_GROUP_TYPE.MATCH_NONE; private String mConditionName = ""; private String mOperation = ""; private String mValue = ""; private String mCondRegExp = ""; private String mCondNextOperation = ""; private boolean mConditionOperAnd = false; private String mConversionType = ""; private String mOverrideValue = "";
private int mMappedTablePosition = MAPPED_TABLE_POSITION.AUTO_SET.getType();
ibm-datapower/ertool
framework/src/com/ibm/datapower/er/Analytics/ConditionSort.java
// Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java // public enum ConditionSortType { // DEFAULT, TIMESTAMP // }
import java.text.SimpleDateFormat; import java.util.Comparator; import com.ibm.datapower.er.Analytics.ConditionsNode.ConditionSortType;
if (o1.getSortConditionName().length() < 1 || o2.getSortConditionName().length() < 1) { if (!o1.getSortMethod().equals("descending")) { if ( o1.getConditionID() > o2.getConditionID() ) return 1; else return 0; } else { if ( o1.getConditionID() > o2.getConditionID() ) return -1; else return 0; } } String condO1 = ""; String condO2 = ""; if (o1.getSortConditionName().equals("condensecondition") && o2.getSortConditionName().equals("condensecondition")) { condO1 = Integer.toString(o1.getCondenseCount()); condO2 = Integer.toString(o2.getCondenseCount()); } else { condO1 = o1.getCondition(o1.getSortConditionName()); condO2 = o2.getCondition(o2.getSortConditionName()); } boolean useTimestampCompare = false; SimpleDateFormat fmt = null;
// Path: framework/src/com/ibm/datapower/er/Analytics/ConditionsNode.java // public enum ConditionSortType { // DEFAULT, TIMESTAMP // } // Path: framework/src/com/ibm/datapower/er/Analytics/ConditionSort.java import java.text.SimpleDateFormat; import java.util.Comparator; import com.ibm.datapower.er.Analytics.ConditionsNode.ConditionSortType; if (o1.getSortConditionName().length() < 1 || o2.getSortConditionName().length() < 1) { if (!o1.getSortMethod().equals("descending")) { if ( o1.getConditionID() > o2.getConditionID() ) return 1; else return 0; } else { if ( o1.getConditionID() > o2.getConditionID() ) return -1; else return 0; } } String condO1 = ""; String condO2 = ""; if (o1.getSortConditionName().equals("condensecondition") && o2.getSortConditionName().equals("condensecondition")) { condO1 = Integer.toString(o1.getCondenseCount()); condO2 = Integer.toString(o2.getCondenseCount()); } else { condO1 = o1.getCondition(o1.getSortConditionName()); condO2 = o2.getCondition(o2.getSortConditionName()); } boolean useTimestampCompare = false; SimpleDateFormat fmt = null;
if (o1.getSortType() == ConditionSortType.TIMESTAMP && o1.getSortOption().length() > 0) {
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/activity/SettingsActivity.java
// Path: app/src/main/java/com/xargsgrep/portknocker/fragment/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener // { // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.preferences); // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // } // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) // { // if (isAdded() && getString(R.string.pref_key_hide_ports_widget).equals(key)) // { // HostWidget.updateAllAppWidgets(getActivity()); // } // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.fragment.SettingsFragment;
/* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.activity; public class SettingsActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); getFragmentManager() .beginTransaction()
// Path: app/src/main/java/com/xargsgrep/portknocker/fragment/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener // { // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.preferences); // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // } // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) // { // if (isAdded() && getString(R.string.pref_key_hide_ports_widget).equals(key)) // { // HostWidget.updateAllAppWidgets(getActivity()); // } // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/activity/SettingsActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.fragment.SettingsFragment; /* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.activity; public class SettingsActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); getFragmentManager() .beginTransaction()
.replace(R.id.fragment_content, new SettingsFragment())
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/db/DatabaseManager.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP}
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import java.util.ArrayList; import java.util.List;
/* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.db; public class DatabaseManager { private DatabaseHelper databaseHelper; public DatabaseManager(Context context) { databaseHelper = new DatabaseHelper(context); }
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // Path: app/src/main/java/com/xargsgrep/portknocker/db/DatabaseManager.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import java.util.ArrayList; import java.util.List; /* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.db; public class DatabaseManager { private DatabaseHelper databaseHelper; public DatabaseManager(Context context) { databaseHelper = new DatabaseHelper(context); }
public List<Host> getAllHosts()
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/db/DatabaseManager.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP}
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import java.util.ArrayList; import java.util.List;
/* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.db; public class DatabaseManager { private DatabaseHelper databaseHelper; public DatabaseManager(Context context) { databaseHelper = new DatabaseHelper(context); } public List<Host> getAllHosts() { List<Host> hosts = new ArrayList<>(); SQLiteDatabase database = getReadableDatabase(); Cursor hostsCursor = database.query( DatabaseHelper.HOST_TABLE_NAME, DatabaseHelper.HOST_TABLE_COLUMNS, null, null, null, null, DatabaseHelper.HOST_ID_COLUMN ); hostsCursor.moveToFirst(); while (!hostsCursor.isAfterLast()) { Host host = cursorToHost(hostsCursor);
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // Path: app/src/main/java/com/xargsgrep/portknocker/db/DatabaseManager.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import java.util.ArrayList; import java.util.List; /* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.db; public class DatabaseManager { private DatabaseHelper databaseHelper; public DatabaseManager(Context context) { databaseHelper = new DatabaseHelper(context); } public List<Host> getAllHosts() { List<Host> hosts = new ArrayList<>(); SQLiteDatabase database = getReadableDatabase(); Cursor hostsCursor = database.query( DatabaseHelper.HOST_TABLE_NAME, DatabaseHelper.HOST_TABLE_COLUMNS, null, null, null, null, DatabaseHelper.HOST_ID_COLUMN ); hostsCursor.moveToFirst(); while (!hostsCursor.isAfterLast()) { Host host = cursorToHost(hostsCursor);
List<Port> ports = getPortsForHost(database, host.getId());
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/db/DatabaseManager.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP}
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import java.util.ArrayList; import java.util.List;
while (!portsCursor.isAfterLast()) { Port port = cursorToPort(portsCursor); ports.add(port); portsCursor.moveToNext(); } portsCursor.close(); return ports; } private Host cursorToHost(Cursor cursor) { Host host = new Host(); host.setId(cursor.getLong(0)); host.setLabel(cursor.getString(1)); host.setHostname(cursor.getString(2)); host.setDelay(cursor.getInt(3)); host.setLaunchIntentPackage(cursor.getString(4)); host.setTcpConnectTimeout(cursor.getInt(7)); return host; } private Port cursorToPort(Cursor cursor) { Port port = new Port(); port.setHostId(cursor.getLong(0)); port.setIndex(cursor.getInt(1)); port.setPort(cursor.getInt(2));
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // Path: app/src/main/java/com/xargsgrep/portknocker/db/DatabaseManager.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xargsgrep.portknocker.model.Host; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import java.util.ArrayList; import java.util.List; while (!portsCursor.isAfterLast()) { Port port = cursorToPort(portsCursor); ports.add(port); portsCursor.moveToNext(); } portsCursor.close(); return ports; } private Host cursorToHost(Cursor cursor) { Host host = new Host(); host.setId(cursor.getLong(0)); host.setLabel(cursor.getString(1)); host.setHostname(cursor.getString(2)); host.setDelay(cursor.getInt(3)); host.setLaunchIntentPackage(cursor.getString(4)); host.setTcpConnectTimeout(cursor.getInt(7)); return host; } private Port cursorToPort(Cursor cursor) { Port port = new Port(); port.setHostId(cursor.getLong(0)); port.setIndex(cursor.getInt(1)); port.setPort(cursor.getInt(2));
port.setProtocol(Protocol.values()[cursor.getInt(3)]);
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/fragment/SettingsFragment.java
// Path: app/src/main/java/com/xargsgrep/portknocker/widget/HostWidget.java // public class HostWidget extends AppWidgetProvider // { // @Override // public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) // { // for (int appWidgetId : appWidgetIds) // { // long hostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // @Override // public void onDeleted(Context context, int[] appWidgetIds) // { // for (int i = 0; i < appWidgetIds.length; i++) // { // ConfigureWidgetActivity.deleteHostIdPreference(context, appWidgetIds[i]); // } // } // // public static void updateAllAppWidgets(Context context) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, null); // } // } // // public static void updateAllAppWidgetsForHost(Context context, long hostId) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Long hostId) // { // // workaround for phantom widgets // boolean configured = ConfigureWidgetActivity.getConfiguredPreference(context, appWidgetId); // if (!configured) return; // // Long widgetHostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // if (hostId != null && !hostId.equals(widgetHostId)) return; // // DatabaseManager hostDataManager = new DatabaseManager(context); // RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); // // // boolean hostExists = hostDataManager.hostExists(widgetHostId); // if (hostExists) // { // Host host = hostDataManager.getHost(widgetHostId); // // Intent intent = new Intent(context, HostListActivity.class); // intent.putExtra("hostId", widgetHostId); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // // views.setTextViewText(R.id.widget_host_label, host.getLabel()); // views.setTextViewText(R.id.widget_host_hostname, host.getHostname()); // views.setTextViewText(R.id.widget_host_ports, host.getPortsString()); // // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); // if (sharedPreferences.getBoolean(context.getString(R.string.pref_key_hide_ports_widget), false)) // { // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // } // else // { // views.setViewVisibility(R.id.widget_host_ports, View.VISIBLE); // } // } // else // { // views.setTextViewText(R.id.widget_host_label, "Invalid Host"); // views.setViewVisibility(R.id.widget_host_hostname, View.GONE); // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // // Intent intent = new Intent(context, HostListActivity.class); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // } // // appWidgetManager.updateAppWidget(appWidgetId, views); // } // }
import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceFragment; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.widget.HostWidget;
/* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.fragment; public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (isAdded() && getString(R.string.pref_key_hide_ports_widget).equals(key)) {
// Path: app/src/main/java/com/xargsgrep/portknocker/widget/HostWidget.java // public class HostWidget extends AppWidgetProvider // { // @Override // public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) // { // for (int appWidgetId : appWidgetIds) // { // long hostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // @Override // public void onDeleted(Context context, int[] appWidgetIds) // { // for (int i = 0; i < appWidgetIds.length; i++) // { // ConfigureWidgetActivity.deleteHostIdPreference(context, appWidgetIds[i]); // } // } // // public static void updateAllAppWidgets(Context context) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, null); // } // } // // public static void updateAllAppWidgetsForHost(Context context, long hostId) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Long hostId) // { // // workaround for phantom widgets // boolean configured = ConfigureWidgetActivity.getConfiguredPreference(context, appWidgetId); // if (!configured) return; // // Long widgetHostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // if (hostId != null && !hostId.equals(widgetHostId)) return; // // DatabaseManager hostDataManager = new DatabaseManager(context); // RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); // // // boolean hostExists = hostDataManager.hostExists(widgetHostId); // if (hostExists) // { // Host host = hostDataManager.getHost(widgetHostId); // // Intent intent = new Intent(context, HostListActivity.class); // intent.putExtra("hostId", widgetHostId); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // // views.setTextViewText(R.id.widget_host_label, host.getLabel()); // views.setTextViewText(R.id.widget_host_hostname, host.getHostname()); // views.setTextViewText(R.id.widget_host_ports, host.getPortsString()); // // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); // if (sharedPreferences.getBoolean(context.getString(R.string.pref_key_hide_ports_widget), false)) // { // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // } // else // { // views.setViewVisibility(R.id.widget_host_ports, View.VISIBLE); // } // } // else // { // views.setTextViewText(R.id.widget_host_label, "Invalid Host"); // views.setViewVisibility(R.id.widget_host_hostname, View.GONE); // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // // Intent intent = new Intent(context, HostListActivity.class); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // } // // appWidgetManager.updateAppWidget(appWidgetId, views); // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/fragment/SettingsFragment.java import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceFragment; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.widget.HostWidget; /* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.fragment; public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (isAdded() && getString(R.string.pref_key_hide_ports_widget).equals(key)) {
HostWidget.updateAllAppWidgets(getActivity());
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/utils/SerializationUtils.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // }
import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.os.Environment; import android.support.annotation.NonNull; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.xargsgrep.portknocker.model.Host; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.util.List;
package com.xargsgrep.portknocker.utils; public class SerializationUtils {
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/utils/SerializationUtils.java import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.os.Environment; import android.support.annotation.NonNull; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.xargsgrep.portknocker.model.Host; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.util.List; package com.xargsgrep.portknocker.utils; public class SerializationUtils {
public static String serializeHosts(String fileName, List<Host> hosts) throws Exception
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/db/DatabaseHelper.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; import com.xargsgrep.portknocker.model.Host;
PORT_INDEX_COLUMN, PORT_PORT_COLUMN, PORT_PROTOCOL_COLUMN }; public DatabaseHelper(Context context) { super(context, DATABASE_FILENAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createHostTableSQL = "create table %s (" + " %s integer primary key autoincrement," + " %s string not null," + " %s string not null," + " %s integer not null default %d," + " %s string," + " %s string," + " %s integer," + " %s integer not null default %d" + ");"; createHostTableSQL = String.format( createHostTableSQL, HOST_TABLE_NAME, HOST_ID_COLUMN, HOST_LABEL_COLUMN, HOST_HOSTNAME_COLUMN,
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Host.java // public class Host // { // public static final int DEFAULT_DELAY = 1000; // public static final int DEFAULT_TCP_CONNECT_TIMEOUT = 100; // // private long id; // private String label; // private String hostname; // private int delay = DEFAULT_DELAY; // private int tcpConnectTimeout = DEFAULT_TCP_CONNECT_TIMEOUT; // private String launchIntentPackage; // private List<Port> ports = new ArrayList<>(); // // @JsonIgnore // public long getId() // { // return id; // } // // public void setId(long id) // { // this.id = id; // } // // public String getLabel() // { // return label; // } // // public void setLabel(String label) // { // this.label = label; // } // // public String getHostname() // { // return hostname; // } // // public void setHostname(String hostname) // { // this.hostname = hostname; // } // // public int getDelay() // { // return delay; // } // // public void setDelay(int delay) // { // this.delay = delay; // } // // public String getLaunchIntentPackage() // { // return launchIntentPackage; // } // // public int getTcpConnectTimeout() // { // return tcpConnectTimeout; // } // // public void setTcpConnectTimeout(int tcpConnectTimeout) // { // this.tcpConnectTimeout = tcpConnectTimeout; // } // // public void setLaunchIntentPackage(String launchIntentPackage) // { // this.launchIntentPackage = launchIntentPackage; // } // // public List<Port> getPorts() // { // return ports; // } // // public void setPorts(List<Port> ports) // { // this.ports = ports; // } // // @JsonIgnore // public String getPortsString() // { // StringBuilder portsString = new StringBuilder(); // // if (ports.size() > 0) // { // for (Port port : ports) // { // portsString.append(port.getPort()); // portsString.append(":"); // portsString.append(port.getProtocol()); // portsString.append(", "); // } // portsString.replace(portsString.length() - 2, portsString.length(), ""); // } // // return portsString.toString(); // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/db/DatabaseHelper.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; import com.xargsgrep.portknocker.model.Host; PORT_INDEX_COLUMN, PORT_PORT_COLUMN, PORT_PROTOCOL_COLUMN }; public DatabaseHelper(Context context) { super(context, DATABASE_FILENAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createHostTableSQL = "create table %s (" + " %s integer primary key autoincrement," + " %s string not null," + " %s string not null," + " %s integer not null default %d," + " %s string," + " %s string," + " %s integer," + " %s integer not null default %d" + ");"; createHostTableSQL = String.format( createHostTableSQL, HOST_TABLE_NAME, HOST_ID_COLUMN, HOST_LABEL_COLUMN, HOST_HOSTNAME_COLUMN,
HOST_DELAY_COLUMN, Host.DEFAULT_DELAY,
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/activity/SettingsActivityCompat.java
// Path: app/src/main/java/com/xargsgrep/portknocker/widget/HostWidget.java // public class HostWidget extends AppWidgetProvider // { // @Override // public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) // { // for (int appWidgetId : appWidgetIds) // { // long hostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // @Override // public void onDeleted(Context context, int[] appWidgetIds) // { // for (int i = 0; i < appWidgetIds.length; i++) // { // ConfigureWidgetActivity.deleteHostIdPreference(context, appWidgetIds[i]); // } // } // // public static void updateAllAppWidgets(Context context) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, null); // } // } // // public static void updateAllAppWidgetsForHost(Context context, long hostId) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Long hostId) // { // // workaround for phantom widgets // boolean configured = ConfigureWidgetActivity.getConfiguredPreference(context, appWidgetId); // if (!configured) return; // // Long widgetHostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // if (hostId != null && !hostId.equals(widgetHostId)) return; // // DatabaseManager hostDataManager = new DatabaseManager(context); // RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); // // // boolean hostExists = hostDataManager.hostExists(widgetHostId); // if (hostExists) // { // Host host = hostDataManager.getHost(widgetHostId); // // Intent intent = new Intent(context, HostListActivity.class); // intent.putExtra("hostId", widgetHostId); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // // views.setTextViewText(R.id.widget_host_label, host.getLabel()); // views.setTextViewText(R.id.widget_host_hostname, host.getHostname()); // views.setTextViewText(R.id.widget_host_ports, host.getPortsString()); // // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); // if (sharedPreferences.getBoolean(context.getString(R.string.pref_key_hide_ports_widget), false)) // { // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // } // else // { // views.setViewVisibility(R.id.widget_host_ports, View.VISIBLE); // } // } // else // { // views.setTextViewText(R.id.widget_host_label, "Invalid Host"); // views.setViewVisibility(R.id.widget_host_hostname, View.GONE); // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // // Intent intent = new Intent(context, HostListActivity.class); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // } // // appWidgetManager.updateAppWidget(appWidgetId, views); // } // }
import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.MenuItem; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.widget.HostWidget;
/* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.activity; public class SettingsActivityCompat extends PreferenceActivity implements OnSharedPreferenceChangeListener { @Override @SuppressWarnings("deprecation") public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent hostListIntent = new Intent(this, HostListActivity.class); hostListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(hostListIntent); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (getString(R.string.pref_key_hide_ports_widget).equals(key)) {
// Path: app/src/main/java/com/xargsgrep/portknocker/widget/HostWidget.java // public class HostWidget extends AppWidgetProvider // { // @Override // public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) // { // for (int appWidgetId : appWidgetIds) // { // long hostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // @Override // public void onDeleted(Context context, int[] appWidgetIds) // { // for (int i = 0; i < appWidgetIds.length; i++) // { // ConfigureWidgetActivity.deleteHostIdPreference(context, appWidgetIds[i]); // } // } // // public static void updateAllAppWidgets(Context context) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, null); // } // } // // public static void updateAllAppWidgetsForHost(Context context, long hostId) // { // AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); // int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, HostWidget.class)); // for (int appWidgetId : appWidgetIds) // { // updateAppWidget(context, appWidgetManager, appWidgetId, hostId); // } // } // // public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Long hostId) // { // // workaround for phantom widgets // boolean configured = ConfigureWidgetActivity.getConfiguredPreference(context, appWidgetId); // if (!configured) return; // // Long widgetHostId = ConfigureWidgetActivity.getHostIdPreference(context, appWidgetId); // if (hostId != null && !hostId.equals(widgetHostId)) return; // // DatabaseManager hostDataManager = new DatabaseManager(context); // RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); // // // boolean hostExists = hostDataManager.hostExists(widgetHostId); // if (hostExists) // { // Host host = hostDataManager.getHost(widgetHostId); // // Intent intent = new Intent(context, HostListActivity.class); // intent.putExtra("hostId", widgetHostId); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // // views.setTextViewText(R.id.widget_host_label, host.getLabel()); // views.setTextViewText(R.id.widget_host_hostname, host.getHostname()); // views.setTextViewText(R.id.widget_host_ports, host.getPortsString()); // // SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); // if (sharedPreferences.getBoolean(context.getString(R.string.pref_key_hide_ports_widget), false)) // { // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // } // else // { // views.setViewVisibility(R.id.widget_host_ports, View.VISIBLE); // } // } // else // { // views.setTextViewText(R.id.widget_host_label, "Invalid Host"); // views.setViewVisibility(R.id.widget_host_hostname, View.GONE); // views.setViewVisibility(R.id.widget_host_ports, View.GONE); // // Intent intent = new Intent(context, HostListActivity.class); // PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); // views.setOnClickPendingIntent(R.id.widget, pendingIntent); // } // // appWidgetManager.updateAppWidget(appWidgetId, views); // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/activity/SettingsActivityCompat.java import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.MenuItem; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.widget.HostWidget; /* * Copyright 2014 Ahsan Rabbani * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xargsgrep.portknocker.activity; public class SettingsActivityCompat extends PreferenceActivity implements OnSharedPreferenceChangeListener { @Override @SuppressWarnings("deprecation") public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent hostListIntent = new Intent(this, HostListActivity.class); hostListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(hostListIntent); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (getString(R.string.pref_key_hide_ports_widget).equals(key)) {
HostWidget.updateAllAppWidgets(this);
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/adapter/PortArrayAdapter.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // // Path: app/src/main/java/com/xargsgrep/portknocker/utils/StringUtils.java // public class StringUtils // { // public static boolean contains(String stringToCheck, String str) // { // return (stringToCheck == null) ? false : stringToCheck.contains(str); // } // // // String.isEmpty only available starting API 9 // public static boolean isEmpty(String str) // { // return (str == null || str.length() == 0); // } // // public static boolean isBlank(String str) // { // return (str == null || isEmpty(str.trim())); // } // // public static boolean isNotBlank(String str) // { // return !isBlank(str); // } // }
import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import com.xargsgrep.portknocker.utils.StringUtils; import java.util.List;
this.ports = ports; } @Override public int getCount() { return ports.size(); } @Override public Port getItem(int position) { return ports.get(position); } public List<Port> getPorts() { return ports; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) view = LayoutInflater.from(getContext()).inflate(R.layout.port_row, null); EditText portView = (EditText) view.findViewById(R.id.port_row_port); Spinner protocolSpinner = (Spinner) view.findViewById(R.id.port_row_protocol); ImageButton deleteButton = (ImageButton) view.findViewById(R.id.port_row_delete);
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // // Path: app/src/main/java/com/xargsgrep/portknocker/utils/StringUtils.java // public class StringUtils // { // public static boolean contains(String stringToCheck, String str) // { // return (stringToCheck == null) ? false : stringToCheck.contains(str); // } // // // String.isEmpty only available starting API 9 // public static boolean isEmpty(String str) // { // return (str == null || str.length() == 0); // } // // public static boolean isBlank(String str) // { // return (str == null || isEmpty(str.trim())); // } // // public static boolean isNotBlank(String str) // { // return !isBlank(str); // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/adapter/PortArrayAdapter.java import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import com.xargsgrep.portknocker.utils.StringUtils; import java.util.List; this.ports = ports; } @Override public int getCount() { return ports.size(); } @Override public Port getItem(int position) { return ports.get(position); } public List<Port> getPorts() { return ports; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) view = LayoutInflater.from(getContext()).inflate(R.layout.port_row, null); EditText portView = (EditText) view.findViewById(R.id.port_row_port); Spinner protocolSpinner = (Spinner) view.findViewById(R.id.port_row_protocol); ImageButton deleteButton = (ImageButton) view.findViewById(R.id.port_row_delete);
ArrayAdapter<Protocol> protocolAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, Protocol.values());
xargsgrep/PortKnocker
app/src/main/java/com/xargsgrep/portknocker/adapter/PortArrayAdapter.java
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // // Path: app/src/main/java/com/xargsgrep/portknocker/utils/StringUtils.java // public class StringUtils // { // public static boolean contains(String stringToCheck, String str) // { // return (stringToCheck == null) ? false : stringToCheck.contains(str); // } // // // String.isEmpty only available starting API 9 // public static boolean isEmpty(String str) // { // return (str == null || str.length() == 0); // } // // public static boolean isBlank(String str) // { // return (str == null || isEmpty(str.trim())); // } // // public static boolean isNotBlank(String str) // { // return !isBlank(str); // } // }
import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import com.xargsgrep.portknocker.utils.StringUtils; import java.util.List;
@Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) view = LayoutInflater.from(getContext()).inflate(R.layout.port_row, null); EditText portView = (EditText) view.findViewById(R.id.port_row_port); Spinner protocolSpinner = (Spinner) view.findViewById(R.id.port_row_protocol); ImageButton deleteButton = (ImageButton) view.findViewById(R.id.port_row_delete); ArrayAdapter<Protocol> protocolAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, Protocol.values()); protocolAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); protocolSpinner.setAdapter(protocolAdapter); Port port = ports.get(position); portView.setText((port.getPort() > -1) ? Integer.valueOf(port.getPort()).toString() : ""); protocolSpinner.setSelection(port.getProtocol().ordinal()); final int fPosition = position; portView.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if (!hasFocus) { String portStr = ((EditText) view).getText().toString(); // if fPosition is out of bounds, it means the last row was focused and a row before it was deleted ports.get((fPosition >= getCount()) ? fPosition - 1
// Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public class Port // { // private long hostId; // private int index; // private int port = -1; // private Protocol protocol = Protocol.TCP; // // public static enum Protocol {TCP, UDP} // // public Port() { } // // @JsonIgnore // public long getHostId() // { // return hostId; // } // // public void setHostId(long hostId) // { // this.hostId = hostId; // } // // @JsonIgnore // public int getIndex() // { // return index; // } // // public void setIndex(int index) // { // this.index = index; // } // // public int getPort() // { // return port; // } // // public void setPort(int port) // { // this.port = port; // } // // public Protocol getProtocol() // { // return protocol; // } // // public void setProtocol(Protocol protocol) // { // this.protocol = protocol; // } // } // // Path: app/src/main/java/com/xargsgrep/portknocker/model/Port.java // public static enum Protocol {TCP, UDP} // // Path: app/src/main/java/com/xargsgrep/portknocker/utils/StringUtils.java // public class StringUtils // { // public static boolean contains(String stringToCheck, String str) // { // return (stringToCheck == null) ? false : stringToCheck.contains(str); // } // // // String.isEmpty only available starting API 9 // public static boolean isEmpty(String str) // { // return (str == null || str.length() == 0); // } // // public static boolean isBlank(String str) // { // return (str == null || isEmpty(str.trim())); // } // // public static boolean isNotBlank(String str) // { // return !isBlank(str); // } // } // Path: app/src/main/java/com/xargsgrep/portknocker/adapter/PortArrayAdapter.java import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.xargsgrep.portknocker.R; import com.xargsgrep.portknocker.model.Port; import com.xargsgrep.portknocker.model.Port.Protocol; import com.xargsgrep.portknocker.utils.StringUtils; import java.util.List; @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) view = LayoutInflater.from(getContext()).inflate(R.layout.port_row, null); EditText portView = (EditText) view.findViewById(R.id.port_row_port); Spinner protocolSpinner = (Spinner) view.findViewById(R.id.port_row_protocol); ImageButton deleteButton = (ImageButton) view.findViewById(R.id.port_row_delete); ArrayAdapter<Protocol> protocolAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, Protocol.values()); protocolAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); protocolSpinner.setAdapter(protocolAdapter); Port port = ports.get(position); portView.setText((port.getPort() > -1) ? Integer.valueOf(port.getPort()).toString() : ""); protocolSpinner.setSelection(port.getProtocol().ordinal()); final int fPosition = position; portView.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if (!hasFocus) { String portStr = ((EditText) view).getText().toString(); // if fPosition is out of bounds, it means the last row was focused and a row before it was deleted ports.get((fPosition >= getCount()) ? fPosition - 1
: fPosition).setPort((StringUtils.isNotBlank(portStr)) ? Integer.parseInt(portStr) : -1);
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/manifest/Manifest.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // }
import java.net.URL; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import org.apache.hms.common.entity.RestSource; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.manifest; @XmlSeeAlso({ ClusterManifest.class, ConfigManifest.class, NodesManifest.class, SoftwareManifest.class }) @XmlTransient @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@manifest")
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // Path: common/src/main/java/org/apache/hms/common/entity/manifest/Manifest.java import java.net.URL; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import org.apache.hms.common.entity.RestSource; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.manifest; @XmlSeeAlso({ ClusterManifest.class, ConfigManifest.class, NodesManifest.class, SoftwareManifest.class }) @XmlTransient @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@manifest")
public abstract class Manifest extends RestSource {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/DeleteClusterCommand.java
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java // @XmlRootElement // public class ClusterManifest extends Manifest { // @XmlAttribute // private String clusterName; // @XmlElement // private NodesManifest nodes; // @XmlElement // private SoftwareManifest software; // @XmlElement // private ConfigManifest config; // // public String getClusterName() { // return this.clusterName; // } // // public NodesManifest getNodes() { // return this.nodes; // } // // public SoftwareManifest getSoftware() { // return this.software; // } // // public ConfigManifest getConfig() { // return this.config; // } // // public void setClusterName(String cluster) { // this.clusterName = cluster; // } // // public void setNodes(NodesManifest nodes) { // this.nodes = nodes; // } // // public void setSoftware(SoftwareManifest software) { // this.software = software; // } // // public void setConfig(ConfigManifest config) { // this.config = config; // } // // public void load() throws IOException { // if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { // URL url = nodes.getUrl(); // nodes = fetch(url, NodesManifest.class); // nodes.setUrl(url); // } // if(software!=null && software.getUrl()!=null && software.getRoles()==null) { // URL url = software.getUrl(); // software = fetch(url, SoftwareManifest.class); // software.setUrl(url); // } // if(config!=null && config.getUrl()!=null && config.getActions()==null) { // URL url = config.getUrl(); // config = fetch(url, ConfigManifest.class); // config.setUrl(url); // config.expand(nodes); // } // } // // private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { // if(url.getProtocol().toLowerCase().equals("file")) { // FileReader fstream = new FileReader(url.getPath()); // BufferedReader in = new BufferedReader(fstream); // StringBuilder buffer = new StringBuilder(); // String str; // while((str = in.readLine()) != null) { // buffer.append(str); // } // return JAXBUtil.read(buffer.toString().getBytes(), c); // } else { // com.sun.jersey.api.client.Client wsClient = com.sun.jersey.api.client.Client.create(); // WebResource webResource = wsClient.resource(url.toString()); // return webResource.get(c); // } // } // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.manifest.ClusterManifest; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlType(name="", propOrder = {}) public class DeleteClusterCommand extends ClusterCommand { public DeleteClusterCommand() { this.cmd = CmdType.DELETE; }
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java // @XmlRootElement // public class ClusterManifest extends Manifest { // @XmlAttribute // private String clusterName; // @XmlElement // private NodesManifest nodes; // @XmlElement // private SoftwareManifest software; // @XmlElement // private ConfigManifest config; // // public String getClusterName() { // return this.clusterName; // } // // public NodesManifest getNodes() { // return this.nodes; // } // // public SoftwareManifest getSoftware() { // return this.software; // } // // public ConfigManifest getConfig() { // return this.config; // } // // public void setClusterName(String cluster) { // this.clusterName = cluster; // } // // public void setNodes(NodesManifest nodes) { // this.nodes = nodes; // } // // public void setSoftware(SoftwareManifest software) { // this.software = software; // } // // public void setConfig(ConfigManifest config) { // this.config = config; // } // // public void load() throws IOException { // if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { // URL url = nodes.getUrl(); // nodes = fetch(url, NodesManifest.class); // nodes.setUrl(url); // } // if(software!=null && software.getUrl()!=null && software.getRoles()==null) { // URL url = software.getUrl(); // software = fetch(url, SoftwareManifest.class); // software.setUrl(url); // } // if(config!=null && config.getUrl()!=null && config.getActions()==null) { // URL url = config.getUrl(); // config = fetch(url, ConfigManifest.class); // config.setUrl(url); // config.expand(nodes); // } // } // // private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { // if(url.getProtocol().toLowerCase().equals("file")) { // FileReader fstream = new FileReader(url.getPath()); // BufferedReader in = new BufferedReader(fstream); // StringBuilder buffer = new StringBuilder(); // String str; // while((str = in.readLine()) != null) { // buffer.append(str); // } // return JAXBUtil.read(buffer.toString().getBytes(), c); // } else { // com.sun.jersey.api.client.Client wsClient = com.sun.jersey.api.client.Client.create(); // WebResource webResource = wsClient.resource(url.toString()); // return webResource.get(c); // } // } // } // Path: common/src/main/java/org/apache/hms/common/entity/command/DeleteClusterCommand.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.manifest.ClusterManifest; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlType(name="", propOrder = {}) public class DeleteClusterCommand extends ClusterCommand { public DeleteClusterCommand() { this.cmd = CmdType.DELETE; }
public DeleteClusterCommand(String clusterName, ClusterManifest cm) {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/action/PackageAction.java
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/PackageInfo.java // public class PackageInfo extends RestSource { // @XmlElement // private String name; // @XmlElement // private String[] relocate; // // public String getName() { // return name; // } // // public String[] getRelocate() { // return relocate; // } // // public void setName(String name) { // this.name = name; // } // // public void setRelocate(String[] relocate) { // this.relocate = relocate; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("package: "); // sb.append(name); // return sb.toString(); // } // // @Override // public boolean equals(Object obj) { // if(obj == null) { // return false; // } // return name.equals(((PackageInfo) obj).getName()); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // }
import org.apache.hms.common.entity.manifest.PackageInfo; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * Action describes what package to install or remove from a node. * */ @XmlRootElement @XmlType(propOrder = { "packages", "dryRun" }) public class PackageAction extends Action { @XmlElement
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/PackageInfo.java // public class PackageInfo extends RestSource { // @XmlElement // private String name; // @XmlElement // private String[] relocate; // // public String getName() { // return name; // } // // public String[] getRelocate() { // return relocate; // } // // public void setName(String name) { // this.name = name; // } // // public void setRelocate(String[] relocate) { // this.relocate = relocate; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("package: "); // sb.append(name); // return sb.toString(); // } // // @Override // public boolean equals(Object obj) { // if(obj == null) { // return false; // } // return name.equals(((PackageInfo) obj).getName()); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/action/PackageAction.java import org.apache.hms.common.entity.manifest.PackageInfo; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * Action describes what package to install or remove from a node. * */ @XmlRootElement @XmlType(propOrder = { "packages", "dryRun" }) public class PackageAction extends Action { @XmlElement
private PackageInfo[] packages;
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // }
import org.apache.hms.common.entity.Status.StatusAdapter; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.cluster; /** * MachineState defines a list of state entries of a node. * For example, a node can have HADOOP-0.20.206 installed, and * namenode is started. Both states are stored in the MachineState. * */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {})
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java import org.apache.hms.common.entity.Status.StatusAdapter; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.cluster; /** * MachineState defines a list of state entries of a node. * For example, a node can have HADOOP-0.20.206 installed, and * namenode is started. Both states are stored in the MachineState. * */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {})
public class MachineState extends RestSource {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // }
import org.apache.hms.common.entity.Status.StatusAdapter; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status;
if (stateEntries != null) { for (StateEntry a : stateEntries) { sb.append(a); sb.append(" "); } } return sb.toString(); } /** * A state entry compose of: * * Type of state to record, valid type are: PACKAGE, DAEMON * A unique name field to identify the package or daemon * Status is the state that a node must maintain. * @author eyang * */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public static class StateEntry { private static final int PRIME = 16777619; @XmlElement @XmlJavaTypeAdapter(StateTypeAdapter.class) protected StateType type; @XmlElement protected String name; @XmlElement @XmlJavaTypeAdapter(StatusAdapter.class)
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java import org.apache.hms.common.entity.Status.StatusAdapter; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; if (stateEntries != null) { for (StateEntry a : stateEntries) { sb.append(a); sb.append(" "); } } return sb.toString(); } /** * A state entry compose of: * * Type of state to record, valid type are: PACKAGE, DAEMON * A unique name field to identify the package or daemon * Status is the state that a node must maintain. * @author eyang * */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public static class StateEntry { private static final int PRIME = 16777619; @XmlElement @XmlJavaTypeAdapter(StateTypeAdapter.class) protected StateType type; @XmlElement protected String name; @XmlElement @XmlJavaTypeAdapter(StatusAdapter.class)
protected Status status;
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/UpgradeClusterCommand.java
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java // @XmlRootElement // public class ClusterManifest extends Manifest { // @XmlAttribute // private String clusterName; // @XmlElement // private NodesManifest nodes; // @XmlElement // private SoftwareManifest software; // @XmlElement // private ConfigManifest config; // // public String getClusterName() { // return this.clusterName; // } // // public NodesManifest getNodes() { // return this.nodes; // } // // public SoftwareManifest getSoftware() { // return this.software; // } // // public ConfigManifest getConfig() { // return this.config; // } // // public void setClusterName(String cluster) { // this.clusterName = cluster; // } // // public void setNodes(NodesManifest nodes) { // this.nodes = nodes; // } // // public void setSoftware(SoftwareManifest software) { // this.software = software; // } // // public void setConfig(ConfigManifest config) { // this.config = config; // } // // public void load() throws IOException { // if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { // URL url = nodes.getUrl(); // nodes = fetch(url, NodesManifest.class); // nodes.setUrl(url); // } // if(software!=null && software.getUrl()!=null && software.getRoles()==null) { // URL url = software.getUrl(); // software = fetch(url, SoftwareManifest.class); // software.setUrl(url); // } // if(config!=null && config.getUrl()!=null && config.getActions()==null) { // URL url = config.getUrl(); // config = fetch(url, ConfigManifest.class); // config.setUrl(url); // config.expand(nodes); // } // } // // private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { // if(url.getProtocol().toLowerCase().equals("file")) { // FileReader fstream = new FileReader(url.getPath()); // BufferedReader in = new BufferedReader(fstream); // StringBuilder buffer = new StringBuilder(); // String str; // while((str = in.readLine()) != null) { // buffer.append(str); // } // return JAXBUtil.read(buffer.toString().getBytes(), c); // } else { // com.sun.jersey.api.client.Client wsClient = com.sun.jersey.api.client.Client.create(); // WebResource webResource = wsClient.resource(url.toString()); // return webResource.get(c); // } // } // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.manifest.ClusterManifest; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlType(name="", propOrder = {}) public class UpgradeClusterCommand extends ClusterCommand { public UpgradeClusterCommand() { this.cmd = CmdType.UPGRADE; }
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java // @XmlRootElement // public class ClusterManifest extends Manifest { // @XmlAttribute // private String clusterName; // @XmlElement // private NodesManifest nodes; // @XmlElement // private SoftwareManifest software; // @XmlElement // private ConfigManifest config; // // public String getClusterName() { // return this.clusterName; // } // // public NodesManifest getNodes() { // return this.nodes; // } // // public SoftwareManifest getSoftware() { // return this.software; // } // // public ConfigManifest getConfig() { // return this.config; // } // // public void setClusterName(String cluster) { // this.clusterName = cluster; // } // // public void setNodes(NodesManifest nodes) { // this.nodes = nodes; // } // // public void setSoftware(SoftwareManifest software) { // this.software = software; // } // // public void setConfig(ConfigManifest config) { // this.config = config; // } // // public void load() throws IOException { // if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { // URL url = nodes.getUrl(); // nodes = fetch(url, NodesManifest.class); // nodes.setUrl(url); // } // if(software!=null && software.getUrl()!=null && software.getRoles()==null) { // URL url = software.getUrl(); // software = fetch(url, SoftwareManifest.class); // software.setUrl(url); // } // if(config!=null && config.getUrl()!=null && config.getActions()==null) { // URL url = config.getUrl(); // config = fetch(url, ConfigManifest.class); // config.setUrl(url); // config.expand(nodes); // } // } // // private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { // if(url.getProtocol().toLowerCase().equals("file")) { // FileReader fstream = new FileReader(url.getPath()); // BufferedReader in = new BufferedReader(fstream); // StringBuilder buffer = new StringBuilder(); // String str; // while((str = in.readLine()) != null) { // buffer.append(str); // } // return JAXBUtil.read(buffer.toString().getBytes(), c); // } else { // com.sun.jersey.api.client.Client wsClient = com.sun.jersey.api.client.Client.create(); // WebResource webResource = wsClient.resource(url.toString()); // return webResource.get(c); // } // } // } // Path: common/src/main/java/org/apache/hms/common/entity/command/UpgradeClusterCommand.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.manifest.ClusterManifest; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlType(name="", propOrder = {}) public class UpgradeClusterCommand extends ClusterCommand { public UpgradeClusterCommand() { this.cmd = CmdType.UPGRADE; }
public UpgradeClusterCommand(String clusterName, ClusterManifest cm) {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/manifest/ConfigManifest.java
// Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/ScriptAction.java // @XmlRootElement // @XmlType(propOrder = { "script", "parameters" }) // public class ScriptAction extends Action { // @XmlElement // private String script; // @XmlElement(name="parameters") // private String[] parameters; // // public String getScript() { // return script; // } // // public String[] getParameters() { // return parameters; // } // // public void setScript(String script) { // this.script =script; // } // // public void setParameters(String[] parameters) { // this.parameters = parameters; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(super.toString()); // sb.append(", script="); // sb.append(script); // sb.append(", parameters="); // if (parameters != null) { // for (String p : parameters) { // sb.append(p); // sb.append(" "); // } // } // if (role != null) { // sb.append(", role="); // sb.append(role); // } // return sb.toString(); // } // }
import org.apache.commons.logging.LogFactory; import org.apache.hms.common.entity.action.Action; import org.apache.hms.common.entity.action.ScriptAction; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.manifest; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {}) @XmlRootElement public class ConfigManifest extends Manifest { private static Log LOG = LogFactory.getLog(ConfigManifest.class); @XmlElement
// Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/ScriptAction.java // @XmlRootElement // @XmlType(propOrder = { "script", "parameters" }) // public class ScriptAction extends Action { // @XmlElement // private String script; // @XmlElement(name="parameters") // private String[] parameters; // // public String getScript() { // return script; // } // // public String[] getParameters() { // return parameters; // } // // public void setScript(String script) { // this.script =script; // } // // public void setParameters(String[] parameters) { // this.parameters = parameters; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(super.toString()); // sb.append(", script="); // sb.append(script); // sb.append(", parameters="); // if (parameters != null) { // for (String p : parameters) { // sb.append(p); // sb.append(" "); // } // } // if (role != null) { // sb.append(", role="); // sb.append(role); // } // return sb.toString(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/manifest/ConfigManifest.java import org.apache.commons.logging.LogFactory; import org.apache.hms.common.entity.action.Action; import org.apache.hms.common.entity.action.ScriptAction; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.manifest; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {}) @XmlRootElement public class ConfigManifest extends Manifest { private static Log LOG = LogFactory.getLog(ConfigManifest.class); @XmlElement
private List<Action> actions;
macroadster/HMS
agent/src/main/java/org/apache/hms/agent/dispatcher/PackageRunner.java
// Path: agent/src/main/java/org/apache/hms/agent/Agent.java // public class Agent { // private static Log log = LogFactory.getLog(Agent.class); // // private static Agent instance = null; // private Server server = null; // private static URL serverConf = null; // // public static Agent getInstance() { // if(instance==null) { // instance = new Agent(); // } // return instance; // } // // public void start() { // try { // System.out.close(); // System.err.close(); // instance = this; // run(); // } catch(Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // System.exit(-1); // } // } // // public void run() { // server = new Server(4080); // // XmlConfiguration configuration; // try { // Context root = new Context(server, "/", Context.SESSIONS); // ServletHolder sh = new ServletHolder(ServletContainer.class); // sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); // sh.setInitParameter("com.sun.jersey.config.property.packages", "org.apache.hms.agent.rest"); // root.addServlet(sh, "/*"); // server.setStopAtShutdown(true); // server.start(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public void stop() throws Exception { // try { // server.stop(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public static void main(String[] args) { // Agent agent = Agent.getInstance(); // agent.start(); // } // // } // // Path: common/src/main/java/org/apache/hms/common/util/FileUtil.java // public class FileUtil { // public static boolean deleteDir(File dir) { // if (dir.isDirectory()) { // String[] children = dir.list(); // for (int i=0; i<children.length; i++) { // boolean success = deleteDir(new File(dir, children[i])); // if (!success) { // return false; // } // } // } // return dir.delete(); // } // }
import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hms.agent.Agent; import org.apache.hms.common.entity.PackageCommand; import org.apache.hms.common.entity.PackageInfo; import org.apache.hms.common.entity.ScriptCommand; import org.apache.hms.common.entity.agent.DaemonAction; import org.apache.hms.common.rest.Response; import org.apache.hms.common.util.FileUtil;
return r; } private Response dryRun(PackageCommand dc) { Response r = null; ScriptCommand cmd = new ScriptCommand(); cmd.setCmd(dc.getCmd()); cmd.setScript("yum"); PackageInfo[] packages = dc.getPackages(); String[] parms = new String[packages.length+4]; parms[0] = "install"; parms[1] = "-y"; parms[2] = "--downloadonly"; parms[3] = "--downloaddir=/tmp/system_update"; for(int i=0;i<packages.length;i++) { parms[i+4] = packages[i].getName(); } cmd.setParms(parms); ShellRunner shell = new ShellRunner(); r = shell.run(cmd); if(r.getCode()!=1) { return r; } else { cmd.setScript("rpm"); String[] rpmParms = new String[3]; rpmParms[0] = "-i"; rpmParms[1] = "--test"; rpmParms[2] = "/tmp/system_update/*.rpm"; cmd.setParms(rpmParms); r = shell.run(cmd);
// Path: agent/src/main/java/org/apache/hms/agent/Agent.java // public class Agent { // private static Log log = LogFactory.getLog(Agent.class); // // private static Agent instance = null; // private Server server = null; // private static URL serverConf = null; // // public static Agent getInstance() { // if(instance==null) { // instance = new Agent(); // } // return instance; // } // // public void start() { // try { // System.out.close(); // System.err.close(); // instance = this; // run(); // } catch(Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // System.exit(-1); // } // } // // public void run() { // server = new Server(4080); // // XmlConfiguration configuration; // try { // Context root = new Context(server, "/", Context.SESSIONS); // ServletHolder sh = new ServletHolder(ServletContainer.class); // sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); // sh.setInitParameter("com.sun.jersey.config.property.packages", "org.apache.hms.agent.rest"); // root.addServlet(sh, "/*"); // server.setStopAtShutdown(true); // server.start(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public void stop() throws Exception { // try { // server.stop(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public static void main(String[] args) { // Agent agent = Agent.getInstance(); // agent.start(); // } // // } // // Path: common/src/main/java/org/apache/hms/common/util/FileUtil.java // public class FileUtil { // public static boolean deleteDir(File dir) { // if (dir.isDirectory()) { // String[] children = dir.list(); // for (int i=0; i<children.length; i++) { // boolean success = deleteDir(new File(dir, children[i])); // if (!success) { // return false; // } // } // } // return dir.delete(); // } // } // Path: agent/src/main/java/org/apache/hms/agent/dispatcher/PackageRunner.java import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hms.agent.Agent; import org.apache.hms.common.entity.PackageCommand; import org.apache.hms.common.entity.PackageInfo; import org.apache.hms.common.entity.ScriptCommand; import org.apache.hms.common.entity.agent.DaemonAction; import org.apache.hms.common.rest.Response; import org.apache.hms.common.util.FileUtil; return r; } private Response dryRun(PackageCommand dc) { Response r = null; ScriptCommand cmd = new ScriptCommand(); cmd.setCmd(dc.getCmd()); cmd.setScript("yum"); PackageInfo[] packages = dc.getPackages(); String[] parms = new String[packages.length+4]; parms[0] = "install"; parms[1] = "-y"; parms[2] = "--downloadonly"; parms[3] = "--downloaddir=/tmp/system_update"; for(int i=0;i<packages.length;i++) { parms[i+4] = packages[i].getName(); } cmd.setParms(parms); ShellRunner shell = new ShellRunner(); r = shell.run(cmd); if(r.getCode()!=1) { return r; } else { cmd.setScript("rpm"); String[] rpmParms = new String[3]; rpmParms[0] = "-i"; rpmParms[1] = "--test"; rpmParms[2] = "/tmp/system_update/*.rpm"; cmd.setParms(rpmParms); r = shell.run(cmd);
FileUtil.deleteDir(new File("/tmp/system_update"));
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/CommandStatus.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // }
import org.apache.hms.common.entity.action.Action; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; import org.apache.hms.common.entity.Status.StatusAdapter;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {})
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/command/CommandStatus.java import org.apache.hms.common.entity.action.Action; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; import org.apache.hms.common.entity.Status.StatusAdapter; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {})
public class CommandStatus extends RestSource {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/CommandStatus.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // }
import org.apache.hms.common.entity.action.Action; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; import org.apache.hms.common.entity.Status.StatusAdapter;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {}) public class CommandStatus extends RestSource { @XmlElement @XmlJavaTypeAdapter(StatusAdapter.class)
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/command/CommandStatus.java import org.apache.hms.common.entity.action.Action; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; import org.apache.hms.common.entity.Status.StatusAdapter; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {}) public class CommandStatus extends RestSource { @XmlElement @XmlJavaTypeAdapter(StatusAdapter.class)
protected Status status;
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/CommandStatus.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // }
import org.apache.hms.common.entity.action.Action; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; import org.apache.hms.common.entity.Status.StatusAdapter;
} public String toString() { StringBuilder sb = new StringBuilder(); sb.append("cmdStatus="); sb.append(status); sb.append(", startTime="); sb.append(startTime); sb.append(", endTime="); sb.append(endTime); sb.append(", clusterName="); sb.append(clusterName); sb.append(", totalActions="); sb.append(totalActions); sb.append(", completedActions="); sb.append(completedActions); sb.append(", actions="); if (actionEntries != null) { for(ActionEntry a : actionEntries) { sb.append("\n"); sb.append(a); } } return sb.toString(); } @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement @XmlType(name="", propOrder = {}) public static class ActionEntry {
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/Status.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = {}) // public enum Status { // UNQUEUED, QUEUED, STARTED, SUCCEEDED, FAILED, INSTALLED, STOPPED; // // public static class StatusAdapter extends XmlAdapter<String, Status> { // // @Override // public String marshal(Status obj) throws Exception { // return obj.toString(); // } // // @Override // public Status unmarshal(String str) throws Exception { // for (Status j : Status.class.getEnumConstants()) { // if (j.toString().equals(str)) { // return j; // } // } // throw new Exception("Can't convert " + str + " to " // + Status.class.getName()); // } // // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java // @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") // @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) // @XmlRootElement // public abstract class Action extends RestSource { // @XmlElement // protected int actionId; // // /** // * Reference to original command which generated this action. // */ // @XmlElement // protected String cmdPath; // // /** // * Unique identifier of the action type. // */ // @XmlElement // protected String actionType; // // /** // * A list of states, this action depends on. // */ // @XmlElement // protected List<ActionDependency> dependencies; // // /** // * When the action is successfully executed, expectedResults stores the state // * entry for the action. // */ // @XmlElement // protected List<StateEntry> expectedResults; // // /** // * Role is a reference to a list of nodes that should execute this action. // */ // @XmlElement // protected String role; // // public int getActionId() { // return actionId; // } // // public String getCmdPath() { // return cmdPath; // } // // public String getActionType() { // return actionType; // } // // public List<ActionDependency> getDependencies() { // return dependencies; // } // // public List<StateEntry> getExpectedResults() { // return expectedResults; // } // // public String getRole() { // return role; // } // // public void setActionId(int actionId) { // this.actionId = actionId; // } // // public void setCmdPath(String cmdPath) { // this.cmdPath = cmdPath; // } // // public void setActionType(String actionType) { // this.actionType = actionType; // } // // public void setDependencies(List<ActionDependency> dependencies) { // this.dependencies = dependencies; // } // // public void setExpectedResults(List<StateEntry> expectedResults) { // this.expectedResults = expectedResults; // } // // public void setRole(String role) { // this.role = role; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("actionId="); // sb.append(actionId); // sb.append(", cmdPath="); // sb.append(cmdPath); // sb.append(", actionType="); // sb.append(actionType); // if (role != null) { // sb.append(", role="); // sb.append(role); // } // sb.append(", dependencies=["); // if (dependencies != null) { // for(ActionDependency a : dependencies) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // sb.append(", expectedResults=["); // if (expectedResults != null) { // for(StateEntry a : expectedResults) { // sb.append(a); // sb.append(", "); // } // } // sb.append("]"); // return sb.toString(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/command/CommandStatus.java import org.apache.hms.common.entity.action.Action; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.Status; import org.apache.hms.common.entity.Status.StatusAdapter; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("cmdStatus="); sb.append(status); sb.append(", startTime="); sb.append(startTime); sb.append(", endTime="); sb.append(endTime); sb.append(", clusterName="); sb.append(clusterName); sb.append(", totalActions="); sb.append(totalActions); sb.append(", completedActions="); sb.append(completedActions); sb.append(", actions="); if (actionEntries != null) { for(ActionEntry a : actionEntries) { sb.append("\n"); sb.append(a); } } return sb.toString(); } @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement @XmlType(name="", propOrder = {}) public static class ActionEntry {
protected Action action;
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/action/Action.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // }
import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * HMS Action defines a operation for HMS Agent to execute, this abstract class defines the basic * structure required to construct an HMS Action. * */ @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) @XmlRootElement
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * HMS Action defines a operation for HMS Agent to execute, this abstract class defines the basic * structure required to construct an HMS Action. * */ @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) @XmlRootElement
public abstract class Action extends RestSource {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/action/Action.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // }
import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * HMS Action defines a operation for HMS Agent to execute, this abstract class defines the basic * structure required to construct an HMS Action. * */ @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) @XmlRootElement public abstract class Action extends RestSource { @XmlElement protected int actionId; /** * Reference to original command which generated this action. */ @XmlElement protected String cmdPath; /** * Unique identifier of the action type. */ @XmlElement protected String actionType; /** * A list of states, this action depends on. */ @XmlElement protected List<ActionDependency> dependencies; /** * When the action is successfully executed, expectedResults stores the state * entry for the action. */ @XmlElement
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // } // Path: common/src/main/java/org/apache/hms/common/entity/action/Action.java import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * HMS Action defines a operation for HMS Agent to execute, this abstract class defines the basic * structure required to construct an HMS Action. * */ @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@action") @XmlSeeAlso({ ScriptAction.class, DaemonAction.class, PackageAction.class }) @XmlRootElement public abstract class Action extends RestSource { @XmlElement protected int actionId; /** * Reference to original command which generated this action. */ @XmlElement protected String cmdPath; /** * Unique identifier of the action type. */ @XmlElement protected String actionType; /** * A list of states, this action depends on. */ @XmlElement protected List<ActionDependency> dependencies; /** * When the action is successfully executed, expectedResults stores the state * entry for the action. */ @XmlElement
protected List<StateEntry> expectedResults;
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/Command.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {})
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // Path: common/src/main/java/org/apache/hms/common/entity/command/Command.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.hms.common.entity.RestSource; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {})
public abstract class Command extends RestSource {
macroadster/HMS
common/src/main/java/org/apache/hms/common/util/JAXBUtil.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // }
import java.io.IOException; import java.io.StringWriter; import org.apache.hms.common.entity.RestSource; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.AnnotationIntrospector; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.util; public class JAXBUtil { private static ObjectMapper mapper = new ObjectMapper(); private static AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); public JAXBUtil() { mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); mapper.getSerializationConfig().setAnnotationIntrospector(introspector); }
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // Path: common/src/main/java/org/apache/hms/common/util/JAXBUtil.java import java.io.IOException; import java.io.StringWriter; import org.apache.hms.common.entity.RestSource; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.AnnotationIntrospector; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.util; public class JAXBUtil { private static ObjectMapper mapper = new ObjectMapper(); private static AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); public JAXBUtil() { mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); mapper.getSerializationConfig().setAnnotationIntrospector(introspector); }
public static byte[] write(RestSource x) throws IOException {
macroadster/HMS
agent/src/main/java/org/apache/hms/agent/rest/PackageManager.java
// Path: agent/src/main/java/org/apache/hms/agent/dispatcher/PackageRunner.java // public class PackageRunner { // private static Log log = LogFactory.getLog(PackageRunner.class); // // public Response install(PackageCommand dc) { // dc.setCmd("install"); // if(dc.getDryRun()) { // return dryRun(dc); // } // return helper(dc); // } // // public Response remove(PackageCommand dc) { // dc.setCmd("erase"); // return helper(dc); // } // // public Response query(PackageCommand dc) { // dc.setCmd("info"); // return helper(dc); // } // // private Response helper(PackageCommand dc) { // ScriptCommand cmd = new ScriptCommand(); // cmd.setCmd(dc.getCmd()); // Response r = null; // cmd.setScript("yum"); // String[] parms = null; // if(dc.getPackages().length>0) { // parms = new String[dc.getPackages().length+2]; // for(int i = 0; i< dc.getPackages().length;i++) { // parms[i+2] = dc.getPackages()[i].getName(); // } // } // if(parms != null) { // parms[0] = dc.getCmd(); // parms[1] = "-y"; // cmd.setParms(parms); // ShellRunner shell = new ShellRunner(); // r = shell.run(cmd); // } else { // r = new Response(); // r.setCode(1); // r.setError("Invalid package name"); // } // return r; // } // // private Response dryRun(PackageCommand dc) { // Response r = null; // ScriptCommand cmd = new ScriptCommand(); // cmd.setCmd(dc.getCmd()); // cmd.setScript("yum"); // PackageInfo[] packages = dc.getPackages(); // String[] parms = new String[packages.length+4]; // parms[0] = "install"; // parms[1] = "-y"; // parms[2] = "--downloadonly"; // parms[3] = "--downloaddir=/tmp/system_update"; // for(int i=0;i<packages.length;i++) { // parms[i+4] = packages[i].getName(); // } // cmd.setParms(parms); // ShellRunner shell = new ShellRunner(); // r = shell.run(cmd); // if(r.getCode()!=1) { // return r; // } else { // cmd.setScript("rpm"); // String[] rpmParms = new String[3]; // rpmParms[0] = "-i"; // rpmParms[1] = "--test"; // rpmParms[2] = "/tmp/system_update/*.rpm"; // cmd.setParms(rpmParms); // r = shell.run(cmd); // FileUtil.deleteDir(new File("/tmp/system_update")); // return r; // } // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // }
import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.apache.hms.agent.dispatcher.PackageRunner; import org.apache.hms.common.entity.PackageCommand; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.rest.Response;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.agent.rest; @Path("package") public class PackageManager extends RestSource { @POST @Path("install") public Response install(PackageCommand pc) {
// Path: agent/src/main/java/org/apache/hms/agent/dispatcher/PackageRunner.java // public class PackageRunner { // private static Log log = LogFactory.getLog(PackageRunner.class); // // public Response install(PackageCommand dc) { // dc.setCmd("install"); // if(dc.getDryRun()) { // return dryRun(dc); // } // return helper(dc); // } // // public Response remove(PackageCommand dc) { // dc.setCmd("erase"); // return helper(dc); // } // // public Response query(PackageCommand dc) { // dc.setCmd("info"); // return helper(dc); // } // // private Response helper(PackageCommand dc) { // ScriptCommand cmd = new ScriptCommand(); // cmd.setCmd(dc.getCmd()); // Response r = null; // cmd.setScript("yum"); // String[] parms = null; // if(dc.getPackages().length>0) { // parms = new String[dc.getPackages().length+2]; // for(int i = 0; i< dc.getPackages().length;i++) { // parms[i+2] = dc.getPackages()[i].getName(); // } // } // if(parms != null) { // parms[0] = dc.getCmd(); // parms[1] = "-y"; // cmd.setParms(parms); // ShellRunner shell = new ShellRunner(); // r = shell.run(cmd); // } else { // r = new Response(); // r.setCode(1); // r.setError("Invalid package name"); // } // return r; // } // // private Response dryRun(PackageCommand dc) { // Response r = null; // ScriptCommand cmd = new ScriptCommand(); // cmd.setCmd(dc.getCmd()); // cmd.setScript("yum"); // PackageInfo[] packages = dc.getPackages(); // String[] parms = new String[packages.length+4]; // parms[0] = "install"; // parms[1] = "-y"; // parms[2] = "--downloadonly"; // parms[3] = "--downloaddir=/tmp/system_update"; // for(int i=0;i<packages.length;i++) { // parms[i+4] = packages[i].getName(); // } // cmd.setParms(parms); // ShellRunner shell = new ShellRunner(); // r = shell.run(cmd); // if(r.getCode()!=1) { // return r; // } else { // cmd.setScript("rpm"); // String[] rpmParms = new String[3]; // rpmParms[0] = "-i"; // rpmParms[1] = "--test"; // rpmParms[2] = "/tmp/system_update/*.rpm"; // cmd.setParms(rpmParms); // r = shell.run(cmd); // FileUtil.deleteDir(new File("/tmp/system_update")); // return r; // } // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // Path: agent/src/main/java/org/apache/hms/agent/rest/PackageManager.java import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.apache.hms.agent.dispatcher.PackageRunner; import org.apache.hms.common.entity.PackageCommand; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.rest.Response; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.agent.rest; @Path("package") public class PackageManager extends RestSource { @POST @Path("install") public Response install(PackageCommand pc) {
PackageRunner pr = new PackageRunner();
macroadster/HMS
common/src/test/java/org/apache/hms/common/util/TestMulticastDNS.java
// Path: common/src/main/java/org/apache/hms/common/util/ExceptionUtil.java // public class ExceptionUtil { // public static String getStackTrace(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // }
import java.net.InetAddress; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.hms.common.util.ExceptionUtil;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.util; /** * Test MulticastDNS and ServiceDiscoveryUtil class * */ public class TestMulticastDNS { private static Log LOG = LogFactory.getLog(TestMulticastDNS.class); @Test public void testZeroconf() { try { String type = "_test._tcp.local."; InetAddress addr = InetAddress.getLocalHost(); ; ServiceDiscoveryUtil sdu = new ServiceDiscoveryUtil(addr, type); sdu.start(); MulticastDNS mdns = new MulticastDNS(addr, type, 2181); mdns.handleRegisterCommand(); Thread.sleep(5000); Collection<String> list = sdu.resolve(); mdns.handleUnregisterCommand(); boolean test = false; for(String x : list) { if(x.contains(addr.getHostAddress())) { test = true; } } Assert.assertEquals(test, true); } catch (Exception e) {
// Path: common/src/main/java/org/apache/hms/common/util/ExceptionUtil.java // public class ExceptionUtil { // public static String getStackTrace(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // } // Path: common/src/test/java/org/apache/hms/common/util/TestMulticastDNS.java import java.net.InetAddress; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.hms.common.util.ExceptionUtil; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.util; /** * Test MulticastDNS and ServiceDiscoveryUtil class * */ public class TestMulticastDNS { private static Log LOG = LogFactory.getLog(TestMulticastDNS.class); @Test public void testZeroconf() { try { String type = "_test._tcp.local."; InetAddress addr = InetAddress.getLocalHost(); ; ServiceDiscoveryUtil sdu = new ServiceDiscoveryUtil(addr, type); sdu.start(); MulticastDNS mdns = new MulticastDNS(addr, type, 2181); mdns.handleRegisterCommand(); Thread.sleep(5000); Collection<String> list = sdu.resolve(); mdns.handleUnregisterCommand(); boolean test = false; for(String x : list) { if(x.contains(addr.getHostAddress())) { test = true; } } Assert.assertEquals(test, true); } catch (Exception e) {
LOG.error(ExceptionUtil.getStackTrace(e));
macroadster/HMS
beacon/src/main/java/org/apache/hms/beacon/Beacon.java
// Path: common/src/main/java/org/apache/hms/common/util/DaemonWatcher.java // public class DaemonWatcher extends PidFile { // private static DaemonWatcher instance = null; // // public synchronized static DaemonWatcher createInstance(String name, int port) { // if(instance == null) { // instance = new DaemonWatcher(name, port); // Runtime.getRuntime().addShutdownHook(instance); // } // return instance; // } // // public static DaemonWatcher getInstance() { // return instance; // } // // private DaemonWatcher(String name, int port) { // super(name, port); // } // // public static void bailout(int status) { // System.exit(status); // } // } // // Path: common/src/main/java/org/apache/hms/common/util/MulticastDNS.java // public class MulticastDNS { // private static Log LOG = LogFactory.getLog(MulticastDNS.class); // public static JmDNS jmdns; // private InetAddress addr; // private String svcType = "_zookeeper._tcp.local."; // private String svcName; // private int svcPort = 2181; // private Hashtable<String, String> settings; // // public MulticastDNS() throws UnknownHostException { // super(); // InetAddress addr = InetAddress.getLocalHost(); // String hostname = addr.getHostName(); // if(hostname.indexOf('.')>0) { // hostname = hostname.substring(0, hostname.indexOf('.')); // } // svcName = hostname; // settings = new Hashtable<String,String>(); // settings.put("host", svcName); // settings.put("port", new Integer(svcPort).toString()); // } // // public MulticastDNS(String svcType, int svcPort) throws UnknownHostException { // this(); // this.svcType = svcType; // this.svcPort = svcPort; // } // // public MulticastDNS(InetAddress addr, String svcType, int svcPort) throws UnknownHostException { // this(); // this.addr = addr; // this.svcType = svcType; // this.svcPort = svcPort; // } // // protected void handleRegisterCommand() throws IOException { // if(jmdns==null) { // if(addr!=null) { // jmdns = JmDNS.create(this.addr); // } else { // jmdns = JmDNS.create(); // } // } // ServiceInfo svcInfo = ServiceInfo.create(svcType, svcName, svcPort, 1, 1, settings); // try { // this.jmdns.registerService(svcInfo); // LOG.info("Registered service '" + svcName + "' as: " + svcInfo); // } catch (IOException e) { // LOG.error("Failed to register service '" + svcName + "'"); // } // } // // protected void handleUnregisterCommand() { // this.jmdns.unregisterAllServices(); // try { // this.jmdns.close(); // } catch (IOException e) { // LOG.error(ExceptionUtil.getStackTrace(e)); // } // } // // }
import java.io.IOException; import java.net.UnknownHostException; import org.apache.hms.common.util.DaemonWatcher; import org.apache.hms.common.util.MulticastDNS;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.beacon; /** * * HMS Beacon broadcast ZooKeeper server location by using MulticastDNS. * This utility runs on the same node as ZooKeeper server. * */ public class Beacon extends MulticastDNS { public Beacon() throws UnknownHostException { super(); } public Beacon(String svcType, int svcPort) throws UnknownHostException { super(svcType, svcPort); } /** * Register Zookeeper host location in MulticastDNS * @throws IOException */ public void start() throws IOException { handleRegisterCommand(); } /** * Remove Zookeeper host location from MulticastDNS * @throws IOException */ public void stop() throws IOException { handleUnregisterCommand(); } public static void main(String[] args) throws IOException {
// Path: common/src/main/java/org/apache/hms/common/util/DaemonWatcher.java // public class DaemonWatcher extends PidFile { // private static DaemonWatcher instance = null; // // public synchronized static DaemonWatcher createInstance(String name, int port) { // if(instance == null) { // instance = new DaemonWatcher(name, port); // Runtime.getRuntime().addShutdownHook(instance); // } // return instance; // } // // public static DaemonWatcher getInstance() { // return instance; // } // // private DaemonWatcher(String name, int port) { // super(name, port); // } // // public static void bailout(int status) { // System.exit(status); // } // } // // Path: common/src/main/java/org/apache/hms/common/util/MulticastDNS.java // public class MulticastDNS { // private static Log LOG = LogFactory.getLog(MulticastDNS.class); // public static JmDNS jmdns; // private InetAddress addr; // private String svcType = "_zookeeper._tcp.local."; // private String svcName; // private int svcPort = 2181; // private Hashtable<String, String> settings; // // public MulticastDNS() throws UnknownHostException { // super(); // InetAddress addr = InetAddress.getLocalHost(); // String hostname = addr.getHostName(); // if(hostname.indexOf('.')>0) { // hostname = hostname.substring(0, hostname.indexOf('.')); // } // svcName = hostname; // settings = new Hashtable<String,String>(); // settings.put("host", svcName); // settings.put("port", new Integer(svcPort).toString()); // } // // public MulticastDNS(String svcType, int svcPort) throws UnknownHostException { // this(); // this.svcType = svcType; // this.svcPort = svcPort; // } // // public MulticastDNS(InetAddress addr, String svcType, int svcPort) throws UnknownHostException { // this(); // this.addr = addr; // this.svcType = svcType; // this.svcPort = svcPort; // } // // protected void handleRegisterCommand() throws IOException { // if(jmdns==null) { // if(addr!=null) { // jmdns = JmDNS.create(this.addr); // } else { // jmdns = JmDNS.create(); // } // } // ServiceInfo svcInfo = ServiceInfo.create(svcType, svcName, svcPort, 1, 1, settings); // try { // this.jmdns.registerService(svcInfo); // LOG.info("Registered service '" + svcName + "' as: " + svcInfo); // } catch (IOException e) { // LOG.error("Failed to register service '" + svcName + "'"); // } // } // // protected void handleUnregisterCommand() { // this.jmdns.unregisterAllServices(); // try { // this.jmdns.close(); // } catch (IOException e) { // LOG.error(ExceptionUtil.getStackTrace(e)); // } // } // // } // Path: beacon/src/main/java/org/apache/hms/beacon/Beacon.java import java.io.IOException; import java.net.UnknownHostException; import org.apache.hms.common.util.DaemonWatcher; import org.apache.hms.common.util.MulticastDNS; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.beacon; /** * * HMS Beacon broadcast ZooKeeper server location by using MulticastDNS. * This utility runs on the same node as ZooKeeper server. * */ public class Beacon extends MulticastDNS { public Beacon() throws UnknownHostException { super(); } public Beacon(String svcType, int svcPort) throws UnknownHostException { super(svcType, svcPort); } /** * Register Zookeeper host location in MulticastDNS * @throws IOException */ public void start() throws IOException { handleRegisterCommand(); } /** * Remove Zookeeper host location from MulticastDNS * @throws IOException */ public void stop() throws IOException { handleUnregisterCommand(); } public static void main(String[] args) throws IOException {
DaemonWatcher.createInstance(System.getProperty("PID"), 9101);
macroadster/HMS
agent/src/main/java/org/apache/hms/agent/dispatcher/ShellRunner.java
// Path: agent/src/main/java/org/apache/hms/agent/Agent.java // public class Agent { // private static Log log = LogFactory.getLog(Agent.class); // // private static Agent instance = null; // private Server server = null; // private static URL serverConf = null; // // public static Agent getInstance() { // if(instance==null) { // instance = new Agent(); // } // return instance; // } // // public void start() { // try { // System.out.close(); // System.err.close(); // instance = this; // run(); // } catch(Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // System.exit(-1); // } // } // // public void run() { // server = new Server(4080); // // XmlConfiguration configuration; // try { // Context root = new Context(server, "/", Context.SESSIONS); // ServletHolder sh = new ServletHolder(ServletContainer.class); // sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); // sh.setInitParameter("com.sun.jersey.config.property.packages", "org.apache.hms.agent.rest"); // root.addServlet(sh, "/*"); // server.setStopAtShutdown(true); // server.start(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public void stop() throws Exception { // try { // server.stop(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public static void main(String[] args) { // Agent agent = Agent.getInstance(); // agent.start(); // } // // } // // Path: common/src/main/java/org/apache/hms/common/util/ExceptionUtil.java // public class ExceptionUtil { // public static String getStackTrace(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // }
import java.io.DataInputStream; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hms.agent.Agent; import org.apache.hms.common.entity.ScriptCommand; import org.apache.hms.common.rest.Response; import org.apache.hms.common.util.ExceptionUtil;
Process proc; try { String[] parameters = cmd.getParms(); int size = 0; if(parameters!=null) { size = parameters.length; } String[] cmdArray = new String[size+1]; cmdArray[0]=cmd.getScript(); for(int i=0;i<size;i++) { cmdArray[i+1]=parameters[i]; } proc = Runtime.getRuntime().exec(cmdArray); DataInputStream in = new DataInputStream(proc.getInputStream()); DataInputStream err = new DataInputStream(proc.getErrorStream()); String str; while ((str = in.readLine()) != null) { stdout.append(str); stdout.append("\n"); } while ((str = err.readLine()) != null) { errorBuffer.append(str); errorBuffer.append("\n"); } int exitCode = proc.waitFor(); r.setCode(exitCode); r.setError(errorBuffer.toString()); r.setOutput(stdout.toString()); } catch (Exception e) { r.setCode(1);
// Path: agent/src/main/java/org/apache/hms/agent/Agent.java // public class Agent { // private static Log log = LogFactory.getLog(Agent.class); // // private static Agent instance = null; // private Server server = null; // private static URL serverConf = null; // // public static Agent getInstance() { // if(instance==null) { // instance = new Agent(); // } // return instance; // } // // public void start() { // try { // System.out.close(); // System.err.close(); // instance = this; // run(); // } catch(Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // System.exit(-1); // } // } // // public void run() { // server = new Server(4080); // // XmlConfiguration configuration; // try { // Context root = new Context(server, "/", Context.SESSIONS); // ServletHolder sh = new ServletHolder(ServletContainer.class); // sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); // sh.setInitParameter("com.sun.jersey.config.property.packages", "org.apache.hms.agent.rest"); // root.addServlet(sh, "/*"); // server.setStopAtShutdown(true); // server.start(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public void stop() throws Exception { // try { // server.stop(); // } catch (Exception e) { // log.error(ExceptionUtil.getStackTrace(e)); // } // } // // public static void main(String[] args) { // Agent agent = Agent.getInstance(); // agent.start(); // } // // } // // Path: common/src/main/java/org/apache/hms/common/util/ExceptionUtil.java // public class ExceptionUtil { // public static String getStackTrace(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // } // Path: agent/src/main/java/org/apache/hms/agent/dispatcher/ShellRunner.java import java.io.DataInputStream; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hms.agent.Agent; import org.apache.hms.common.entity.ScriptCommand; import org.apache.hms.common.rest.Response; import org.apache.hms.common.util.ExceptionUtil; Process proc; try { String[] parameters = cmd.getParms(); int size = 0; if(parameters!=null) { size = parameters.length; } String[] cmdArray = new String[size+1]; cmdArray[0]=cmd.getScript(); for(int i=0;i<size;i++) { cmdArray[i+1]=parameters[i]; } proc = Runtime.getRuntime().exec(cmdArray); DataInputStream in = new DataInputStream(proc.getInputStream()); DataInputStream err = new DataInputStream(proc.getErrorStream()); String str; while ((str = in.readLine()) != null) { stdout.append(str); stdout.append("\n"); } while ((str = err.readLine()) != null) { errorBuffer.append(str); errorBuffer.append("\n"); } int exitCode = proc.waitFor(); r.setCode(exitCode); r.setError(errorBuffer.toString()); r.setOutput(stdout.toString()); } catch (Exception e) { r.setCode(1);
r.setError(ExceptionUtil.getStackTrace(e));
macroadster/HMS
common/src/main/java/org/apache/hms/common/util/ZookeeperUtil.java
// Path: common/src/main/java/org/apache/hms/common/conf/CommonConfigurationKeys.java // public class CommonConfigurationKeys { // // /** Location of zookeeper servers */ // public static final String ZOOKEEPER_ADDRESS_KEY = "hms.zookeeper.address"; // /** Default location of zookeeper servers */ // public static final String ZOOKEEPER_ADDRESS_DEFAULT = "localhost:2181"; // // /** Path to zookeeper cluster root */ // public static final String ZOOKEEPER_CLUSTER_ROOT_KEY = "hms.zookeeper.cluster.path"; // /** Default location of zookeeper cluster root */ // public static final String ZOOKEEPER_CLUSTER_ROOT_DEFAULT = "/clusters"; // // /** Path to zookeeper command queue */ // public static final String ZOOKEEPER_COMMAND_QUEUE_PATH_KEY = "hms.zookeeper.command.queue.path"; // /** Default location of zookeeper command queue */ // public static final String ZOOKEEPER_COMMAND_QUEUE_PATH_DEFAULT = "/cmdqueue"; // // /** Path to zookeeper live controller queue */ // public static final String ZOOKEEPER_LIVE_CONTROLLER_PATH_KEY = "hms.zookeeper.live.controller.path"; // /** Default location of zookeeper live controller queue */ // public static final String ZOOKEEPER_LIVE_CONTROLLER_PATH_DEFAULT = "/livecontrollers"; // // /** Path to zookeeper lock queue */ // public static final String ZOOKEEPER_LOCK_QUEUE_PATH_KEY = "hms.zookeeper.lock.queue.path"; // /** Default location of zookeeper lock queue */ // public static final String ZOOKEEPER_LOCK_QUEUE_PATH_DEFAULT = "/locks"; // // /** Reference key for path to nodes manifest */ // public static final String ZOOKEEPER_NODES_MANIFEST_KEY = "hms.nodes.manifest.path"; // /** Default location of nodes manifest */ // public static final String ZOOKEEPER_NODES_MANIFEST_PATH_DEFAULT = "/nodes-manifest"; // // /** Zeroconf zookeeper type */ // public static final String ZEROCONF_ZOOKEEPER_TYPE = "_zookeeper._tcp.local."; // // /** Path to zookeeper status qeueue */ // public static final String ZOOKEEPER_STATUS_QUEUE_PATH_KEY = "hms.zookeeper.status.queue.path"; // /** Default location of zookeeper status queue */ // public static final String ZOOKEEPER_STATUS_QUEUE_PATH_DEFAULT = "/status"; // // /** Path to zookeeper software manifest */ // public static final String ZOOKEEPER_SOFTWARE_MANIFEST_KEY = "hms.software.manifest.path"; // // /** Default location of software manifest */ // public static final String ZOOKEEPER_SOFTWARE_MANIFEST_PATH_DEFAULT = "/software-manifest"; // // /** Path to zookeeper config blueprint */ // public static final String ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT = "/config-blueprint"; // }
import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hms.common.conf.CommonConfigurationKeys;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.util; public class ZookeeperUtil { public static String COMMAND_STATUS = "/status"; private static final Pattern BASENAME = Pattern.compile(".*?([^/]*)$"); public static String getClusterPath(String clusterName) { StringBuilder clusterNode = new StringBuilder();
// Path: common/src/main/java/org/apache/hms/common/conf/CommonConfigurationKeys.java // public class CommonConfigurationKeys { // // /** Location of zookeeper servers */ // public static final String ZOOKEEPER_ADDRESS_KEY = "hms.zookeeper.address"; // /** Default location of zookeeper servers */ // public static final String ZOOKEEPER_ADDRESS_DEFAULT = "localhost:2181"; // // /** Path to zookeeper cluster root */ // public static final String ZOOKEEPER_CLUSTER_ROOT_KEY = "hms.zookeeper.cluster.path"; // /** Default location of zookeeper cluster root */ // public static final String ZOOKEEPER_CLUSTER_ROOT_DEFAULT = "/clusters"; // // /** Path to zookeeper command queue */ // public static final String ZOOKEEPER_COMMAND_QUEUE_PATH_KEY = "hms.zookeeper.command.queue.path"; // /** Default location of zookeeper command queue */ // public static final String ZOOKEEPER_COMMAND_QUEUE_PATH_DEFAULT = "/cmdqueue"; // // /** Path to zookeeper live controller queue */ // public static final String ZOOKEEPER_LIVE_CONTROLLER_PATH_KEY = "hms.zookeeper.live.controller.path"; // /** Default location of zookeeper live controller queue */ // public static final String ZOOKEEPER_LIVE_CONTROLLER_PATH_DEFAULT = "/livecontrollers"; // // /** Path to zookeeper lock queue */ // public static final String ZOOKEEPER_LOCK_QUEUE_PATH_KEY = "hms.zookeeper.lock.queue.path"; // /** Default location of zookeeper lock queue */ // public static final String ZOOKEEPER_LOCK_QUEUE_PATH_DEFAULT = "/locks"; // // /** Reference key for path to nodes manifest */ // public static final String ZOOKEEPER_NODES_MANIFEST_KEY = "hms.nodes.manifest.path"; // /** Default location of nodes manifest */ // public static final String ZOOKEEPER_NODES_MANIFEST_PATH_DEFAULT = "/nodes-manifest"; // // /** Zeroconf zookeeper type */ // public static final String ZEROCONF_ZOOKEEPER_TYPE = "_zookeeper._tcp.local."; // // /** Path to zookeeper status qeueue */ // public static final String ZOOKEEPER_STATUS_QUEUE_PATH_KEY = "hms.zookeeper.status.queue.path"; // /** Default location of zookeeper status queue */ // public static final String ZOOKEEPER_STATUS_QUEUE_PATH_DEFAULT = "/status"; // // /** Path to zookeeper software manifest */ // public static final String ZOOKEEPER_SOFTWARE_MANIFEST_KEY = "hms.software.manifest.path"; // // /** Default location of software manifest */ // public static final String ZOOKEEPER_SOFTWARE_MANIFEST_PATH_DEFAULT = "/software-manifest"; // // /** Path to zookeeper config blueprint */ // public static final String ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT = "/config-blueprint"; // } // Path: common/src/main/java/org/apache/hms/common/util/ZookeeperUtil.java import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hms.common.conf.CommonConfigurationKeys; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.util; public class ZookeeperUtil { public static String COMMAND_STATUS = "/status"; private static final Pattern BASENAME = Pattern.compile(".*?([^/]*)$"); public static String getClusterPath(String clusterName) { StringBuilder clusterNode = new StringBuilder();
clusterNode.append(CommonConfigurationKeys.ZOOKEEPER_CLUSTER_ROOT_DEFAULT);
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/action/ActionDependency.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/manifest/Role.java // public class Role extends RestSource { // @XmlAttribute // public String name; // @XmlElement(name="package") // private PackageInfo[] packages; // @XmlElement(name="host") // private String[] hosts; // // public String getName() { // return this.name; // } // // public PackageInfo[] getPackages() { // return this.packages; // } // // public String[] getHosts() { // return this.hosts; // } // // public void setName(String name) { // this.name = name; // } // // public void setPackages(PackageInfo[] packages) { // this.packages = packages; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // }
import org.apache.hms.common.entity.manifest.Role; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * Defines the list of states that a action depends on. */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {})
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/manifest/Role.java // public class Role extends RestSource { // @XmlAttribute // public String name; // @XmlElement(name="package") // private PackageInfo[] packages; // @XmlElement(name="host") // private String[] hosts; // // public String getName() { // return this.name; // } // // public PackageInfo[] getPackages() { // return this.packages; // } // // public String[] getHosts() { // return this.hosts; // } // // public void setName(String name) { // this.name = name; // } // // public void setPackages(PackageInfo[] packages) { // this.packages = packages; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // } // Path: common/src/main/java/org/apache/hms/common/entity/action/ActionDependency.java import org.apache.hms.common.entity.manifest.Role; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * Defines the list of states that a action depends on. */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {})
public class ActionDependency extends RestSource {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/action/ActionDependency.java
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/manifest/Role.java // public class Role extends RestSource { // @XmlAttribute // public String name; // @XmlElement(name="package") // private PackageInfo[] packages; // @XmlElement(name="host") // private String[] hosts; // // public String getName() { // return this.name; // } // // public PackageInfo[] getPackages() { // return this.packages; // } // // public String[] getHosts() { // return this.hosts; // } // // public void setName(String name) { // this.name = name; // } // // public void setPackages(PackageInfo[] packages) { // this.packages = packages; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // }
import org.apache.hms.common.entity.manifest.Role; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * Defines the list of states that a action depends on. */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {}) public class ActionDependency extends RestSource { @XmlElement protected List<String> hosts; @XmlElement
// Path: common/src/main/java/org/apache/hms/common/entity/RestSource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name="", propOrder = {}) // public abstract class RestSource { // // } // // Path: common/src/main/java/org/apache/hms/common/entity/cluster/MachineState.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public static class StateEntry { // private static final int PRIME = 16777619; // // @XmlElement // @XmlJavaTypeAdapter(StateTypeAdapter.class) // protected StateType type; // @XmlElement // protected String name; // @XmlElement // @XmlJavaTypeAdapter(StatusAdapter.class) // protected Status status; // // public StateEntry(){ // } // // public StateEntry(StateType type, String name, Status status) { // this.type = type; // this.name = name; // this.status = status; // } // // public StateType getType() { // return type; // } // // public String getName() { // return name; // } // // public Status getStatus() { // return status; // } // // public void setType(StateType type) { // this.type = type; // } // // public void setName(String name) { // this.name = name; // } // // public void setStatus(Status status) { // this.status = status; // } // // static boolean isEqual(Object a, Object b) { // return a == null ? b == null : a.equals(b); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj instanceof StateEntry) { // StateEntry that = (StateEntry) obj; // return this.type == that.type // && isEqual(this.name, that.name); // } // return false; // } // // @Override // public int hashCode() { // int result = 1; // result = PRIME * result + ((type == null) ? 0 : type.hashCode()); // result = PRIME * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("("); // sb.append(type); // sb.append(":"); // sb.append(name); // sb.append(":"); // sb.append(status); // sb.append(")"); // return sb.toString(); // } // } // // Path: common/src/main/java/org/apache/hms/common/entity/manifest/Role.java // public class Role extends RestSource { // @XmlAttribute // public String name; // @XmlElement(name="package") // private PackageInfo[] packages; // @XmlElement(name="host") // private String[] hosts; // // public String getName() { // return this.name; // } // // public PackageInfo[] getPackages() { // return this.packages; // } // // public String[] getHosts() { // return this.hosts; // } // // public void setName(String name) { // this.name = name; // } // // public void setPackages(PackageInfo[] packages) { // this.packages = packages; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // } // Path: common/src/main/java/org/apache/hms/common/entity/action/ActionDependency.java import org.apache.hms.common.entity.manifest.Role; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.RestSource; import org.apache.hms.common.entity.cluster.MachineState.StateEntry; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.action; /** * Defines the list of states that a action depends on. */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="", propOrder = {}) public class ActionDependency extends RestSource { @XmlElement protected List<String> hosts; @XmlElement
protected List<StateEntry> states;
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/command/CreateClusterCommand.java
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java // @XmlRootElement // public class ClusterManifest extends Manifest { // @XmlAttribute // private String clusterName; // @XmlElement // private NodesManifest nodes; // @XmlElement // private SoftwareManifest software; // @XmlElement // private ConfigManifest config; // // public String getClusterName() { // return this.clusterName; // } // // public NodesManifest getNodes() { // return this.nodes; // } // // public SoftwareManifest getSoftware() { // return this.software; // } // // public ConfigManifest getConfig() { // return this.config; // } // // public void setClusterName(String cluster) { // this.clusterName = cluster; // } // // public void setNodes(NodesManifest nodes) { // this.nodes = nodes; // } // // public void setSoftware(SoftwareManifest software) { // this.software = software; // } // // public void setConfig(ConfigManifest config) { // this.config = config; // } // // public void load() throws IOException { // if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { // URL url = nodes.getUrl(); // nodes = fetch(url, NodesManifest.class); // nodes.setUrl(url); // } // if(software!=null && software.getUrl()!=null && software.getRoles()==null) { // URL url = software.getUrl(); // software = fetch(url, SoftwareManifest.class); // software.setUrl(url); // } // if(config!=null && config.getUrl()!=null && config.getActions()==null) { // URL url = config.getUrl(); // config = fetch(url, ConfigManifest.class); // config.setUrl(url); // config.expand(nodes); // } // } // // private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { // if(url.getProtocol().toLowerCase().equals("file")) { // FileReader fstream = new FileReader(url.getPath()); // BufferedReader in = new BufferedReader(fstream); // StringBuilder buffer = new StringBuilder(); // String str; // while((str = in.readLine()) != null) { // buffer.append(str); // } // return JAXBUtil.read(buffer.toString().getBytes(), c); // } else { // com.sun.jersey.api.client.Client wsClient = com.sun.jersey.api.client.Client.create(); // WebResource webResource = wsClient.resource(url.toString()); // return webResource.get(c); // } // } // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.manifest.ClusterManifest; import org.codehaus.jackson.annotate.JsonTypeInfo;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlType(name="", propOrder = {}) public class CreateClusterCommand extends ClusterCommand { public CreateClusterCommand() { this.cmd = CmdType.CREATE; }
// Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java // @XmlRootElement // public class ClusterManifest extends Manifest { // @XmlAttribute // private String clusterName; // @XmlElement // private NodesManifest nodes; // @XmlElement // private SoftwareManifest software; // @XmlElement // private ConfigManifest config; // // public String getClusterName() { // return this.clusterName; // } // // public NodesManifest getNodes() { // return this.nodes; // } // // public SoftwareManifest getSoftware() { // return this.software; // } // // public ConfigManifest getConfig() { // return this.config; // } // // public void setClusterName(String cluster) { // this.clusterName = cluster; // } // // public void setNodes(NodesManifest nodes) { // this.nodes = nodes; // } // // public void setSoftware(SoftwareManifest software) { // this.software = software; // } // // public void setConfig(ConfigManifest config) { // this.config = config; // } // // public void load() throws IOException { // if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { // URL url = nodes.getUrl(); // nodes = fetch(url, NodesManifest.class); // nodes.setUrl(url); // } // if(software!=null && software.getUrl()!=null && software.getRoles()==null) { // URL url = software.getUrl(); // software = fetch(url, SoftwareManifest.class); // software.setUrl(url); // } // if(config!=null && config.getUrl()!=null && config.getActions()==null) { // URL url = config.getUrl(); // config = fetch(url, ConfigManifest.class); // config.setUrl(url); // config.expand(nodes); // } // } // // private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { // if(url.getProtocol().toLowerCase().equals("file")) { // FileReader fstream = new FileReader(url.getPath()); // BufferedReader in = new BufferedReader(fstream); // StringBuilder buffer = new StringBuilder(); // String str; // while((str = in.readLine()) != null) { // buffer.append(str); // } // return JAXBUtil.read(buffer.toString().getBytes(), c); // } else { // com.sun.jersey.api.client.Client wsClient = com.sun.jersey.api.client.Client.create(); // WebResource webResource = wsClient.resource(url.toString()); // return webResource.get(c); // } // } // } // Path: common/src/main/java/org/apache/hms/common/entity/command/CreateClusterCommand.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.hms.common.entity.manifest.ClusterManifest; import org.codehaus.jackson.annotate.JsonTypeInfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.common.entity.command; @XmlRootElement @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@command") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlType(name="", propOrder = {}) public class CreateClusterCommand extends ClusterCommand { public CreateClusterCommand() { this.cmd = CmdType.CREATE; }
public CreateClusterCommand(String clusterName, ClusterManifest cm) {
macroadster/HMS
common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java
// Path: common/src/main/java/org/apache/hms/common/util/JAXBUtil.java // public class JAXBUtil { // // private static ObjectMapper mapper = new ObjectMapper(); // private static AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); // // public JAXBUtil() { // mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); // mapper.getSerializationConfig().setAnnotationIntrospector(introspector); // } // // public static byte[] write(RestSource x) throws IOException { // try { // return mapper.writeValueAsBytes(x); // } catch (Throwable e) { // throw new IOException(e); // } // } // // public static <T> T read(byte[] buffer, java.lang.Class<T> c) throws IOException { // return (T) mapper.readValue(buffer, 0, buffer.length, c); // } // // public static String print(RestSource x) throws IOException { // try { // JsonFactory jf = new JsonFactory(); // StringWriter sw = new StringWriter(); // JsonGenerator jp = jf.createJsonGenerator(sw); // jp.useDefaultPrettyPrinter(); // mapper.writeValue(jp, x); // jp.close(); // String buffer = sw.toString(); // return buffer; // } catch (Throwable e) { // throw new IOException(e); // } // } // }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URL; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.hms.common.util.JAXBUtil; import com.sun.jersey.api.client.WebResource;
} public void load() throws IOException { if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { URL url = nodes.getUrl(); nodes = fetch(url, NodesManifest.class); nodes.setUrl(url); } if(software!=null && software.getUrl()!=null && software.getRoles()==null) { URL url = software.getUrl(); software = fetch(url, SoftwareManifest.class); software.setUrl(url); } if(config!=null && config.getUrl()!=null && config.getActions()==null) { URL url = config.getUrl(); config = fetch(url, ConfigManifest.class); config.setUrl(url); config.expand(nodes); } } private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { if(url.getProtocol().toLowerCase().equals("file")) { FileReader fstream = new FileReader(url.getPath()); BufferedReader in = new BufferedReader(fstream); StringBuilder buffer = new StringBuilder(); String str; while((str = in.readLine()) != null) { buffer.append(str); }
// Path: common/src/main/java/org/apache/hms/common/util/JAXBUtil.java // public class JAXBUtil { // // private static ObjectMapper mapper = new ObjectMapper(); // private static AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); // // public JAXBUtil() { // mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); // mapper.getSerializationConfig().setAnnotationIntrospector(introspector); // } // // public static byte[] write(RestSource x) throws IOException { // try { // return mapper.writeValueAsBytes(x); // } catch (Throwable e) { // throw new IOException(e); // } // } // // public static <T> T read(byte[] buffer, java.lang.Class<T> c) throws IOException { // return (T) mapper.readValue(buffer, 0, buffer.length, c); // } // // public static String print(RestSource x) throws IOException { // try { // JsonFactory jf = new JsonFactory(); // StringWriter sw = new StringWriter(); // JsonGenerator jp = jf.createJsonGenerator(sw); // jp.useDefaultPrettyPrinter(); // mapper.writeValue(jp, x); // jp.close(); // String buffer = sw.toString(); // return buffer; // } catch (Throwable e) { // throw new IOException(e); // } // } // } // Path: common/src/main/java/org/apache/hms/common/entity/manifest/ClusterManifest.java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URL; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.hms.common.util.JAXBUtil; import com.sun.jersey.api.client.WebResource; } public void load() throws IOException { if(nodes!=null && nodes.getUrl()!=null && nodes.getRoles()==null) { URL url = nodes.getUrl(); nodes = fetch(url, NodesManifest.class); nodes.setUrl(url); } if(software!=null && software.getUrl()!=null && software.getRoles()==null) { URL url = software.getUrl(); software = fetch(url, SoftwareManifest.class); software.setUrl(url); } if(config!=null && config.getUrl()!=null && config.getActions()==null) { URL url = config.getUrl(); config = fetch(url, ConfigManifest.class); config.setUrl(url); config.expand(nodes); } } private <T> T fetch(URL url, java.lang.Class<T> c) throws IOException { if(url.getProtocol().toLowerCase().equals("file")) { FileReader fstream = new FileReader(url.getPath()); BufferedReader in = new BufferedReader(fstream); StringBuilder buffer = new StringBuilder(); String str; while((str = in.readLine()) != null) { buffer.append(str); }
return JAXBUtil.read(buffer.toString().getBytes(), c);
macroadster/HMS
agent/src/main/java/org/apache/hms/agent/Agent.java
// Path: common/src/main/java/org/apache/hms/common/util/ExceptionUtil.java // public class ExceptionUtil { // public static String getStackTrace(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // }
import java.net.URL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hms.common.util.ExceptionUtil; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.xml.XmlConfiguration; import com.sun.jersey.spi.container.servlet.ServletContainer;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.agent; public class Agent { private static Log log = LogFactory.getLog(Agent.class); private static Agent instance = null; private Server server = null; private static URL serverConf = null; public static Agent getInstance() { if(instance==null) { instance = new Agent(); } return instance; } public void start() { try { System.out.close(); System.err.close(); instance = this; run(); } catch(Exception e) {
// Path: common/src/main/java/org/apache/hms/common/util/ExceptionUtil.java // public class ExceptionUtil { // public static String getStackTrace(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // } // Path: agent/src/main/java/org/apache/hms/agent/Agent.java import java.net.URL; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hms.common.util.ExceptionUtil; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.xml.XmlConfiguration; import com.sun.jersey.spi.container.servlet.ServletContainer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hms.agent; public class Agent { private static Log log = LogFactory.getLog(Agent.class); private static Agent instance = null; private Server server = null; private static URL serverConf = null; public static Agent getInstance() { if(instance==null) { instance = new Agent(); } return instance; } public void start() { try { System.out.close(); System.err.close(); instance = this; run(); } catch(Exception e) {
log.error(ExceptionUtil.getStackTrace(e));
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/AudioRecorder.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/exceptions/MediaRecorderException.java // public class MediaRecorderException extends Exception { // // public MediaRecorderException(String s) { // super(s); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/listeners/QBMediaRecordListener.java // public interface QBMediaRecordListener { // // void onMediaRecorded(File file); // // void onMediaRecordError(MediaRecorderException e); // // void onMediaRecordClosed(); // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/model/QBMediaRecorder.java // public abstract class QBMediaRecorder<T> { // // public abstract void startRecord(); // // public abstract void stopRecord(); // // public abstract void cancelRecord(); // }
import android.content.Context; import android.media.MediaRecorder; import android.util.Log; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.exceptions.MediaRecorderException; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.listeners.QBMediaRecordListener; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.model.QBMediaRecorder; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit;
package com.quickblox.ui.kit.chatmessage.adapter.media.recorder; /** * Created by roman on 7/26/17. */ public class AudioRecorder extends QBMediaRecorder<AudioRecorder> { private static final String TAG = AudioRecorder.class.getSimpleName();
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/exceptions/MediaRecorderException.java // public class MediaRecorderException extends Exception { // // public MediaRecorderException(String s) { // super(s); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/listeners/QBMediaRecordListener.java // public interface QBMediaRecordListener { // // void onMediaRecorded(File file); // // void onMediaRecordError(MediaRecorderException e); // // void onMediaRecordClosed(); // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/model/QBMediaRecorder.java // public abstract class QBMediaRecorder<T> { // // public abstract void startRecord(); // // public abstract void stopRecord(); // // public abstract void cancelRecord(); // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/AudioRecorder.java import android.content.Context; import android.media.MediaRecorder; import android.util.Log; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.exceptions.MediaRecorderException; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.listeners.QBMediaRecordListener; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.model.QBMediaRecorder; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; package com.quickblox.ui.kit.chatmessage.adapter.media.recorder; /** * Created by roman on 7/26/17. */ public class AudioRecorder extends QBMediaRecorder<AudioRecorder> { private static final String TAG = AudioRecorder.class.getSimpleName();
private QBMediaRecordListener recordListener;
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/AudioRecorder.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/exceptions/MediaRecorderException.java // public class MediaRecorderException extends Exception { // // public MediaRecorderException(String s) { // super(s); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/listeners/QBMediaRecordListener.java // public interface QBMediaRecordListener { // // void onMediaRecorded(File file); // // void onMediaRecordError(MediaRecorderException e); // // void onMediaRecordClosed(); // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/model/QBMediaRecorder.java // public abstract class QBMediaRecorder<T> { // // public abstract void startRecord(); // // public abstract void stopRecord(); // // public abstract void cancelRecord(); // }
import android.content.Context; import android.media.MediaRecorder; import android.util.Log; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.exceptions.MediaRecorderException; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.listeners.QBMediaRecordListener; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.model.QBMediaRecorder; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit;
if (recordListener != null) { recordListener.onMediaRecordClosed(); } } @Override public void stopRecord() { stopAndReleaseMediaRecorder(); sendResult(); } private void initMediaRecorder() { recorder = new MediaRecorder(); recorder.setAudioSource(configurationBuilder.audioSource); recorder.setOutputFormat(configurationBuilder.outputFormat); recorder.setOutputFile(configurationBuilder.filePath); recorder.setAudioChannels(configurationBuilder.channels); recorder.setAudioEncoder(configurationBuilder.audioEncoder); recorder.setAudioEncodingBitRate(configurationBuilder.bitRate); recorder.setAudioSamplingRate(configurationBuilder.samplingRate); recorder.setMaxDuration(configurationBuilder.duration); recorder.setOnInfoListener(new OnInfoListenerImpl()); recorder.setOnErrorListener(new OnErrorListenerImpl()); } private void prepareStartMediaRecorder() { try { recorder.prepare(); recorder.start(); } catch (IOException e) {
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/exceptions/MediaRecorderException.java // public class MediaRecorderException extends Exception { // // public MediaRecorderException(String s) { // super(s); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/listeners/QBMediaRecordListener.java // public interface QBMediaRecordListener { // // void onMediaRecorded(File file); // // void onMediaRecordError(MediaRecorderException e); // // void onMediaRecordClosed(); // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/model/QBMediaRecorder.java // public abstract class QBMediaRecorder<T> { // // public abstract void startRecord(); // // public abstract void stopRecord(); // // public abstract void cancelRecord(); // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/AudioRecorder.java import android.content.Context; import android.media.MediaRecorder; import android.util.Log; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.exceptions.MediaRecorderException; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.listeners.QBMediaRecordListener; import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.model.QBMediaRecorder; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; if (recordListener != null) { recordListener.onMediaRecordClosed(); } } @Override public void stopRecord() { stopAndReleaseMediaRecorder(); sendResult(); } private void initMediaRecorder() { recorder = new MediaRecorder(); recorder.setAudioSource(configurationBuilder.audioSource); recorder.setOutputFormat(configurationBuilder.outputFormat); recorder.setOutputFile(configurationBuilder.filePath); recorder.setAudioChannels(configurationBuilder.channels); recorder.setAudioEncoder(configurationBuilder.audioEncoder); recorder.setAudioEncodingBitRate(configurationBuilder.bitRate); recorder.setAudioSamplingRate(configurationBuilder.samplingRate); recorder.setMaxDuration(configurationBuilder.duration); recorder.setOnInfoListener(new OnInfoListenerImpl()); recorder.setOnErrorListener(new OnErrorListenerImpl()); } private void prepareStartMediaRecorder() { try { recorder.prepare(); recorder.start(); } catch (IOException e) {
notifyListenerError(new MediaRecorderException(e.getMessage()));
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/QBMessageTextClickMovement.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/listeners/QBChatMessageLinkClickListener.java // public interface QBChatMessageLinkClickListener { // // /** // * This method will be invoked when user press and hold // * finger on the {@link TextView} // * // * @param linkText Text which contains link on which user presses. // * @param linkType Type of the link can be one of {@link QBMessageTextClickMovement.QBLinkType} enumeration // * @param positionInAdapter Index of item with this TextView in message adapter // */ // void onLinkClicked(final String linkText, final QBMessageTextClickMovement.QBLinkType linkType, int positionInAdapter); // // /** // * @param text Whole text of {@link TextView} // * @param positionInAdapter Index of item with this TextView in message adapter // */ // void onLongClick(final String text, int positionInAdapter); // }
import android.content.Context; import android.text.Layout; import android.text.Spannable; import android.text.method.ArrowKeyMovementMethod; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.util.Patterns; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.TextView; import com.quickblox.core.helper.Lo; import com.quickblox.ui.kit.chatmessage.adapter.listeners.QBChatMessageLinkClickListener;
package com.quickblox.ui.kit.chatmessage.adapter.utils; //TODO VT maybe need move to package core for hide logic from users public class QBMessageTextClickMovement extends ArrowKeyMovementMethod { private final GestureDetector gestureDetector; private final boolean overrideOnLinkClick; private TextView textView; private Spannable buffer; private int positionInAdapter = -1;
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/listeners/QBChatMessageLinkClickListener.java // public interface QBChatMessageLinkClickListener { // // /** // * This method will be invoked when user press and hold // * finger on the {@link TextView} // * // * @param linkText Text which contains link on which user presses. // * @param linkType Type of the link can be one of {@link QBMessageTextClickMovement.QBLinkType} enumeration // * @param positionInAdapter Index of item with this TextView in message adapter // */ // void onLinkClicked(final String linkText, final QBMessageTextClickMovement.QBLinkType linkType, int positionInAdapter); // // /** // * @param text Whole text of {@link TextView} // * @param positionInAdapter Index of item with this TextView in message adapter // */ // void onLongClick(final String text, int positionInAdapter); // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/QBMessageTextClickMovement.java import android.content.Context; import android.text.Layout; import android.text.Spannable; import android.text.method.ArrowKeyMovementMethod; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.util.Patterns; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.TextView; import com.quickblox.core.helper.Lo; import com.quickblox.ui.kit.chatmessage.adapter.listeners.QBChatMessageLinkClickListener; package com.quickblox.ui.kit.chatmessage.adapter.utils; //TODO VT maybe need move to package core for hide logic from users public class QBMessageTextClickMovement extends ArrowKeyMovementMethod { private final GestureDetector gestureDetector; private final boolean overrideOnLinkClick; private TextView textView; private Spannable buffer; private int positionInAdapter = -1;
public QBMessageTextClickMovement(final QBChatMessageLinkClickListener listener, boolean overrideOnClick, final Context context) {
QuickBlox/ChatMessagesAdapter-android
sample-chat/src/main/java/com/quickblox/sample/chatadapter/App.java
// Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/utils/Consts.java // public interface Consts { // String APP_ID = "92"; // String AUTH_KEY = "wJHdOcQSxXQGWx5"; // String AUTH_SECRET = "BTFsj7Rtt27DAmT"; // String ACCOUNT_KEY = "rz2sXxBt5xgSxGjALDW6"; // // String userOneLogin = "firstuserfirstuser"; // String userTwoLogin = "seconduserseconduser"; // // String userPassword = "x6Bt0VDy5"; // // int userOneID = 16575824; // int userTwoID = 16575844; // }
import android.app.Application; import com.quickblox.auth.session.QBSettings; import com.quickblox.sample.chatadapter.utils.Consts;
package com.quickblox.sample.chatadapter; public class App extends Application { private static App instance; public static synchronized App getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this;
// Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/utils/Consts.java // public interface Consts { // String APP_ID = "92"; // String AUTH_KEY = "wJHdOcQSxXQGWx5"; // String AUTH_SECRET = "BTFsj7Rtt27DAmT"; // String ACCOUNT_KEY = "rz2sXxBt5xgSxGjALDW6"; // // String userOneLogin = "firstuserfirstuser"; // String userTwoLogin = "seconduserseconduser"; // // String userPassword = "x6Bt0VDy5"; // // int userOneID = 16575824; // int userTwoID = 16575844; // } // Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/App.java import android.app.Application; import com.quickblox.auth.session.QBSettings; import com.quickblox.sample.chatadapter.utils.Consts; package com.quickblox.sample.chatadapter; public class App extends Application { private static App instance; public static synchronized App getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this;
QBSettings.getInstance().init(getApplicationContext(), Consts.APP_ID, Consts.AUTH_KEY, Consts.AUTH_SECRET);
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/view/QBPlaybackControlView.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/AudioController.java // public class AudioController implements MediaController { // private SingleMediaManager mediaManager; // private EventMediaController eventMediaController; // // public AudioController(SingleMediaManager mediaManager, EventMediaController eventMediaController) { // this.mediaManager = mediaManager; // this.eventMediaController = eventMediaController; // } // // @Override // public void onPlayClicked(QBPlaybackControlView view, Uri uri) { // eventMediaController.onPlayerInViewInit(view); // mediaManager.playMedia(view, uri); // } // // @Override // public void onPauseClicked() { // mediaManager.pauseMedia(); // } // // @Override // public void onStopAnyPlayback() { // mediaManager.stopAnyPlayback(); // } // // @Override // public void onStartPosition() { // mediaManager.onStartPosition(); // } // // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // }
import android.content.Context; import android.net.Uri; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.ui.PlaybackControlView; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.AudioController; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl;
package com.quickblox.ui.kit.chatmessage.adapter.media.view; /** * Created by roman on 8/1/17. */ public class QBPlaybackControlView extends PlaybackControlView { private static String TAG = QBPlaybackControlView.class.getSimpleName(); private static final int[] STATE_SET_PLAY = {R.attr.state_play, -R.attr.state_pause}; private static final int[] STATE_SET_PAUSE = {-R.attr.state_play, R.attr.state_pause}; private final TextView durationView; private final TextView positionView; private final View playButton; private final View pauseButton; private final ImageView iconPlayPauseView; private final ComponentListener componentListener;
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/AudioController.java // public class AudioController implements MediaController { // private SingleMediaManager mediaManager; // private EventMediaController eventMediaController; // // public AudioController(SingleMediaManager mediaManager, EventMediaController eventMediaController) { // this.mediaManager = mediaManager; // this.eventMediaController = eventMediaController; // } // // @Override // public void onPlayClicked(QBPlaybackControlView view, Uri uri) { // eventMediaController.onPlayerInViewInit(view); // mediaManager.playMedia(view, uri); // } // // @Override // public void onPauseClicked() { // mediaManager.pauseMedia(); // } // // @Override // public void onStopAnyPlayback() { // mediaManager.stopAnyPlayback(); // } // // @Override // public void onStartPosition() { // mediaManager.onStartPosition(); // } // // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/view/QBPlaybackControlView.java import android.content.Context; import android.net.Uri; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.ui.PlaybackControlView; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.AudioController; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; package com.quickblox.ui.kit.chatmessage.adapter.media.view; /** * Created by roman on 8/1/17. */ public class QBPlaybackControlView extends PlaybackControlView { private static String TAG = QBPlaybackControlView.class.getSimpleName(); private static final int[] STATE_SET_PLAY = {R.attr.state_play, -R.attr.state_pause}; private static final int[] STATE_SET_PAUSE = {-R.attr.state_play, R.attr.state_pause}; private final TextView durationView; private final TextView positionView; private final View playButton; private final View pauseButton; private final ImageView iconPlayPauseView; private final ComponentListener componentListener;
private AudioController mediaController;
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/view/QBPlaybackControlView.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/AudioController.java // public class AudioController implements MediaController { // private SingleMediaManager mediaManager; // private EventMediaController eventMediaController; // // public AudioController(SingleMediaManager mediaManager, EventMediaController eventMediaController) { // this.mediaManager = mediaManager; // this.eventMediaController = eventMediaController; // } // // @Override // public void onPlayClicked(QBPlaybackControlView view, Uri uri) { // eventMediaController.onPlayerInViewInit(view); // mediaManager.playMedia(view, uri); // } // // @Override // public void onPauseClicked() { // mediaManager.pauseMedia(); // } // // @Override // public void onStopAnyPlayback() { // mediaManager.stopAnyPlayback(); // } // // @Override // public void onStartPosition() { // mediaManager.onStartPosition(); // } // // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // }
import android.content.Context; import android.net.Uri; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.ui.PlaybackControlView; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.AudioController; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl;
} public boolean isCurrentViewPlaying() { return getPlayer() != null; } public void updatePlayPauseIconView() { if (!isVisible() || iconPlayPauseView == null) { return; } boolean requestPlayPauseFocus; requestPlayPauseFocus = getPlayer() != null && getPlayer().getPlayWhenReady(); if(requestPlayPauseFocus){ setPauseStateIcon(); } else { setPlayStateIcon(); } } private void setPlayStateIcon() { iconPlayPauseView.setActivated(false); iconPlayPauseView.setImageState(STATE_SET_PLAY, true); } private void setPauseStateIcon() { iconPlayPauseView.setActivated(true); iconPlayPauseView.setImageState(STATE_SET_PAUSE, true); }
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/AudioController.java // public class AudioController implements MediaController { // private SingleMediaManager mediaManager; // private EventMediaController eventMediaController; // // public AudioController(SingleMediaManager mediaManager, EventMediaController eventMediaController) { // this.mediaManager = mediaManager; // this.eventMediaController = eventMediaController; // } // // @Override // public void onPlayClicked(QBPlaybackControlView view, Uri uri) { // eventMediaController.onPlayerInViewInit(view); // mediaManager.playMedia(view, uri); // } // // @Override // public void onPauseClicked() { // mediaManager.pauseMedia(); // } // // @Override // public void onStopAnyPlayback() { // mediaManager.stopAnyPlayback(); // } // // @Override // public void onStartPosition() { // mediaManager.onStartPosition(); // } // // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/view/QBPlaybackControlView.java import android.content.Context; import android.net.Uri; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.ui.PlaybackControlView; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.AudioController; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; } public boolean isCurrentViewPlaying() { return getPlayer() != null; } public void updatePlayPauseIconView() { if (!isVisible() || iconPlayPauseView == null) { return; } boolean requestPlayPauseFocus; requestPlayPauseFocus = getPlayer() != null && getPlayer().getPlayWhenReady(); if(requestPlayPauseFocus){ setPauseStateIcon(); } else { setPlayStateIcon(); } } private void setPlayStateIcon() { iconPlayPauseView.setActivated(false); iconPlayPauseView.setImageState(STATE_SET_PLAY, true); } private void setPauseStateIcon() { iconPlayPauseView.setActivated(true); iconPlayPauseView.setImageState(STATE_SET_PAUSE, true); }
private final class ComponentListener extends ExoPlayerEventListenerImpl implements View.OnClickListener {
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/QBLinkPreviewCashService.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/models/QBLinkPreview.java // public class QBLinkPreview implements Serializable{ // // @SerializedName("ogTitle") // private String title; // // @SerializedName("ogDescription") // private String description; // // @SerializedName("ogImage") // private QBLinkPreviewImage image; // // @SerializedName("ogLocale") // private String locale; // // @SerializedName("ogSiteName") // private String siteName; // // @SerializedName("ogUrl") // private String url; // // @SerializedName("ogType") // private String type; //possible "site", "website" // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public QBLinkPreviewImage getImage() { // return image; // } // // public void setImage(QBLinkPreviewImage image) { // this.image = image; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getSiteName() { // return siteName; // } // // public void setSiteName(String siteName) { // this.siteName = siteName; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override // public String toString() { // StringBuilder stringBuilder = new StringBuilder(QBLinkPreview.class.getSimpleName()); // stringBuilder.append("{").append("title").append("=").append(getTitle()). // append(", description").append("=").append(getDescription()). // append(", image").append("=").append(getImage()). // append(", locale").append("=").append(getLocale()). // append(", siteName").append("=").append(getSiteName()). // append(", url").append("=").append(getUrl()). // append(", type").append("=").append(getType()). // append("}"); // return stringBuilder.toString(); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/network/QBRestRequestExecutor.java // public class QBRestRequestExecutor { // // public static Performer<QBLinkPreview> getLinkPreview(String url, String token) { // return new QueryGetLinkPreview(url, token); // } // }
import android.os.Bundle; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.ui.kit.chatmessage.adapter.models.QBLinkPreview; import com.quickblox.ui.kit.chatmessage.adapter.utils.network.QBRestRequestExecutor; import java.util.HashMap; import java.util.Map;
package com.quickblox.ui.kit.chatmessage.adapter.utils; public class QBLinkPreviewCashService { private static QBLinkPreviewCashService INSTANCE;
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/models/QBLinkPreview.java // public class QBLinkPreview implements Serializable{ // // @SerializedName("ogTitle") // private String title; // // @SerializedName("ogDescription") // private String description; // // @SerializedName("ogImage") // private QBLinkPreviewImage image; // // @SerializedName("ogLocale") // private String locale; // // @SerializedName("ogSiteName") // private String siteName; // // @SerializedName("ogUrl") // private String url; // // @SerializedName("ogType") // private String type; //possible "site", "website" // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public QBLinkPreviewImage getImage() { // return image; // } // // public void setImage(QBLinkPreviewImage image) { // this.image = image; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getSiteName() { // return siteName; // } // // public void setSiteName(String siteName) { // this.siteName = siteName; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override // public String toString() { // StringBuilder stringBuilder = new StringBuilder(QBLinkPreview.class.getSimpleName()); // stringBuilder.append("{").append("title").append("=").append(getTitle()). // append(", description").append("=").append(getDescription()). // append(", image").append("=").append(getImage()). // append(", locale").append("=").append(getLocale()). // append(", siteName").append("=").append(getSiteName()). // append(", url").append("=").append(getUrl()). // append(", type").append("=").append(getType()). // append("}"); // return stringBuilder.toString(); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/network/QBRestRequestExecutor.java // public class QBRestRequestExecutor { // // public static Performer<QBLinkPreview> getLinkPreview(String url, String token) { // return new QueryGetLinkPreview(url, token); // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/QBLinkPreviewCashService.java import android.os.Bundle; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.ui.kit.chatmessage.adapter.models.QBLinkPreview; import com.quickblox.ui.kit.chatmessage.adapter.utils.network.QBRestRequestExecutor; import java.util.HashMap; import java.util.Map; package com.quickblox.ui.kit.chatmessage.adapter.utils; public class QBLinkPreviewCashService { private static QBLinkPreviewCashService INSTANCE;
private Map<String, QBLinkPreview> linkPreviewsHolder = new HashMap<>();
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/QBLinkPreviewCashService.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/models/QBLinkPreview.java // public class QBLinkPreview implements Serializable{ // // @SerializedName("ogTitle") // private String title; // // @SerializedName("ogDescription") // private String description; // // @SerializedName("ogImage") // private QBLinkPreviewImage image; // // @SerializedName("ogLocale") // private String locale; // // @SerializedName("ogSiteName") // private String siteName; // // @SerializedName("ogUrl") // private String url; // // @SerializedName("ogType") // private String type; //possible "site", "website" // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public QBLinkPreviewImage getImage() { // return image; // } // // public void setImage(QBLinkPreviewImage image) { // this.image = image; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getSiteName() { // return siteName; // } // // public void setSiteName(String siteName) { // this.siteName = siteName; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override // public String toString() { // StringBuilder stringBuilder = new StringBuilder(QBLinkPreview.class.getSimpleName()); // stringBuilder.append("{").append("title").append("=").append(getTitle()). // append(", description").append("=").append(getDescription()). // append(", image").append("=").append(getImage()). // append(", locale").append("=").append(getLocale()). // append(", siteName").append("=").append(getSiteName()). // append(", url").append("=").append(getUrl()). // append(", type").append("=").append(getType()). // append("}"); // return stringBuilder.toString(); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/network/QBRestRequestExecutor.java // public class QBRestRequestExecutor { // // public static Performer<QBLinkPreview> getLinkPreview(String url, String token) { // return new QueryGetLinkPreview(url, token); // } // }
import android.os.Bundle; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.ui.kit.chatmessage.adapter.models.QBLinkPreview; import com.quickblox.ui.kit.chatmessage.adapter.utils.network.QBRestRequestExecutor; import java.util.HashMap; import java.util.Map;
package com.quickblox.ui.kit.chatmessage.adapter.utils; public class QBLinkPreviewCashService { private static QBLinkPreviewCashService INSTANCE; private Map<String, QBLinkPreview> linkPreviewsHolder = new HashMap<>(); private QBLinkPreviewCashService() { } public static QBLinkPreviewCashService getInstance(){ if (INSTANCE == null){ INSTANCE = new QBLinkPreviewCashService(); } return INSTANCE; } public void getLinkPreview(final String url, String token, boolean forceLoad, final QBEntityCallback<QBLinkPreview> callback) { if (!forceLoad) { QBLinkPreview linkPreview = linkPreviewsHolder.get(url); if (linkPreview != null && callback != null){ callback.onSuccess(linkPreview, new Bundle()); } else { getLinkPreview(url, token, true, callback); } return; }
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/models/QBLinkPreview.java // public class QBLinkPreview implements Serializable{ // // @SerializedName("ogTitle") // private String title; // // @SerializedName("ogDescription") // private String description; // // @SerializedName("ogImage") // private QBLinkPreviewImage image; // // @SerializedName("ogLocale") // private String locale; // // @SerializedName("ogSiteName") // private String siteName; // // @SerializedName("ogUrl") // private String url; // // @SerializedName("ogType") // private String type; //possible "site", "website" // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public QBLinkPreviewImage getImage() { // return image; // } // // public void setImage(QBLinkPreviewImage image) { // this.image = image; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getSiteName() { // return siteName; // } // // public void setSiteName(String siteName) { // this.siteName = siteName; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override // public String toString() { // StringBuilder stringBuilder = new StringBuilder(QBLinkPreview.class.getSimpleName()); // stringBuilder.append("{").append("title").append("=").append(getTitle()). // append(", description").append("=").append(getDescription()). // append(", image").append("=").append(getImage()). // append(", locale").append("=").append(getLocale()). // append(", siteName").append("=").append(getSiteName()). // append(", url").append("=").append(getUrl()). // append(", type").append("=").append(getType()). // append("}"); // return stringBuilder.toString(); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/network/QBRestRequestExecutor.java // public class QBRestRequestExecutor { // // public static Performer<QBLinkPreview> getLinkPreview(String url, String token) { // return new QueryGetLinkPreview(url, token); // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/utils/QBLinkPreviewCashService.java import android.os.Bundle; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.ui.kit.chatmessage.adapter.models.QBLinkPreview; import com.quickblox.ui.kit.chatmessage.adapter.utils.network.QBRestRequestExecutor; import java.util.HashMap; import java.util.Map; package com.quickblox.ui.kit.chatmessage.adapter.utils; public class QBLinkPreviewCashService { private static QBLinkPreviewCashService INSTANCE; private Map<String, QBLinkPreview> linkPreviewsHolder = new HashMap<>(); private QBLinkPreviewCashService() { } public static QBLinkPreviewCashService getInstance(){ if (INSTANCE == null){ INSTANCE = new QBLinkPreviewCashService(); } return INSTANCE; } public void getLinkPreview(final String url, String token, boolean forceLoad, final QBEntityCallback<QBLinkPreview> callback) { if (!forceLoad) { QBLinkPreview linkPreview = linkPreviewsHolder.get(url); if (linkPreview != null && callback != null){ callback.onSuccess(linkPreview, new Bundle()); } else { getLinkPreview(url, token, true, callback); } return; }
QBRestRequestExecutor.getLinkPreview(url, token).performAsync(new QBEntityCallback<QBLinkPreview>() {
QuickBlox/ChatMessagesAdapter-android
sample-chat/src/main/java/com/quickblox/sample/chatadapter/ui/activity/SplashActivity.java
// Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/utils/ChatHelper.java // public class ChatHelper { // private static final String TAG = ChatHelper.class.getSimpleName(); // // private static final int CHAT_SOCKET_TIMEOUT = 0; // // private static final int CHAT_HISTORY_ITEMS_PER_PAGE = 100; // private static final String CHAT_HISTORY_ITEMS_SORT_FIELD = "date_sent"; // // private static ChatHelper instance; // // private QBChatService qbChatService; // // public static synchronized ChatHelper getInstance() { // if (instance == null) { // QBSettings.getInstance().setLogLevel(LogLevel.DEBUG); // QBChatService.setDebugEnabled(true); // QBChatService.setConfigurationBuilder(buildChatConfigs()); // QBChatService.setDefaultPacketReplyTimeout(20 * 1000); // instance = new ChatHelper(); // } // return instance; // } // // private ChatHelper() { // qbChatService = QBChatService.getInstance(); // } // // private static QBChatService.ConfigurationBuilder buildChatConfigs() { // QBChatService.ConfigurationBuilder configurationBuilder = new QBChatService.ConfigurationBuilder(); // configurationBuilder.setKeepAlive(true) // .setSocketTimeout(CHAT_SOCKET_TIMEOUT) // .setAutojoinEnabled(false); // // return configurationBuilder; // } // // public void loginAndGetUsers(final QBUser user, final QBEntityCallback<ArrayList<QBUser>> callback) { // Performer<QBSession> performer = QBAuth.createSession(user); // final Observable<QBSession> observableSession = performer.convertTo(RxJavaPerformProcessor.INSTANCE); // // Observable<Void> observableLoginToChat = Observable.fromCallable(new Callable<Void>() { // @Override // public Void call() throws Exception { // QBChatService.getInstance().login(user); // return null; // } // }); // // performMultiRequest(observableSession, observableLoginToChat, callback); // } // // private void performMultiRequest(Observable<QBSession> session, Observable<Void> loginToChat, final QBEntityCallback<ArrayList<QBUser>> callback) { // final ArrayList<Integer> usersIds = new ArrayList<>(); // usersIds.add(Consts.userOneID); // usersIds.add(Consts.userTwoID); // // Observable.zip( // loginToChat.subscribeOn(Schedulers.io()), // session.flatMap(new Func1<QBSession, Observable<ArrayList<QBUser>>>() { // @Override // public Observable<ArrayList<QBUser>> call(QBSession qbSession) { // return QBUsers.getUsersByIDs(usersIds, null).convertTo(RxJavaPerformProcessor.INSTANCE); // } // }) // .subscribeOn(Schedulers.io()), // mergeResult() // ) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Observer<ArrayList<QBUser>>() { // @Override // public void onCompleted() { // } // // @Override // public void onError(Throwable e) { // Log.d(TAG, "onError " + e); // } // // @Override // public void onNext(ArrayList<QBUser> qbUsers) { // Log.d(TAG, "onNext" + qbUsers); // callback.onSuccess(qbUsers, Bundle.EMPTY); // } // }); // } // // private Func2<Void, ArrayList<QBUser>, ArrayList<QBUser>> mergeResult() { // return new Func2<Void, ArrayList<QBUser>, ArrayList<QBUser>>() { // @Override // public ArrayList<QBUser> call(Void aVoid, ArrayList<QBUser> qbUsers) { // return qbUsers; // } // }; // } // // public void loadChatHistory(QBChatDialog dialog, int skipPagination, // final QBEntityCallback<ArrayList<QBChatMessage>> callback) { // QBRequestGetBuilder customObjectRequestBuilder = new QBRequestGetBuilder(); // customObjectRequestBuilder.setSkip(skipPagination); // customObjectRequestBuilder.setLimit(CHAT_HISTORY_ITEMS_PER_PAGE); // customObjectRequestBuilder.sortDesc(CHAT_HISTORY_ITEMS_SORT_FIELD); // // QBRestChatService.getDialogMessages(dialog, customObjectRequestBuilder).performAsync( // new QBEntityCallback<ArrayList<QBChatMessage>>() { // @Override // public void onSuccess(ArrayList<QBChatMessage> qbChatMessages, Bundle bundle) { // callback.onSuccess(qbChatMessages, bundle); // } // // @Override // public void onError(QBResponseException e) { // callback.onError(e); // } // }); // } // // public void logout() { // qbChatService.destroy(); // } // } // // Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/utils/Consts.java // public interface Consts { // String APP_ID = "92"; // String AUTH_KEY = "wJHdOcQSxXQGWx5"; // String AUTH_SECRET = "BTFsj7Rtt27DAmT"; // String ACCOUNT_KEY = "rz2sXxBt5xgSxGjALDW6"; // // String userOneLogin = "firstuserfirstuser"; // String userTwoLogin = "seconduserseconduser"; // // String userPassword = "x6Bt0VDy5"; // // int userOneID = 16575824; // int userTwoID = 16575844; // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.sample.chatadapter.R; import com.quickblox.sample.chatadapter.utils.ChatHelper; import com.quickblox.sample.chatadapter.utils.Consts; import com.quickblox.users.model.QBUser; import java.util.ArrayList;
package com.quickblox.sample.chatadapter.ui.activity; public class SplashActivity extends AppCompatActivity { private static final String TAG = SplashActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); loginToQB(); } private void loginToQB() {
// Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/utils/ChatHelper.java // public class ChatHelper { // private static final String TAG = ChatHelper.class.getSimpleName(); // // private static final int CHAT_SOCKET_TIMEOUT = 0; // // private static final int CHAT_HISTORY_ITEMS_PER_PAGE = 100; // private static final String CHAT_HISTORY_ITEMS_SORT_FIELD = "date_sent"; // // private static ChatHelper instance; // // private QBChatService qbChatService; // // public static synchronized ChatHelper getInstance() { // if (instance == null) { // QBSettings.getInstance().setLogLevel(LogLevel.DEBUG); // QBChatService.setDebugEnabled(true); // QBChatService.setConfigurationBuilder(buildChatConfigs()); // QBChatService.setDefaultPacketReplyTimeout(20 * 1000); // instance = new ChatHelper(); // } // return instance; // } // // private ChatHelper() { // qbChatService = QBChatService.getInstance(); // } // // private static QBChatService.ConfigurationBuilder buildChatConfigs() { // QBChatService.ConfigurationBuilder configurationBuilder = new QBChatService.ConfigurationBuilder(); // configurationBuilder.setKeepAlive(true) // .setSocketTimeout(CHAT_SOCKET_TIMEOUT) // .setAutojoinEnabled(false); // // return configurationBuilder; // } // // public void loginAndGetUsers(final QBUser user, final QBEntityCallback<ArrayList<QBUser>> callback) { // Performer<QBSession> performer = QBAuth.createSession(user); // final Observable<QBSession> observableSession = performer.convertTo(RxJavaPerformProcessor.INSTANCE); // // Observable<Void> observableLoginToChat = Observable.fromCallable(new Callable<Void>() { // @Override // public Void call() throws Exception { // QBChatService.getInstance().login(user); // return null; // } // }); // // performMultiRequest(observableSession, observableLoginToChat, callback); // } // // private void performMultiRequest(Observable<QBSession> session, Observable<Void> loginToChat, final QBEntityCallback<ArrayList<QBUser>> callback) { // final ArrayList<Integer> usersIds = new ArrayList<>(); // usersIds.add(Consts.userOneID); // usersIds.add(Consts.userTwoID); // // Observable.zip( // loginToChat.subscribeOn(Schedulers.io()), // session.flatMap(new Func1<QBSession, Observable<ArrayList<QBUser>>>() { // @Override // public Observable<ArrayList<QBUser>> call(QBSession qbSession) { // return QBUsers.getUsersByIDs(usersIds, null).convertTo(RxJavaPerformProcessor.INSTANCE); // } // }) // .subscribeOn(Schedulers.io()), // mergeResult() // ) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Observer<ArrayList<QBUser>>() { // @Override // public void onCompleted() { // } // // @Override // public void onError(Throwable e) { // Log.d(TAG, "onError " + e); // } // // @Override // public void onNext(ArrayList<QBUser> qbUsers) { // Log.d(TAG, "onNext" + qbUsers); // callback.onSuccess(qbUsers, Bundle.EMPTY); // } // }); // } // // private Func2<Void, ArrayList<QBUser>, ArrayList<QBUser>> mergeResult() { // return new Func2<Void, ArrayList<QBUser>, ArrayList<QBUser>>() { // @Override // public ArrayList<QBUser> call(Void aVoid, ArrayList<QBUser> qbUsers) { // return qbUsers; // } // }; // } // // public void loadChatHistory(QBChatDialog dialog, int skipPagination, // final QBEntityCallback<ArrayList<QBChatMessage>> callback) { // QBRequestGetBuilder customObjectRequestBuilder = new QBRequestGetBuilder(); // customObjectRequestBuilder.setSkip(skipPagination); // customObjectRequestBuilder.setLimit(CHAT_HISTORY_ITEMS_PER_PAGE); // customObjectRequestBuilder.sortDesc(CHAT_HISTORY_ITEMS_SORT_FIELD); // // QBRestChatService.getDialogMessages(dialog, customObjectRequestBuilder).performAsync( // new QBEntityCallback<ArrayList<QBChatMessage>>() { // @Override // public void onSuccess(ArrayList<QBChatMessage> qbChatMessages, Bundle bundle) { // callback.onSuccess(qbChatMessages, bundle); // } // // @Override // public void onError(QBResponseException e) { // callback.onError(e); // } // }); // } // // public void logout() { // qbChatService.destroy(); // } // } // // Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/utils/Consts.java // public interface Consts { // String APP_ID = "92"; // String AUTH_KEY = "wJHdOcQSxXQGWx5"; // String AUTH_SECRET = "BTFsj7Rtt27DAmT"; // String ACCOUNT_KEY = "rz2sXxBt5xgSxGjALDW6"; // // String userOneLogin = "firstuserfirstuser"; // String userTwoLogin = "seconduserseconduser"; // // String userPassword = "x6Bt0VDy5"; // // int userOneID = 16575824; // int userTwoID = 16575844; // } // Path: sample-chat/src/main/java/com/quickblox/sample/chatadapter/ui/activity/SplashActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.quickblox.core.QBEntityCallback; import com.quickblox.core.exception.QBResponseException; import com.quickblox.sample.chatadapter.R; import com.quickblox.sample.chatadapter.utils.ChatHelper; import com.quickblox.sample.chatadapter.utils.Consts; import com.quickblox.users.model.QBUser; import java.util.ArrayList; package com.quickblox.sample.chatadapter.ui.activity; public class SplashActivity extends AppCompatActivity { private static final String TAG = SplashActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); loginToQB(); } private void loginToQB() {
QBUser qbUser = new QBUser(Consts.userTwoLogin, Consts.userPassword);
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/listeners/QBMediaRecordListener.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/exceptions/MediaRecorderException.java // public class MediaRecorderException extends Exception { // // public MediaRecorderException(String s) { // super(s); // } // }
import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.exceptions.MediaRecorderException; import java.io.File;
package com.quickblox.ui.kit.chatmessage.adapter.media.recorder.listeners; /** * Created by roman on 7/26/17. */ public interface QBMediaRecordListener { void onMediaRecorded(File file);
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/exceptions/MediaRecorderException.java // public class MediaRecorderException extends Exception { // // public MediaRecorderException(String s) { // super(s); // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/recorder/listeners/QBMediaRecordListener.java import com.quickblox.ui.kit.chatmessage.adapter.media.recorder.exceptions.MediaRecorderException; import java.io.File; package com.quickblox.ui.kit.chatmessage.adapter.media.recorder.listeners; /** * Created by roman on 7/26/17. */ public interface QBMediaRecordListener { void onMediaRecorded(File file);
void onMediaRecordError(MediaRecorderException e);
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/video/ui/VideoPlayerActivity.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/SimpleExoPlayerInitializer.java // public class SimpleExoPlayerInitializer { // // public static SimpleExoPlayer initializeExoPlayer(Context context) { // return ExoPlayerFactory.newSimpleInstance( // new DefaultRenderersFactory(context), // new DefaultTrackSelector(), new DefaultLoadControl()); // } // // public static MediaSource buildMediaSource(Uri uri, Context context) { // String userAgent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name)); // return new ExtractorMediaSource(uri, // new DefaultHttpDataSourceFactory(userAgent), // new DefaultExtractorsFactory(), null, null); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/VideoRendererEventListenerImpl.java // public class VideoRendererEventListenerImpl implements VideoRendererEventListener { // @Override // public void onVideoEnabled(DecoderCounters counters) { // // } // // @Override // public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { // // } // // @Override // public void onVideoInputFormatChanged(Format format) { // // } // // @Override // public void onDroppedFrames(int count, long elapsedMs) { // // } // // @Override // public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { // // } // // @Override // public void onRenderedFirstFrame(Surface surface) { // // } // // @Override // public void onVideoDisabled(DecoderCounters counters) { // // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.view.TextureView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.util.Util; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.SimpleExoPlayerInitializer; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.VideoRendererEventListenerImpl;
public void onPause() { super.onPause(); if (Util.SDK_INT <= 23) { releasePlayer(); } } @Override public void onStop() { super.onStop(); if (Util.SDK_INT > 23) { releasePlayer(); } } private void setScreenOrientationPortrait() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } private void initViews() { simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view); textureView = (TextureView) simpleExoPlayerView.getVideoSurfaceView(); } private void initFields() { videoUri = getIntent().getParcelableExtra(EXTRA_VIDEO_URI); shouldAutoPlay = true; } private void initializePlayer() {
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/SimpleExoPlayerInitializer.java // public class SimpleExoPlayerInitializer { // // public static SimpleExoPlayer initializeExoPlayer(Context context) { // return ExoPlayerFactory.newSimpleInstance( // new DefaultRenderersFactory(context), // new DefaultTrackSelector(), new DefaultLoadControl()); // } // // public static MediaSource buildMediaSource(Uri uri, Context context) { // String userAgent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name)); // return new ExtractorMediaSource(uri, // new DefaultHttpDataSourceFactory(userAgent), // new DefaultExtractorsFactory(), null, null); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/VideoRendererEventListenerImpl.java // public class VideoRendererEventListenerImpl implements VideoRendererEventListener { // @Override // public void onVideoEnabled(DecoderCounters counters) { // // } // // @Override // public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { // // } // // @Override // public void onVideoInputFormatChanged(Format format) { // // } // // @Override // public void onDroppedFrames(int count, long elapsedMs) { // // } // // @Override // public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { // // } // // @Override // public void onRenderedFirstFrame(Surface surface) { // // } // // @Override // public void onVideoDisabled(DecoderCounters counters) { // // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/video/ui/VideoPlayerActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.view.TextureView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.util.Util; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.SimpleExoPlayerInitializer; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.VideoRendererEventListenerImpl; public void onPause() { super.onPause(); if (Util.SDK_INT <= 23) { releasePlayer(); } } @Override public void onStop() { super.onStop(); if (Util.SDK_INT > 23) { releasePlayer(); } } private void setScreenOrientationPortrait() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } private void initViews() { simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view); textureView = (TextureView) simpleExoPlayerView.getVideoSurfaceView(); } private void initFields() { videoUri = getIntent().getParcelableExtra(EXTRA_VIDEO_URI); shouldAutoPlay = true; } private void initializePlayer() {
player = SimpleExoPlayerInitializer.initializeExoPlayer(this);
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/video/ui/VideoPlayerActivity.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/SimpleExoPlayerInitializer.java // public class SimpleExoPlayerInitializer { // // public static SimpleExoPlayer initializeExoPlayer(Context context) { // return ExoPlayerFactory.newSimpleInstance( // new DefaultRenderersFactory(context), // new DefaultTrackSelector(), new DefaultLoadControl()); // } // // public static MediaSource buildMediaSource(Uri uri, Context context) { // String userAgent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name)); // return new ExtractorMediaSource(uri, // new DefaultHttpDataSourceFactory(userAgent), // new DefaultExtractorsFactory(), null, null); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/VideoRendererEventListenerImpl.java // public class VideoRendererEventListenerImpl implements VideoRendererEventListener { // @Override // public void onVideoEnabled(DecoderCounters counters) { // // } // // @Override // public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { // // } // // @Override // public void onVideoInputFormatChanged(Format format) { // // } // // @Override // public void onDroppedFrames(int count, long elapsedMs) { // // } // // @Override // public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { // // } // // @Override // public void onRenderedFirstFrame(Surface surface) { // // } // // @Override // public void onVideoDisabled(DecoderCounters counters) { // // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.view.TextureView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.util.Util; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.SimpleExoPlayerInitializer; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.VideoRendererEventListenerImpl;
player.setVideoDebugListener(new VideoListener()); simpleExoPlayerView.setPlayer(player); player.setPlayWhenReady(shouldAutoPlay); boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(SimpleExoPlayerInitializer.buildMediaSource(videoUri, this)); } private void releasePlayer() { if (player != null) { shouldAutoPlay = player.getPlayWhenReady(); updateResumePosition(); player.release(); player = null; } } private void updateResumePosition() { resumeWindow = player.getCurrentWindowIndex(); resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition()) : C.TIME_UNSET; } private void setPlayerToStartPosition() { player.seekTo(0); player.setPlayWhenReady(false); }
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/SimpleExoPlayerInitializer.java // public class SimpleExoPlayerInitializer { // // public static SimpleExoPlayer initializeExoPlayer(Context context) { // return ExoPlayerFactory.newSimpleInstance( // new DefaultRenderersFactory(context), // new DefaultTrackSelector(), new DefaultLoadControl()); // } // // public static MediaSource buildMediaSource(Uri uri, Context context) { // String userAgent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name)); // return new ExtractorMediaSource(uri, // new DefaultHttpDataSourceFactory(userAgent), // new DefaultExtractorsFactory(), null, null); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/VideoRendererEventListenerImpl.java // public class VideoRendererEventListenerImpl implements VideoRendererEventListener { // @Override // public void onVideoEnabled(DecoderCounters counters) { // // } // // @Override // public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { // // } // // @Override // public void onVideoInputFormatChanged(Format format) { // // } // // @Override // public void onDroppedFrames(int count, long elapsedMs) { // // } // // @Override // public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { // // } // // @Override // public void onRenderedFirstFrame(Surface surface) { // // } // // @Override // public void onVideoDisabled(DecoderCounters counters) { // // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/video/ui/VideoPlayerActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.view.TextureView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.util.Util; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.SimpleExoPlayerInitializer; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.VideoRendererEventListenerImpl; player.setVideoDebugListener(new VideoListener()); simpleExoPlayerView.setPlayer(player); player.setPlayWhenReady(shouldAutoPlay); boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(SimpleExoPlayerInitializer.buildMediaSource(videoUri, this)); } private void releasePlayer() { if (player != null) { shouldAutoPlay = player.getPlayWhenReady(); updateResumePosition(); player.release(); player = null; } } private void updateResumePosition() { resumeWindow = player.getCurrentWindowIndex(); resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition()) : C.TIME_UNSET; } private void setPlayerToStartPosition() { player.seekTo(0); player.setPlayWhenReady(false); }
private class PlayerStateListener extends ExoPlayerEventListenerImpl {
QuickBlox/ChatMessagesAdapter-android
chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/video/ui/VideoPlayerActivity.java
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/SimpleExoPlayerInitializer.java // public class SimpleExoPlayerInitializer { // // public static SimpleExoPlayer initializeExoPlayer(Context context) { // return ExoPlayerFactory.newSimpleInstance( // new DefaultRenderersFactory(context), // new DefaultTrackSelector(), new DefaultLoadControl()); // } // // public static MediaSource buildMediaSource(Uri uri, Context context) { // String userAgent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name)); // return new ExtractorMediaSource(uri, // new DefaultHttpDataSourceFactory(userAgent), // new DefaultExtractorsFactory(), null, null); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/VideoRendererEventListenerImpl.java // public class VideoRendererEventListenerImpl implements VideoRendererEventListener { // @Override // public void onVideoEnabled(DecoderCounters counters) { // // } // // @Override // public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { // // } // // @Override // public void onVideoInputFormatChanged(Format format) { // // } // // @Override // public void onDroppedFrames(int count, long elapsedMs) { // // } // // @Override // public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { // // } // // @Override // public void onRenderedFirstFrame(Surface surface) { // // } // // @Override // public void onVideoDisabled(DecoderCounters counters) { // // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.view.TextureView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.util.Util; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.SimpleExoPlayerInitializer; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.VideoRendererEventListenerImpl;
private void releasePlayer() { if (player != null) { shouldAutoPlay = player.getPlayWhenReady(); updateResumePosition(); player.release(); player = null; } } private void updateResumePosition() { resumeWindow = player.getCurrentWindowIndex(); resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition()) : C.TIME_UNSET; } private void setPlayerToStartPosition() { player.seekTo(0); player.setPlayWhenReady(false); } private class PlayerStateListener extends ExoPlayerEventListenerImpl { @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { if (playbackState == Player.STATE_ENDED) { setPlayerToStartPosition(); } } }
// Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/ExoPlayerEventListenerImpl.java // public class ExoPlayerEventListenerImpl implements Player.EventListener { // @Override // public void onTimelineChanged(Timeline timeline, Object manifest) { // // } // // @Override // public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // // } // // @Override // public void onLoadingChanged(boolean isLoading) { // // } // // @Override // public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // // } // // @Override // public void onRepeatModeChanged(int repeatMode) { // // } // // @Override // public void onPlayerError(ExoPlaybackException error) { // // } // // @Override // public void onPositionDiscontinuity() { // // } // // @Override // public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { // // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/SimpleExoPlayerInitializer.java // public class SimpleExoPlayerInitializer { // // public static SimpleExoPlayer initializeExoPlayer(Context context) { // return ExoPlayerFactory.newSimpleInstance( // new DefaultRenderersFactory(context), // new DefaultTrackSelector(), new DefaultLoadControl()); // } // // public static MediaSource buildMediaSource(Uri uri, Context context) { // String userAgent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name)); // return new ExtractorMediaSource(uri, // new DefaultHttpDataSourceFactory(userAgent), // new DefaultExtractorsFactory(), null, null); // } // } // // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/utils/VideoRendererEventListenerImpl.java // public class VideoRendererEventListenerImpl implements VideoRendererEventListener { // @Override // public void onVideoEnabled(DecoderCounters counters) { // // } // // @Override // public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) { // // } // // @Override // public void onVideoInputFormatChanged(Format format) { // // } // // @Override // public void onDroppedFrames(int count, long elapsedMs) { // // } // // @Override // public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { // // } // // @Override // public void onRenderedFirstFrame(Surface surface) { // // } // // @Override // public void onVideoDisabled(DecoderCounters counters) { // // } // } // Path: chat-message-adapter/src/main/java/com/quickblox/ui/kit/chatmessage/adapter/media/video/ui/VideoPlayerActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Matrix; import android.net.Uri; import android.os.Bundle; import android.view.TextureView; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; import com.google.android.exoplayer2.util.Util; import com.quickblox.ui.kit.chatmessage.adapter.R; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.ExoPlayerEventListenerImpl; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.SimpleExoPlayerInitializer; import com.quickblox.ui.kit.chatmessage.adapter.media.utils.VideoRendererEventListenerImpl; private void releasePlayer() { if (player != null) { shouldAutoPlay = player.getPlayWhenReady(); updateResumePosition(); player.release(); player = null; } } private void updateResumePosition() { resumeWindow = player.getCurrentWindowIndex(); resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition()) : C.TIME_UNSET; } private void setPlayerToStartPosition() { player.seekTo(0); player.setPlayWhenReady(false); } private class PlayerStateListener extends ExoPlayerEventListenerImpl { @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { if (playbackState == Player.STATE_ENDED) { setPlayerToStartPosition(); } } }
private class VideoListener extends VideoRendererEventListenerImpl {
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/data/source/local/DbHelper.java
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/DbContract.java // public class DbContract { // public static final String SCHEME ="content://"; // public static final String AUTHORITY = "com.chernandezgil.farmacias"; // public static final Uri BASE_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY); // public static final String PATH_FARMACIAS="farmacias"; // public static final String PATH_QUICK_SEARCH ="quick_search"; // public static final String PATH_FAVORITES= "favorites"; // // public static final class FarmaciasEntity implements BaseColumns { // // public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FARMACIAS).build(); // public static final Uri CONTENT_URI_QUICK_SEARCH =BASE_CONTENT_URI.buildUpon().appendPath(PATH_QUICK_SEARCH).build(); // public static final Uri CONTENT_URI_PATH_FAVORITES =BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVORITES).build(); // // public static final String CONTENT_TYPE = // "vnd.android.cursor.dir/" + AUTHORITY + "/" + PATH_FARMACIAS; // public static final String CONTENT_ITEM_TYPE = // "vnd.android.cursor.item/" + AUTHORITY + "/" + PATH_FARMACIAS; // // public static final String TABLE_NAME="farmacias"; // public static final String NAME="name"; // public static final String ADDRESS="address"; // public static final String LOCALITY="locality"; // public static final String PROVINCE="province"; // public static final String POSTAL_CODE="postal_code"; // public static final String PHONE="phone"; // public static final String LAT="lat"; // public static final String LON="lon"; // public static final String HOURS="hours"; // public static final String FAVORITE="favorite"; // // public static Uri buildFarmaciasUriByPhone(long id){ // // return ContentUris.withAppendedId(CONTENT_URI,id); // } // public static Uri buildFarmaciasUriByPhone(String phone) { // return CONTENT_URI.buildUpon().appendPath(phone).build(); // } // // public static Uri buildFarmaciasUriByName(String name) { // // return CONTENT_URI.buildUpon().appendPath(name).build(); // // } // public static Uri buildFarmaciasUriByNameQuickSearch(String name) { // return CONTENT_URI_QUICK_SEARCH.buildUpon().appendPath(name).build(); // } // public static Uri buildFavoritesUriByPhone(String phone) { // return CONTENT_URI_PATH_FAVORITES.buildUpon().appendPath(phone).build(); // } // // } // // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.chernandezgil.farmacias.data.source.local.DbContract;
package com.chernandezgil.farmacias.data.source.local; /** * Created by Carlos on 09/07/2016. */ public class DbHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "farmacias.db"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) {
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/DbContract.java // public class DbContract { // public static final String SCHEME ="content://"; // public static final String AUTHORITY = "com.chernandezgil.farmacias"; // public static final Uri BASE_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY); // public static final String PATH_FARMACIAS="farmacias"; // public static final String PATH_QUICK_SEARCH ="quick_search"; // public static final String PATH_FAVORITES= "favorites"; // // public static final class FarmaciasEntity implements BaseColumns { // // public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FARMACIAS).build(); // public static final Uri CONTENT_URI_QUICK_SEARCH =BASE_CONTENT_URI.buildUpon().appendPath(PATH_QUICK_SEARCH).build(); // public static final Uri CONTENT_URI_PATH_FAVORITES =BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVORITES).build(); // // public static final String CONTENT_TYPE = // "vnd.android.cursor.dir/" + AUTHORITY + "/" + PATH_FARMACIAS; // public static final String CONTENT_ITEM_TYPE = // "vnd.android.cursor.item/" + AUTHORITY + "/" + PATH_FARMACIAS; // // public static final String TABLE_NAME="farmacias"; // public static final String NAME="name"; // public static final String ADDRESS="address"; // public static final String LOCALITY="locality"; // public static final String PROVINCE="province"; // public static final String POSTAL_CODE="postal_code"; // public static final String PHONE="phone"; // public static final String LAT="lat"; // public static final String LON="lon"; // public static final String HOURS="hours"; // public static final String FAVORITE="favorite"; // // public static Uri buildFarmaciasUriByPhone(long id){ // // return ContentUris.withAppendedId(CONTENT_URI,id); // } // public static Uri buildFarmaciasUriByPhone(String phone) { // return CONTENT_URI.buildUpon().appendPath(phone).build(); // } // // public static Uri buildFarmaciasUriByName(String name) { // // return CONTENT_URI.buildUpon().appendPath(name).build(); // // } // public static Uri buildFarmaciasUriByNameQuickSearch(String name) { // return CONTENT_URI_QUICK_SEARCH.buildUpon().appendPath(name).build(); // } // public static Uri buildFavoritesUriByPhone(String phone) { // return CONTENT_URI_PATH_FAVORITES.buildUpon().appendPath(phone).build(); // } // // } // // } // Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/DbHelper.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.chernandezgil.farmacias.data.source.local.DbContract; package com.chernandezgil.farmacias.data.source.local; /** * Created by Carlos on 09/07/2016. */ public class DbHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "farmacias.db"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_FARMACIAS_TABLE="CREATE TABLE "+ DbContract.FarmaciasEntity.TABLE_NAME + " ("+
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/view/FavoriteContract.java
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // }
import android.content.Intent; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List;
package com.chernandezgil.farmacias.view; /** * Created by Carlos on 28/09/2016. */ public interface FavoriteContract { interface View {
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/view/FavoriteContract.java import android.content.Intent; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List; package com.chernandezgil.farmacias.view; /** * Created by Carlos on 28/09/2016. */ public interface FavoriteContract { interface View {
void showResults(List<Pharmacy> pharmacyList);
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/ui/adapter/FindQuickSearchAdapter.java
// Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // }
import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package com.chernandezgil.farmacias.ui.adapter; /** * Created by Carlos on 08/09/2016. */ public class FindQuickSearchAdapter extends RecyclerView.Adapter<FindQuickSearchAdapter.ViewHolder> implements View.OnClickListener { private static final String LOG_TAG = FindQuickSearchAdapter.class.getSimpleName();
// Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/FindQuickSearchAdapter.java import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package com.chernandezgil.farmacias.ui.adapter; /** * Created by Carlos on 08/09/2016. */ public class FindQuickSearchAdapter extends RecyclerView.Adapter<FindQuickSearchAdapter.ViewHolder> implements View.OnClickListener { private static final String LOG_TAG = FindQuickSearchAdapter.class.getSimpleName();
private List<SuggestionsBean> mList;
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/view/FindContract.java
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // }
import android.content.Intent; import android.database.Cursor; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List;
package com.chernandezgil.farmacias.view; /** * Created by Carlos on 05/09/2016. */ public interface FindContract { interface View {
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/view/FindContract.java import android.content.Intent; import android.database.Cursor; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List; package com.chernandezgil.farmacias.view; /** * Created by Carlos on 05/09/2016. */ public interface FindContract { interface View {
void showResults(List<Pharmacy> pharmacyList);
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/view/FindContract.java
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // }
import android.content.Intent; import android.database.Cursor; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List;
package com.chernandezgil.farmacias.view; /** * Created by Carlos on 05/09/2016. */ public interface FindContract { interface View { void showResults(List<Pharmacy> pharmacyList); void showNoResults();
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/SuggestionsBean.java // public class SuggestionsBean { // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // SuggestionsBean that = (SuggestionsBean) o; // // // return name.equals(that.name); // // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // private String name; // private int imageId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getImageId() { // return imageId; // } // // public void setImageId(int imageId) { // this.imageId = imageId; // } // // public SuggestionsBean() { // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/view/FindContract.java import android.content.Intent; import android.database.Cursor; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import com.chernandezgil.farmacias.model.SuggestionsBean; import java.util.List; package com.chernandezgil.farmacias.view; /** * Created by Carlos on 05/09/2016. */ public interface FindContract { interface View { void showResults(List<Pharmacy> pharmacyList); void showNoResults();
void showResultsQuickSearch(List<SuggestionsBean> list);
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManagerImp.java
// Path: app/src/main/java/com/chernandezgil/farmacias/Utilities/Constants.java // public class Constants { // // public static final String SPACE = " "; // public static final String COMMA = ","; // public static final String CR = "\n"; // public static final String EMPTY_STRING = ""; // public static final String SEMI_COLON=":"; // public static final int BOTTOM_NAVIGATION_HEIGHT=168; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({SCROLL_DOWN, SCROLL_UP}) // public @interface ScrollDirection { // } // // public static final int SCROLL_DOWN = 0; // public static final int SCROLL_UP = 1; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({MAP_TAB,FAVORITE}) // public @interface LayoutType { // } // // public static final int MAP_TAB = 0; // public static final int FAVORITE = 1; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // }
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.preference.PreferenceManager; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.Utilities.Constants; import com.chernandezgil.farmacias.model.Pharmacy; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List;
@Override public boolean isFirstExecution() { return mPrefs.getBoolean(FIRST_EXECUTION_KEY, true); } @Override public void setFirstExecutionFalse() { mEditor.putBoolean(FIRST_EXECUTION_KEY, false); mEditor.apply(); } public int getCurrentItemTabLayout() { return mPrefs.getInt(CURRENT_ITEM_KEY, 0); } public void setCurrentItemTabLayout(int currentItemTabLayout) { mEditor.putInt(CURRENT_ITEM_KEY, currentItemTabLayout); mEditor.apply(); } @Override public void saveLocation(Location location) { //http://stackoverflow.com/questions/3604849/where-to-save-android-gps-latitude-longitude-points // mEditor.putLong(LAT_KEY, Double.doubleToLongBits(location.getLatitude())); // mEditor.putLong(LON_KEY,Double.doubleToLongBits(location.getLongitude()));
// Path: app/src/main/java/com/chernandezgil/farmacias/Utilities/Constants.java // public class Constants { // // public static final String SPACE = " "; // public static final String COMMA = ","; // public static final String CR = "\n"; // public static final String EMPTY_STRING = ""; // public static final String SEMI_COLON=":"; // public static final int BOTTOM_NAVIGATION_HEIGHT=168; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({SCROLL_DOWN, SCROLL_UP}) // public @interface ScrollDirection { // } // // public static final int SCROLL_DOWN = 0; // public static final int SCROLL_UP = 1; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({MAP_TAB,FAVORITE}) // public @interface LayoutType { // } // // public static final int MAP_TAB = 0; // public static final int FAVORITE = 1; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManagerImp.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.preference.PreferenceManager; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.Utilities.Constants; import com.chernandezgil.farmacias.model.Pharmacy; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; @Override public boolean isFirstExecution() { return mPrefs.getBoolean(FIRST_EXECUTION_KEY, true); } @Override public void setFirstExecutionFalse() { mEditor.putBoolean(FIRST_EXECUTION_KEY, false); mEditor.apply(); } public int getCurrentItemTabLayout() { return mPrefs.getInt(CURRENT_ITEM_KEY, 0); } public void setCurrentItemTabLayout(int currentItemTabLayout) { mEditor.putInt(CURRENT_ITEM_KEY, currentItemTabLayout); mEditor.apply(); } @Override public void saveLocation(Location location) { //http://stackoverflow.com/questions/3604849/where-to-save-android-gps-latitude-longitude-points // mEditor.putLong(LAT_KEY, Double.doubleToLongBits(location.getLatitude())); // mEditor.putLong(LON_KEY,Double.doubleToLongBits(location.getLongitude()));
String locationObject = location.getLatitude() + Constants.SEMI_COLON + location.getLongitude();
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManagerImp.java
// Path: app/src/main/java/com/chernandezgil/farmacias/Utilities/Constants.java // public class Constants { // // public static final String SPACE = " "; // public static final String COMMA = ","; // public static final String CR = "\n"; // public static final String EMPTY_STRING = ""; // public static final String SEMI_COLON=":"; // public static final int BOTTOM_NAVIGATION_HEIGHT=168; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({SCROLL_DOWN, SCROLL_UP}) // public @interface ScrollDirection { // } // // public static final int SCROLL_DOWN = 0; // public static final int SCROLL_UP = 1; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({MAP_TAB,FAVORITE}) // public @interface LayoutType { // } // // public static final int MAP_TAB = 0; // public static final int FAVORITE = 1; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // }
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.preference.PreferenceManager; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.Utilities.Constants; import com.chernandezgil.farmacias.model.Pharmacy; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List;
@Override public void saveLocation(Location location) { //http://stackoverflow.com/questions/3604849/where-to-save-android-gps-latitude-longitude-points // mEditor.putLong(LAT_KEY, Double.doubleToLongBits(location.getLatitude())); // mEditor.putLong(LON_KEY,Double.doubleToLongBits(location.getLongitude())); String locationObject = location.getLatitude() + Constants.SEMI_COLON + location.getLongitude(); mEditor.putString(LOCATION_KEY, locationObject); mEditor.apply(); } @Override public Location getLocation() { Location location; String locationObject = mPrefs.getString(LOCATION_KEY, "0:0"); String [] coordinates = locationObject.split(":"); double latitud = Double.parseDouble(coordinates[0]); double longitud = Double.parseDouble(coordinates[1]); location = new Location(Constants.EMPTY_STRING); location.setLatitude(latitud); location.setLongitude(longitud); return location; } @Override public int getRadio() { return mPrefs.getInt(context.getString(R.string.seek_bar_key),2); } @Override
// Path: app/src/main/java/com/chernandezgil/farmacias/Utilities/Constants.java // public class Constants { // // public static final String SPACE = " "; // public static final String COMMA = ","; // public static final String CR = "\n"; // public static final String EMPTY_STRING = ""; // public static final String SEMI_COLON=":"; // public static final int BOTTOM_NAVIGATION_HEIGHT=168; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({SCROLL_DOWN, SCROLL_UP}) // public @interface ScrollDirection { // } // // public static final int SCROLL_DOWN = 0; // public static final int SCROLL_UP = 1; // // @Retention(RetentionPolicy.SOURCE) // @IntDef({MAP_TAB,FAVORITE}) // public @interface LayoutType { // } // // public static final int MAP_TAB = 0; // public static final int FAVORITE = 1; // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManagerImp.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.preference.PreferenceManager; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.Utilities.Constants; import com.chernandezgil.farmacias.model.Pharmacy; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; @Override public void saveLocation(Location location) { //http://stackoverflow.com/questions/3604849/where-to-save-android-gps-latitude-longitude-points // mEditor.putLong(LAT_KEY, Double.doubleToLongBits(location.getLatitude())); // mEditor.putLong(LON_KEY,Double.doubleToLongBits(location.getLongitude())); String locationObject = location.getLatitude() + Constants.SEMI_COLON + location.getLongitude(); mEditor.putString(LOCATION_KEY, locationObject); mEditor.apply(); } @Override public Location getLocation() { Location location; String locationObject = mPrefs.getString(LOCATION_KEY, "0:0"); String [] coordinates = locationObject.split(":"); double latitud = Double.parseDouble(coordinates[0]); double longitud = Double.parseDouble(coordinates[1]); location = new Location(Constants.EMPTY_STRING); location.setLatitude(latitud); location.setLongitude(longitud); return location; } @Override public int getRadio() { return mPrefs.getInt(context.getString(R.string.seek_bar_key),2); } @Override
public void saveFavoriteList(List<Pharmacy> list) {
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/Utilities/ColorUtils.java
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // }
import android.support.annotation.CheckResult; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.FloatRange; import android.support.annotation.IntRange; import android.support.v4.content.ContextCompat; import com.chernandezgil.farmacias.MyApplication;
package com.chernandezgil.farmacias.Utilities; /** * Created by Carlos on 30/09/2016. */ public class ColorUtils { /** * For use in methods like Color.parseColor("") * @param originalColor color, without alpha * @param alpha from 0.0 to 1.0 * @return */ public static String addAlpha(String originalColor, double alpha) { long alphaFixed = Math.round(alpha * 255); String alphaHex = Long.toHexString(alphaFixed); if (alphaHex.length() == 1) { alphaHex = "0" + alphaHex; } originalColor = originalColor.replace("#", "#" + alphaHex); return originalColor; } /** * * http://robusttechhouse.com/tutorial-how-to-use-android-support-annotations-library/ */ public static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @IntRange(from = 0, to = 255) int alpha) { return (color & 0x00ffffff) | (alpha << 24); } /** * * http://robusttechhouse.com/tutorial-how-to-use-android-support-annotations-library/ */ public static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @FloatRange(from = 0f, to = 1f) float alpha) { return modifyAlpha(color, (int) (255f * alpha)); } /** * R.color.color_id */ public static @CheckResult @ColorInt int modifyAlpha(@ColorRes long color, @FloatRange(from = 0f, to = 1f) float alpha) { int colorInt;
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/Utilities/ColorUtils.java import android.support.annotation.CheckResult; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.FloatRange; import android.support.annotation.IntRange; import android.support.v4.content.ContextCompat; import com.chernandezgil.farmacias.MyApplication; package com.chernandezgil.farmacias.Utilities; /** * Created by Carlos on 30/09/2016. */ public class ColorUtils { /** * For use in methods like Color.parseColor("") * @param originalColor color, without alpha * @param alpha from 0.0 to 1.0 * @return */ public static String addAlpha(String originalColor, double alpha) { long alphaFixed = Math.round(alpha * 255); String alphaHex = Long.toHexString(alphaFixed); if (alphaHex.length() == 1) { alphaHex = "0" + alphaHex; } originalColor = originalColor.replace("#", "#" + alphaHex); return originalColor; } /** * * http://robusttechhouse.com/tutorial-how-to-use-android-support-annotations-library/ */ public static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @IntRange(from = 0, to = 255) int alpha) { return (color & 0x00ffffff) | (alpha << 24); } /** * * http://robusttechhouse.com/tutorial-how-to-use-android-support-annotations-library/ */ public static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @FloatRange(from = 0f, to = 1f) float alpha) { return modifyAlpha(color, (int) (255f * alpha)); } /** * R.color.color_id */ public static @CheckResult @ColorInt int modifyAlpha(@ColorRes long color, @FloatRange(from = 0f, to = 1f) float alpha) { int colorInt;
colorInt = ContextCompat.getColor(MyApplication.getContext(),(int)color);
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/ColorMap.java // public class ColorMap { // // // private HashMap<String, Integer> colorHashMap; // int[] colors; // // // public ColorMap() { // colorHashMap = new HashMap<>(); // loadColorsArray(); // } // private void loadColorsArray() { // // colors = MyApplication.getContext().getResources().getIntArray(R.array.colors); // } // public void generate() { // // for (int i = 0; i < 26; i++) { // colorHashMap.put(Utils.characterFromInteger(i), colors[i]); // // } // // } // // public int getColorForString(String letter) { // return colorHashMap.get(letter); // } // // // // private int generateRandomColor() { // int red = ((int) (Math.random() * 255)); // int green = ((int) (Math.random() * 255)); // int blue = ((int) (Math.random() * 255)); // return Color.rgb(red, green, blue); // } // // public HashMap<String, Integer> getColorHashMap() { // return colorHashMap; // } // // public void setColorHashMap(HashMap<String, Integer> colorHashMap) { // this.colorHashMap = colorHashMap; // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/services/DownloadFarmacias.java // public class DownloadFarmacias extends IntentService { // private static String LOG_TAG=DownloadFarmacias.class.getSimpleName(); // public DownloadFarmacias(String name) { // super(name); // } // public DownloadFarmacias(){ // super(LOG_TAG); // } // @Override // protected void onHandleIntent(Intent intent) { // List<FarmaciasCsvBean> listFarmacias= CsvReader.readWithCsvBeanReader(); // Vector<ContentValues> vector=new Vector<>(); // if(listFarmacias!=null) { // getContentResolver().delete(DbContract.FarmaciasEntity.CONTENT_URI,null,null); // } else { // return; // } // for(int i = 0; i<listFarmacias.size();i++) { // FarmaciasCsvBean farmaciasCsvBean=listFarmacias.get(i); // ContentValues contentValues=new ContentValues(); // contentValues.put(DbContract.FarmaciasEntity.NAME,farmaciasCsvBean.getName()); // contentValues.put(DbContract.FarmaciasEntity.HOURS,farmaciasCsvBean.getHorario()); // contentValues.put(DbContract.FarmaciasEntity.ADDRESS,farmaciasCsvBean.getAddress()); // contentValues.put(DbContract.FarmaciasEntity.LOCALITY,farmaciasCsvBean.getLocality()); // contentValues.put(DbContract.FarmaciasEntity.PROVINCE,farmaciasCsvBean.getProvince()); // contentValues.put(DbContract.FarmaciasEntity.POSTAL_CODE,farmaciasCsvBean.getPostal_code()); // contentValues.put(DbContract.FarmaciasEntity.PHONE,farmaciasCsvBean.getPhone()); // contentValues.put(DbContract.FarmaciasEntity.LAT,farmaciasCsvBean.getLat()); // contentValues.put(DbContract.FarmaciasEntity.LON,farmaciasCsvBean.getLon()); // vector.add(contentValues); // // // } // ContentValues[] contentValues=new ContentValues[vector.size()]; // vector.toArray(contentValues); // Uri uri= DbContract.FarmaciasEntity.CONTENT_URI; // int inserted=getContentResolver().bulkInsert(uri,contentValues); // Utils.logD(LOG_TAG,String.format("successfully inserted %d registers in farmacias",inserted)); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // }
import android.content.Context; import android.content.Intent; import com.chernandezgil.farmacias.MyApplication; import com.chernandezgil.farmacias.model.ColorMap; import com.chernandezgil.farmacias.services.DownloadFarmacias; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager;
package com.chernandezgil.farmacias.data.source; /** * Created by Carlos on 12/08/2016. */ public class MainActivityInteractor { private PreferencesManager mPreferencesManager; private Context mContext; public MainActivityInteractor(PreferencesManager preferencesManager) { mPreferencesManager=preferencesManager;
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/ColorMap.java // public class ColorMap { // // // private HashMap<String, Integer> colorHashMap; // int[] colors; // // // public ColorMap() { // colorHashMap = new HashMap<>(); // loadColorsArray(); // } // private void loadColorsArray() { // // colors = MyApplication.getContext().getResources().getIntArray(R.array.colors); // } // public void generate() { // // for (int i = 0; i < 26; i++) { // colorHashMap.put(Utils.characterFromInteger(i), colors[i]); // // } // // } // // public int getColorForString(String letter) { // return colorHashMap.get(letter); // } // // // // private int generateRandomColor() { // int red = ((int) (Math.random() * 255)); // int green = ((int) (Math.random() * 255)); // int blue = ((int) (Math.random() * 255)); // return Color.rgb(red, green, blue); // } // // public HashMap<String, Integer> getColorHashMap() { // return colorHashMap; // } // // public void setColorHashMap(HashMap<String, Integer> colorHashMap) { // this.colorHashMap = colorHashMap; // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/services/DownloadFarmacias.java // public class DownloadFarmacias extends IntentService { // private static String LOG_TAG=DownloadFarmacias.class.getSimpleName(); // public DownloadFarmacias(String name) { // super(name); // } // public DownloadFarmacias(){ // super(LOG_TAG); // } // @Override // protected void onHandleIntent(Intent intent) { // List<FarmaciasCsvBean> listFarmacias= CsvReader.readWithCsvBeanReader(); // Vector<ContentValues> vector=new Vector<>(); // if(listFarmacias!=null) { // getContentResolver().delete(DbContract.FarmaciasEntity.CONTENT_URI,null,null); // } else { // return; // } // for(int i = 0; i<listFarmacias.size();i++) { // FarmaciasCsvBean farmaciasCsvBean=listFarmacias.get(i); // ContentValues contentValues=new ContentValues(); // contentValues.put(DbContract.FarmaciasEntity.NAME,farmaciasCsvBean.getName()); // contentValues.put(DbContract.FarmaciasEntity.HOURS,farmaciasCsvBean.getHorario()); // contentValues.put(DbContract.FarmaciasEntity.ADDRESS,farmaciasCsvBean.getAddress()); // contentValues.put(DbContract.FarmaciasEntity.LOCALITY,farmaciasCsvBean.getLocality()); // contentValues.put(DbContract.FarmaciasEntity.PROVINCE,farmaciasCsvBean.getProvince()); // contentValues.put(DbContract.FarmaciasEntity.POSTAL_CODE,farmaciasCsvBean.getPostal_code()); // contentValues.put(DbContract.FarmaciasEntity.PHONE,farmaciasCsvBean.getPhone()); // contentValues.put(DbContract.FarmaciasEntity.LAT,farmaciasCsvBean.getLat()); // contentValues.put(DbContract.FarmaciasEntity.LON,farmaciasCsvBean.getLon()); // vector.add(contentValues); // // // } // ContentValues[] contentValues=new ContentValues[vector.size()]; // vector.toArray(contentValues); // Uri uri= DbContract.FarmaciasEntity.CONTENT_URI; // int inserted=getContentResolver().bulkInsert(uri,contentValues); // Utils.logD(LOG_TAG,String.format("successfully inserted %d registers in farmacias",inserted)); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java import android.content.Context; import android.content.Intent; import com.chernandezgil.farmacias.MyApplication; import com.chernandezgil.farmacias.model.ColorMap; import com.chernandezgil.farmacias.services.DownloadFarmacias; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; package com.chernandezgil.farmacias.data.source; /** * Created by Carlos on 12/08/2016. */ public class MainActivityInteractor { private PreferencesManager mPreferencesManager; private Context mContext; public MainActivityInteractor(PreferencesManager preferencesManager) { mPreferencesManager=preferencesManager;
mContext= MyApplication.getContext();
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/ColorMap.java // public class ColorMap { // // // private HashMap<String, Integer> colorHashMap; // int[] colors; // // // public ColorMap() { // colorHashMap = new HashMap<>(); // loadColorsArray(); // } // private void loadColorsArray() { // // colors = MyApplication.getContext().getResources().getIntArray(R.array.colors); // } // public void generate() { // // for (int i = 0; i < 26; i++) { // colorHashMap.put(Utils.characterFromInteger(i), colors[i]); // // } // // } // // public int getColorForString(String letter) { // return colorHashMap.get(letter); // } // // // // private int generateRandomColor() { // int red = ((int) (Math.random() * 255)); // int green = ((int) (Math.random() * 255)); // int blue = ((int) (Math.random() * 255)); // return Color.rgb(red, green, blue); // } // // public HashMap<String, Integer> getColorHashMap() { // return colorHashMap; // } // // public void setColorHashMap(HashMap<String, Integer> colorHashMap) { // this.colorHashMap = colorHashMap; // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/services/DownloadFarmacias.java // public class DownloadFarmacias extends IntentService { // private static String LOG_TAG=DownloadFarmacias.class.getSimpleName(); // public DownloadFarmacias(String name) { // super(name); // } // public DownloadFarmacias(){ // super(LOG_TAG); // } // @Override // protected void onHandleIntent(Intent intent) { // List<FarmaciasCsvBean> listFarmacias= CsvReader.readWithCsvBeanReader(); // Vector<ContentValues> vector=new Vector<>(); // if(listFarmacias!=null) { // getContentResolver().delete(DbContract.FarmaciasEntity.CONTENT_URI,null,null); // } else { // return; // } // for(int i = 0; i<listFarmacias.size();i++) { // FarmaciasCsvBean farmaciasCsvBean=listFarmacias.get(i); // ContentValues contentValues=new ContentValues(); // contentValues.put(DbContract.FarmaciasEntity.NAME,farmaciasCsvBean.getName()); // contentValues.put(DbContract.FarmaciasEntity.HOURS,farmaciasCsvBean.getHorario()); // contentValues.put(DbContract.FarmaciasEntity.ADDRESS,farmaciasCsvBean.getAddress()); // contentValues.put(DbContract.FarmaciasEntity.LOCALITY,farmaciasCsvBean.getLocality()); // contentValues.put(DbContract.FarmaciasEntity.PROVINCE,farmaciasCsvBean.getProvince()); // contentValues.put(DbContract.FarmaciasEntity.POSTAL_CODE,farmaciasCsvBean.getPostal_code()); // contentValues.put(DbContract.FarmaciasEntity.PHONE,farmaciasCsvBean.getPhone()); // contentValues.put(DbContract.FarmaciasEntity.LAT,farmaciasCsvBean.getLat()); // contentValues.put(DbContract.FarmaciasEntity.LON,farmaciasCsvBean.getLon()); // vector.add(contentValues); // // // } // ContentValues[] contentValues=new ContentValues[vector.size()]; // vector.toArray(contentValues); // Uri uri= DbContract.FarmaciasEntity.CONTENT_URI; // int inserted=getContentResolver().bulkInsert(uri,contentValues); // Utils.logD(LOG_TAG,String.format("successfully inserted %d registers in farmacias",inserted)); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // }
import android.content.Context; import android.content.Intent; import com.chernandezgil.farmacias.MyApplication; import com.chernandezgil.farmacias.model.ColorMap; import com.chernandezgil.farmacias.services.DownloadFarmacias; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager;
package com.chernandezgil.farmacias.data.source; /** * Created by Carlos on 12/08/2016. */ public class MainActivityInteractor { private PreferencesManager mPreferencesManager; private Context mContext; public MainActivityInteractor(PreferencesManager preferencesManager) { mPreferencesManager=preferencesManager; mContext= MyApplication.getContext(); } public void loadData(){ if(mPreferencesManager.isFirstExecution()) { launchDownloadService();
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/ColorMap.java // public class ColorMap { // // // private HashMap<String, Integer> colorHashMap; // int[] colors; // // // public ColorMap() { // colorHashMap = new HashMap<>(); // loadColorsArray(); // } // private void loadColorsArray() { // // colors = MyApplication.getContext().getResources().getIntArray(R.array.colors); // } // public void generate() { // // for (int i = 0; i < 26; i++) { // colorHashMap.put(Utils.characterFromInteger(i), colors[i]); // // } // // } // // public int getColorForString(String letter) { // return colorHashMap.get(letter); // } // // // // private int generateRandomColor() { // int red = ((int) (Math.random() * 255)); // int green = ((int) (Math.random() * 255)); // int blue = ((int) (Math.random() * 255)); // return Color.rgb(red, green, blue); // } // // public HashMap<String, Integer> getColorHashMap() { // return colorHashMap; // } // // public void setColorHashMap(HashMap<String, Integer> colorHashMap) { // this.colorHashMap = colorHashMap; // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/services/DownloadFarmacias.java // public class DownloadFarmacias extends IntentService { // private static String LOG_TAG=DownloadFarmacias.class.getSimpleName(); // public DownloadFarmacias(String name) { // super(name); // } // public DownloadFarmacias(){ // super(LOG_TAG); // } // @Override // protected void onHandleIntent(Intent intent) { // List<FarmaciasCsvBean> listFarmacias= CsvReader.readWithCsvBeanReader(); // Vector<ContentValues> vector=new Vector<>(); // if(listFarmacias!=null) { // getContentResolver().delete(DbContract.FarmaciasEntity.CONTENT_URI,null,null); // } else { // return; // } // for(int i = 0; i<listFarmacias.size();i++) { // FarmaciasCsvBean farmaciasCsvBean=listFarmacias.get(i); // ContentValues contentValues=new ContentValues(); // contentValues.put(DbContract.FarmaciasEntity.NAME,farmaciasCsvBean.getName()); // contentValues.put(DbContract.FarmaciasEntity.HOURS,farmaciasCsvBean.getHorario()); // contentValues.put(DbContract.FarmaciasEntity.ADDRESS,farmaciasCsvBean.getAddress()); // contentValues.put(DbContract.FarmaciasEntity.LOCALITY,farmaciasCsvBean.getLocality()); // contentValues.put(DbContract.FarmaciasEntity.PROVINCE,farmaciasCsvBean.getProvince()); // contentValues.put(DbContract.FarmaciasEntity.POSTAL_CODE,farmaciasCsvBean.getPostal_code()); // contentValues.put(DbContract.FarmaciasEntity.PHONE,farmaciasCsvBean.getPhone()); // contentValues.put(DbContract.FarmaciasEntity.LAT,farmaciasCsvBean.getLat()); // contentValues.put(DbContract.FarmaciasEntity.LON,farmaciasCsvBean.getLon()); // vector.add(contentValues); // // // } // ContentValues[] contentValues=new ContentValues[vector.size()]; // vector.toArray(contentValues); // Uri uri= DbContract.FarmaciasEntity.CONTENT_URI; // int inserted=getContentResolver().bulkInsert(uri,contentValues); // Utils.logD(LOG_TAG,String.format("successfully inserted %d registers in farmacias",inserted)); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java import android.content.Context; import android.content.Intent; import com.chernandezgil.farmacias.MyApplication; import com.chernandezgil.farmacias.model.ColorMap; import com.chernandezgil.farmacias.services.DownloadFarmacias; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; package com.chernandezgil.farmacias.data.source; /** * Created by Carlos on 12/08/2016. */ public class MainActivityInteractor { private PreferencesManager mPreferencesManager; private Context mContext; public MainActivityInteractor(PreferencesManager preferencesManager) { mPreferencesManager=preferencesManager; mContext= MyApplication.getContext(); } public void loadData(){ if(mPreferencesManager.isFirstExecution()) { launchDownloadService();
ColorMap colorMap = new ColorMap();
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/ColorMap.java // public class ColorMap { // // // private HashMap<String, Integer> colorHashMap; // int[] colors; // // // public ColorMap() { // colorHashMap = new HashMap<>(); // loadColorsArray(); // } // private void loadColorsArray() { // // colors = MyApplication.getContext().getResources().getIntArray(R.array.colors); // } // public void generate() { // // for (int i = 0; i < 26; i++) { // colorHashMap.put(Utils.characterFromInteger(i), colors[i]); // // } // // } // // public int getColorForString(String letter) { // return colorHashMap.get(letter); // } // // // // private int generateRandomColor() { // int red = ((int) (Math.random() * 255)); // int green = ((int) (Math.random() * 255)); // int blue = ((int) (Math.random() * 255)); // return Color.rgb(red, green, blue); // } // // public HashMap<String, Integer> getColorHashMap() { // return colorHashMap; // } // // public void setColorHashMap(HashMap<String, Integer> colorHashMap) { // this.colorHashMap = colorHashMap; // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/services/DownloadFarmacias.java // public class DownloadFarmacias extends IntentService { // private static String LOG_TAG=DownloadFarmacias.class.getSimpleName(); // public DownloadFarmacias(String name) { // super(name); // } // public DownloadFarmacias(){ // super(LOG_TAG); // } // @Override // protected void onHandleIntent(Intent intent) { // List<FarmaciasCsvBean> listFarmacias= CsvReader.readWithCsvBeanReader(); // Vector<ContentValues> vector=new Vector<>(); // if(listFarmacias!=null) { // getContentResolver().delete(DbContract.FarmaciasEntity.CONTENT_URI,null,null); // } else { // return; // } // for(int i = 0; i<listFarmacias.size();i++) { // FarmaciasCsvBean farmaciasCsvBean=listFarmacias.get(i); // ContentValues contentValues=new ContentValues(); // contentValues.put(DbContract.FarmaciasEntity.NAME,farmaciasCsvBean.getName()); // contentValues.put(DbContract.FarmaciasEntity.HOURS,farmaciasCsvBean.getHorario()); // contentValues.put(DbContract.FarmaciasEntity.ADDRESS,farmaciasCsvBean.getAddress()); // contentValues.put(DbContract.FarmaciasEntity.LOCALITY,farmaciasCsvBean.getLocality()); // contentValues.put(DbContract.FarmaciasEntity.PROVINCE,farmaciasCsvBean.getProvince()); // contentValues.put(DbContract.FarmaciasEntity.POSTAL_CODE,farmaciasCsvBean.getPostal_code()); // contentValues.put(DbContract.FarmaciasEntity.PHONE,farmaciasCsvBean.getPhone()); // contentValues.put(DbContract.FarmaciasEntity.LAT,farmaciasCsvBean.getLat()); // contentValues.put(DbContract.FarmaciasEntity.LON,farmaciasCsvBean.getLon()); // vector.add(contentValues); // // // } // ContentValues[] contentValues=new ContentValues[vector.size()]; // vector.toArray(contentValues); // Uri uri= DbContract.FarmaciasEntity.CONTENT_URI; // int inserted=getContentResolver().bulkInsert(uri,contentValues); // Utils.logD(LOG_TAG,String.format("successfully inserted %d registers in farmacias",inserted)); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // }
import android.content.Context; import android.content.Intent; import com.chernandezgil.farmacias.MyApplication; import com.chernandezgil.farmacias.model.ColorMap; import com.chernandezgil.farmacias.services.DownloadFarmacias; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager;
package com.chernandezgil.farmacias.data.source; /** * Created by Carlos on 12/08/2016. */ public class MainActivityInteractor { private PreferencesManager mPreferencesManager; private Context mContext; public MainActivityInteractor(PreferencesManager preferencesManager) { mPreferencesManager=preferencesManager; mContext= MyApplication.getContext(); } public void loadData(){ if(mPreferencesManager.isFirstExecution()) { launchDownloadService(); ColorMap colorMap = new ColorMap(); colorMap.generate(); mPreferencesManager.saveColorMap(colorMap.getColorHashMap()); mPreferencesManager.setFirstExecutionFalse(); } } private void launchDownloadService() {
// Path: app/src/main/java/com/chernandezgil/farmacias/MyApplication.java // public class MyApplication extends Application{ // // private MainComponent mMapComponent; // private static Context context; // @Override // public void onCreate() { // super.onCreate(); // LeakCanary.install(this); // // this.context=getApplicationContext(); // // mMapComponent= DaggerMainComponent.builder() // // .mainModule(new MainModule()) // // .applicationModule(new ApplicationModule(this)) // // .build(); // // // } // public static Context getContext(){ // return context; // } // // public MainComponent getComponent(){ // // return mMapComponent; // // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/model/ColorMap.java // public class ColorMap { // // // private HashMap<String, Integer> colorHashMap; // int[] colors; // // // public ColorMap() { // colorHashMap = new HashMap<>(); // loadColorsArray(); // } // private void loadColorsArray() { // // colors = MyApplication.getContext().getResources().getIntArray(R.array.colors); // } // public void generate() { // // for (int i = 0; i < 26; i++) { // colorHashMap.put(Utils.characterFromInteger(i), colors[i]); // // } // // } // // public int getColorForString(String letter) { // return colorHashMap.get(letter); // } // // // // private int generateRandomColor() { // int red = ((int) (Math.random() * 255)); // int green = ((int) (Math.random() * 255)); // int blue = ((int) (Math.random() * 255)); // return Color.rgb(red, green, blue); // } // // public HashMap<String, Integer> getColorHashMap() { // return colorHashMap; // } // // public void setColorHashMap(HashMap<String, Integer> colorHashMap) { // this.colorHashMap = colorHashMap; // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/services/DownloadFarmacias.java // public class DownloadFarmacias extends IntentService { // private static String LOG_TAG=DownloadFarmacias.class.getSimpleName(); // public DownloadFarmacias(String name) { // super(name); // } // public DownloadFarmacias(){ // super(LOG_TAG); // } // @Override // protected void onHandleIntent(Intent intent) { // List<FarmaciasCsvBean> listFarmacias= CsvReader.readWithCsvBeanReader(); // Vector<ContentValues> vector=new Vector<>(); // if(listFarmacias!=null) { // getContentResolver().delete(DbContract.FarmaciasEntity.CONTENT_URI,null,null); // } else { // return; // } // for(int i = 0; i<listFarmacias.size();i++) { // FarmaciasCsvBean farmaciasCsvBean=listFarmacias.get(i); // ContentValues contentValues=new ContentValues(); // contentValues.put(DbContract.FarmaciasEntity.NAME,farmaciasCsvBean.getName()); // contentValues.put(DbContract.FarmaciasEntity.HOURS,farmaciasCsvBean.getHorario()); // contentValues.put(DbContract.FarmaciasEntity.ADDRESS,farmaciasCsvBean.getAddress()); // contentValues.put(DbContract.FarmaciasEntity.LOCALITY,farmaciasCsvBean.getLocality()); // contentValues.put(DbContract.FarmaciasEntity.PROVINCE,farmaciasCsvBean.getProvince()); // contentValues.put(DbContract.FarmaciasEntity.POSTAL_CODE,farmaciasCsvBean.getPostal_code()); // contentValues.put(DbContract.FarmaciasEntity.PHONE,farmaciasCsvBean.getPhone()); // contentValues.put(DbContract.FarmaciasEntity.LAT,farmaciasCsvBean.getLat()); // contentValues.put(DbContract.FarmaciasEntity.LON,farmaciasCsvBean.getLon()); // vector.add(contentValues); // // // } // ContentValues[] contentValues=new ContentValues[vector.size()]; // vector.toArray(contentValues); // Uri uri= DbContract.FarmaciasEntity.CONTENT_URI; // int inserted=getContentResolver().bulkInsert(uri,contentValues); // Utils.logD(LOG_TAG,String.format("successfully inserted %d registers in farmacias",inserted)); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java import android.content.Context; import android.content.Intent; import com.chernandezgil.farmacias.MyApplication; import com.chernandezgil.farmacias.model.ColorMap; import com.chernandezgil.farmacias.services.DownloadFarmacias; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; package com.chernandezgil.farmacias.data.source; /** * Created by Carlos on 12/08/2016. */ public class MainActivityInteractor { private PreferencesManager mPreferencesManager; private Context mContext; public MainActivityInteractor(PreferencesManager preferencesManager) { mPreferencesManager=preferencesManager; mContext= MyApplication.getContext(); } public void loadData(){ if(mPreferencesManager.isFirstExecution()) { launchDownloadService(); ColorMap colorMap = new ColorMap(); colorMap.generate(); mPreferencesManager.saveColorMap(colorMap.getColorHashMap()); mPreferencesManager.setFirstExecutionFalse(); } } private void launchDownloadService() {
Intent intent = new Intent(mContext, DownloadFarmacias.class);
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/customwidget/dialog/DialogBorrarHistorialBusqueda.java
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/RecentSuggestionsProvider.java // public class RecentSuggestionsProvider extends android.content.SearchRecentSuggestionsProvider { // public final static String AUTHORITY = "com.chernandezgil.farmacias.data.source.local.RecentSuggestionsProvider"; // public final static int MODE = DATABASE_MODE_QUERIES; // // // private UriMatcher matcher; // private static final int SUGGESTIONS_CODE = 5; // public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY); // // public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath() // // public RecentSuggestionsProvider() { // matcher = new UriMatcher(UriMatcher.NO_MATCH); // matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS_CODE); // // // setupSuggestions(AUTHORITY,MODE); // } // // @Override // public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // // int code = matcher.match(uri); // switch (code) { // case SUGGESTIONS_CODE: // if (selectionArgs == null || selectionArgs.length == 0 || selectionArgs[0].trim().length() == 0) // { // return super.query(uri, projection, selection, selectionArgs, sortOrder); // } // else // { // return super.query(uri, projection, selection, selectionArgs, sortOrder); // // // } // // // default: return super.query(uri, projection, selection, selectionArgs, sortOrder); // } // //Cursor c= super.query(uri, projection, selection, selectionArgs, sortOrder); // //return c; // } // // @Override // public int delete(Uri uri, String selection, String[] selectionArgs) { // return super.delete(uri, selection, selectionArgs); // } // }
import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.widget.Toast; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.data.source.local.RecentSuggestionsProvider;
package com.chernandezgil.farmacias.customwidget.dialog; /** * Created by Carlos on 20/12/2016. */ public class DialogBorrarHistorialBusqueda extends DialogFragment { public DialogBorrarHistorialBusqueda() { } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog dialog = new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.borrar_historial_confirmar_accion)) .setMessage(getString(R.string.borrar_historial_mensaje)) .setIcon(R.drawable.alert_box) .setNegativeButton(getString(R.string.borrar_historial_no_text), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(getString(R.string.borrar_historial_yes_text), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // RecentSuggestionsProvider.BASE_CONTENT_URI.buildUpon().appendPath("suggestions") segun // el codigo de la clase para los insert hay que agregar suggestions
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/RecentSuggestionsProvider.java // public class RecentSuggestionsProvider extends android.content.SearchRecentSuggestionsProvider { // public final static String AUTHORITY = "com.chernandezgil.farmacias.data.source.local.RecentSuggestionsProvider"; // public final static int MODE = DATABASE_MODE_QUERIES; // // // private UriMatcher matcher; // private static final int SUGGESTIONS_CODE = 5; // public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY); // // public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath() // // public RecentSuggestionsProvider() { // matcher = new UriMatcher(UriMatcher.NO_MATCH); // matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS_CODE); // // // setupSuggestions(AUTHORITY,MODE); // } // // @Override // public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // // int code = matcher.match(uri); // switch (code) { // case SUGGESTIONS_CODE: // if (selectionArgs == null || selectionArgs.length == 0 || selectionArgs[0].trim().length() == 0) // { // return super.query(uri, projection, selection, selectionArgs, sortOrder); // } // else // { // return super.query(uri, projection, selection, selectionArgs, sortOrder); // // // } // // // default: return super.query(uri, projection, selection, selectionArgs, sortOrder); // } // //Cursor c= super.query(uri, projection, selection, selectionArgs, sortOrder); // //return c; // } // // @Override // public int delete(Uri uri, String selection, String[] selectionArgs) { // return super.delete(uri, selection, selectionArgs); // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/customwidget/dialog/DialogBorrarHistorialBusqueda.java import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.widget.Toast; import com.chernandezgil.farmacias.R; import com.chernandezgil.farmacias.data.source.local.RecentSuggestionsProvider; package com.chernandezgil.farmacias.customwidget.dialog; /** * Created by Carlos on 20/12/2016. */ public class DialogBorrarHistorialBusqueda extends DialogFragment { public DialogBorrarHistorialBusqueda() { } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog dialog = new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.borrar_historial_confirmar_accion)) .setMessage(getString(R.string.borrar_historial_mensaje)) .setIcon(R.drawable.alert_box) .setNegativeButton(getString(R.string.borrar_historial_no_text), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(getString(R.string.borrar_historial_yes_text), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // RecentSuggestionsProvider.BASE_CONTENT_URI.buildUpon().appendPath("suggestions") segun // el codigo de la clase para los insert hay que agregar suggestions
Uri uri = RecentSuggestionsProvider.BASE_CONTENT_URI.buildUpon().appendPath("suggestions").build();
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // }
import android.content.SharedPreferences; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import java.util.HashMap; import java.util.List;
package com.chernandezgil.farmacias.ui.adapter; /** * Created by Carlos on 11/08/2016. */ public interface PreferencesManager { SharedPreferences getSharedPreferences(); String getLocationKey(); int retrieveRadioBusquedaFromSp(); boolean isFirstExecution(); void setFirstExecutionFalse(); int getCurrentItemTabLayout(); void setCurrentItemTabLayout(int currentItemTabLayout); void saveLocation(Location location); Location getLocation(); int getRadio();
// Path: app/src/main/java/com/chernandezgil/farmacias/model/Pharmacy.java // public class Pharmacy extends PharmacyObjectMap implements Parcelable { // // private boolean optionsRow; // int circleColor; // // // // public Pharmacy() { // } // // public int getCircleColor() { // return circleColor; // } // // public void setCircleColor(int circleColor) { // this.circleColor = circleColor; // } // // public boolean isOptionsRow() { // return optionsRow; // } // // public void setOptionsRow(boolean optionsRow) { // this.optionsRow = optionsRow; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // super.writeToParcel(dest, flags); // dest.writeByte(this.optionsRow ? (byte) 1 : (byte) 0); // dest.writeInt(this.circleColor); // } // // protected Pharmacy(Parcel in) { // super(in); // this.optionsRow = in.readByte() != 0; // this.circleColor = in.readInt(); // } // // public static final Creator<Pharmacy> CREATOR = new Creator<Pharmacy>() { // @Override // public Pharmacy createFromParcel(Parcel source) { // return new Pharmacy(source); // } // // @Override // public Pharmacy[] newArray(int size) { // return new Pharmacy[size]; // } // }; // } // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java import android.content.SharedPreferences; import android.location.Location; import com.chernandezgil.farmacias.model.Pharmacy; import java.util.HashMap; import java.util.List; package com.chernandezgil.farmacias.ui.adapter; /** * Created by Carlos on 11/08/2016. */ public interface PreferencesManager { SharedPreferences getSharedPreferences(); String getLocationKey(); int retrieveRadioBusquedaFromSp(); boolean isFirstExecution(); void setFirstExecutionFalse(); int getCurrentItemTabLayout(); void setCurrentItemTabLayout(int currentItemTabLayout); void saveLocation(Location location); Location getLocation(); int getRadio();
void saveFavoriteList(List<Pharmacy> list);
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/presenter/MainActivityPresenter.java
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java // public class MainActivityInteractor { // private PreferencesManager mPreferencesManager; // private Context mContext; // // public MainActivityInteractor(PreferencesManager preferencesManager) { // mPreferencesManager=preferencesManager; // mContext= MyApplication.getContext(); // } // // public void loadData(){ // if(mPreferencesManager.isFirstExecution()) { // launchDownloadService(); // ColorMap colorMap = new ColorMap(); // colorMap.generate(); // mPreferencesManager.saveColorMap(colorMap.getColorHashMap()); // mPreferencesManager.setFirstExecutionFalse(); // } // } // // private void launchDownloadService() { // Intent intent = new Intent(mContext, DownloadFarmacias.class); // mContext.startService(intent); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // // Path: app/src/main/java/com/chernandezgil/farmacias/view/MainActivityContract.java // public interface MainActivityContract { // // interface View { // // } // interface Presenter<V> { // // void setView(V view); // void detachView(); // void onStart(); // // // } // }
import com.chernandezgil.farmacias.data.source.MainActivityInteractor; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; import com.chernandezgil.farmacias.view.MainActivityContract;
package com.chernandezgil.farmacias.presenter; /** * Created by Carlos on 01/08/2016. */ public class MainActivityPresenter implements MainActivityContract.Presenter<MainActivityContract.View> { private static final String LOG_TAG=MainActivityPresenter.class.getSimpleName(); private MainActivityContract.View mMainActivityView;
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java // public class MainActivityInteractor { // private PreferencesManager mPreferencesManager; // private Context mContext; // // public MainActivityInteractor(PreferencesManager preferencesManager) { // mPreferencesManager=preferencesManager; // mContext= MyApplication.getContext(); // } // // public void loadData(){ // if(mPreferencesManager.isFirstExecution()) { // launchDownloadService(); // ColorMap colorMap = new ColorMap(); // colorMap.generate(); // mPreferencesManager.saveColorMap(colorMap.getColorHashMap()); // mPreferencesManager.setFirstExecutionFalse(); // } // } // // private void launchDownloadService() { // Intent intent = new Intent(mContext, DownloadFarmacias.class); // mContext.startService(intent); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // // Path: app/src/main/java/com/chernandezgil/farmacias/view/MainActivityContract.java // public interface MainActivityContract { // // interface View { // // } // interface Presenter<V> { // // void setView(V view); // void detachView(); // void onStart(); // // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/presenter/MainActivityPresenter.java import com.chernandezgil.farmacias.data.source.MainActivityInteractor; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; import com.chernandezgil.farmacias.view.MainActivityContract; package com.chernandezgil.farmacias.presenter; /** * Created by Carlos on 01/08/2016. */ public class MainActivityPresenter implements MainActivityContract.Presenter<MainActivityContract.View> { private static final String LOG_TAG=MainActivityPresenter.class.getSimpleName(); private MainActivityContract.View mMainActivityView;
private MainActivityInteractor mMainActivityInteractor;
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/presenter/MainActivityPresenter.java
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java // public class MainActivityInteractor { // private PreferencesManager mPreferencesManager; // private Context mContext; // // public MainActivityInteractor(PreferencesManager preferencesManager) { // mPreferencesManager=preferencesManager; // mContext= MyApplication.getContext(); // } // // public void loadData(){ // if(mPreferencesManager.isFirstExecution()) { // launchDownloadService(); // ColorMap colorMap = new ColorMap(); // colorMap.generate(); // mPreferencesManager.saveColorMap(colorMap.getColorHashMap()); // mPreferencesManager.setFirstExecutionFalse(); // } // } // // private void launchDownloadService() { // Intent intent = new Intent(mContext, DownloadFarmacias.class); // mContext.startService(intent); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // // Path: app/src/main/java/com/chernandezgil/farmacias/view/MainActivityContract.java // public interface MainActivityContract { // // interface View { // // } // interface Presenter<V> { // // void setView(V view); // void detachView(); // void onStart(); // // // } // }
import com.chernandezgil.farmacias.data.source.MainActivityInteractor; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; import com.chernandezgil.farmacias.view.MainActivityContract;
package com.chernandezgil.farmacias.presenter; /** * Created by Carlos on 01/08/2016. */ public class MainActivityPresenter implements MainActivityContract.Presenter<MainActivityContract.View> { private static final String LOG_TAG=MainActivityPresenter.class.getSimpleName(); private MainActivityContract.View mMainActivityView; private MainActivityInteractor mMainActivityInteractor;
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/MainActivityInteractor.java // public class MainActivityInteractor { // private PreferencesManager mPreferencesManager; // private Context mContext; // // public MainActivityInteractor(PreferencesManager preferencesManager) { // mPreferencesManager=preferencesManager; // mContext= MyApplication.getContext(); // } // // public void loadData(){ // if(mPreferencesManager.isFirstExecution()) { // launchDownloadService(); // ColorMap colorMap = new ColorMap(); // colorMap.generate(); // mPreferencesManager.saveColorMap(colorMap.getColorHashMap()); // mPreferencesManager.setFirstExecutionFalse(); // } // } // // private void launchDownloadService() { // Intent intent = new Intent(mContext, DownloadFarmacias.class); // mContext.startService(intent); // } // } // // Path: app/src/main/java/com/chernandezgil/farmacias/ui/adapter/PreferencesManager.java // public interface PreferencesManager { // // SharedPreferences getSharedPreferences(); // String getLocationKey(); // int retrieveRadioBusquedaFromSp(); // boolean isFirstExecution(); // void setFirstExecutionFalse(); // int getCurrentItemTabLayout(); // void setCurrentItemTabLayout(int currentItemTabLayout); // void saveLocation(Location location); // Location getLocation(); // int getRadio(); // void saveFavoriteList(List<Pharmacy> list); // List<Pharmacy> getFavorites(); // void saveColorMap(HashMap<String,Integer> colorMap); // HashMap<String,Integer> getColorMap(); // void saveStreet(String street); // String getStreet(); // // } // // Path: app/src/main/java/com/chernandezgil/farmacias/view/MainActivityContract.java // public interface MainActivityContract { // // interface View { // // } // interface Presenter<V> { // // void setView(V view); // void detachView(); // void onStart(); // // // } // } // Path: app/src/main/java/com/chernandezgil/farmacias/presenter/MainActivityPresenter.java import com.chernandezgil.farmacias.data.source.MainActivityInteractor; import com.chernandezgil.farmacias.ui.adapter.PreferencesManager; import com.chernandezgil.farmacias.view.MainActivityContract; package com.chernandezgil.farmacias.presenter; /** * Created by Carlos on 01/08/2016. */ public class MainActivityPresenter implements MainActivityContract.Presenter<MainActivityContract.View> { private static final String LOG_TAG=MainActivityPresenter.class.getSimpleName(); private MainActivityContract.View mMainActivityView; private MainActivityInteractor mMainActivityInteractor;
private PreferencesManager mPreferencesManager;
cahergil/Farmacias
app/src/main/java/com/chernandezgil/farmacias/data/LoaderProvider.java
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/DbContract.java // public class DbContract { // public static final String SCHEME ="content://"; // public static final String AUTHORITY = "com.chernandezgil.farmacias"; // public static final Uri BASE_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY); // public static final String PATH_FARMACIAS="farmacias"; // public static final String PATH_QUICK_SEARCH ="quick_search"; // public static final String PATH_FAVORITES= "favorites"; // // public static final class FarmaciasEntity implements BaseColumns { // // public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FARMACIAS).build(); // public static final Uri CONTENT_URI_QUICK_SEARCH =BASE_CONTENT_URI.buildUpon().appendPath(PATH_QUICK_SEARCH).build(); // public static final Uri CONTENT_URI_PATH_FAVORITES =BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVORITES).build(); // // public static final String CONTENT_TYPE = // "vnd.android.cursor.dir/" + AUTHORITY + "/" + PATH_FARMACIAS; // public static final String CONTENT_ITEM_TYPE = // "vnd.android.cursor.item/" + AUTHORITY + "/" + PATH_FARMACIAS; // // public static final String TABLE_NAME="farmacias"; // public static final String NAME="name"; // public static final String ADDRESS="address"; // public static final String LOCALITY="locality"; // public static final String PROVINCE="province"; // public static final String POSTAL_CODE="postal_code"; // public static final String PHONE="phone"; // public static final String LAT="lat"; // public static final String LON="lon"; // public static final String HOURS="hours"; // public static final String FAVORITE="favorite"; // // public static Uri buildFarmaciasUriByPhone(long id){ // // return ContentUris.withAppendedId(CONTENT_URI,id); // } // public static Uri buildFarmaciasUriByPhone(String phone) { // return CONTENT_URI.buildUpon().appendPath(phone).build(); // } // // public static Uri buildFarmaciasUriByName(String name) { // // return CONTENT_URI.buildUpon().appendPath(name).build(); // // } // public static Uri buildFarmaciasUriByNameQuickSearch(String name) { // return CONTENT_URI_QUICK_SEARCH.buildUpon().appendPath(name).build(); // } // public static Uri buildFavoritesUriByPhone(String phone) { // return CONTENT_URI_PATH_FAVORITES.buildUpon().appendPath(phone).build(); // } // // } // // }
import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.chernandezgil.farmacias.data.source.local.DbContract;
package com.chernandezgil.farmacias.data; /** * Created by Carlos on 03/08/2016. */ public class LoaderProvider { private Context mContext;
// Path: app/src/main/java/com/chernandezgil/farmacias/data/source/local/DbContract.java // public class DbContract { // public static final String SCHEME ="content://"; // public static final String AUTHORITY = "com.chernandezgil.farmacias"; // public static final Uri BASE_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY); // public static final String PATH_FARMACIAS="farmacias"; // public static final String PATH_QUICK_SEARCH ="quick_search"; // public static final String PATH_FAVORITES= "favorites"; // // public static final class FarmaciasEntity implements BaseColumns { // // public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FARMACIAS).build(); // public static final Uri CONTENT_URI_QUICK_SEARCH =BASE_CONTENT_URI.buildUpon().appendPath(PATH_QUICK_SEARCH).build(); // public static final Uri CONTENT_URI_PATH_FAVORITES =BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVORITES).build(); // // public static final String CONTENT_TYPE = // "vnd.android.cursor.dir/" + AUTHORITY + "/" + PATH_FARMACIAS; // public static final String CONTENT_ITEM_TYPE = // "vnd.android.cursor.item/" + AUTHORITY + "/" + PATH_FARMACIAS; // // public static final String TABLE_NAME="farmacias"; // public static final String NAME="name"; // public static final String ADDRESS="address"; // public static final String LOCALITY="locality"; // public static final String PROVINCE="province"; // public static final String POSTAL_CODE="postal_code"; // public static final String PHONE="phone"; // public static final String LAT="lat"; // public static final String LON="lon"; // public static final String HOURS="hours"; // public static final String FAVORITE="favorite"; // // public static Uri buildFarmaciasUriByPhone(long id){ // // return ContentUris.withAppendedId(CONTENT_URI,id); // } // public static Uri buildFarmaciasUriByPhone(String phone) { // return CONTENT_URI.buildUpon().appendPath(phone).build(); // } // // public static Uri buildFarmaciasUriByName(String name) { // // return CONTENT_URI.buildUpon().appendPath(name).build(); // // } // public static Uri buildFarmaciasUriByNameQuickSearch(String name) { // return CONTENT_URI_QUICK_SEARCH.buildUpon().appendPath(name).build(); // } // public static Uri buildFavoritesUriByPhone(String phone) { // return CONTENT_URI_PATH_FAVORITES.buildUpon().appendPath(phone).build(); // } // // } // // } // Path: app/src/main/java/com/chernandezgil/farmacias/data/LoaderProvider.java import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.chernandezgil.farmacias.data.source.local.DbContract; package com.chernandezgil.farmacias.data; /** * Created by Carlos on 03/08/2016. */ public class LoaderProvider { private Context mContext;
private String[] projectionSuggestion = new String[]{DbContract.FarmaciasEntity._ID,
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/upgrade/VersionSelectFragment.java
// Path: src/com/xiaomi/mitv/soundbarapp/provider/DataProvider.java // public class DataProvider { // private GalaxyProvider mProvider = new GalaxyProvider(); // public List<FirmwareVersion> listVersion(){ // return mProvider.listVersion(); // } // // public FirmwareVersion queryNewVersion(int localVersion){ // return mProvider.queryNewVersion(localVersion); // } // // public FaqData queryFaqList(){ // return mProvider.queryFaqList(); // } // // // //check if the app run in dev mode via the config file on SDCARD // private boolean isInDevMode(){ // return mProvider.isInDevMode(); // } // }
import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.xiaomi.mitv.content.FirmwareVersion; import com.xiaomi.mitv.soundbar.provider.SoundBarORM; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.provider.DataProvider; import java.util.ArrayList; import java.util.Collections; import java.util.List;
final ViewGroup item = (ViewGroup)inflater.inflate(R.layout.upgrade_version_item, parent, false); ViewHolder holder = new ViewHolder(); holder.mVersionName = (TextView)item.findViewById(R.id.version_name); holder.mVersionRelease = (TextView)item.findViewById(R.id.release_flag); holder.mVersionDesc = (TextView)mMainView.findViewById(R.id.version_desc); item.setTag(holder); convertView = item; } ViewHolder holder = (ViewHolder)convertView.getTag(); FirmwareVersion version = mVersions.get(position); holder.mVersionName.setText("版本:"+version.codeName + "(" + version.code + ")"); holder.mVersionRelease.setText(version.strFlag()); holder.mVersion = version; return convertView; } } private class VersionLoader extends AsyncTask<Void,Void,List<FirmwareVersion>>{ @Override protected void onPreExecute() { mMainView.findViewById(R.id.progress).setVisibility(View.VISIBLE); mMainView.findViewById(R.id.upgrade_execute).setVisibility(View.GONE); mMainView.findViewById(R.id.upgrade_version_list).setVisibility(View.GONE); mMainView.findViewById(R.id.version_desc).setVisibility(View.GONE); } @Override protected List<FirmwareVersion> doInBackground(Void... params) { List<FirmwareVersion> targets = new ArrayList<FirmwareVersion>();
// Path: src/com/xiaomi/mitv/soundbarapp/provider/DataProvider.java // public class DataProvider { // private GalaxyProvider mProvider = new GalaxyProvider(); // public List<FirmwareVersion> listVersion(){ // return mProvider.listVersion(); // } // // public FirmwareVersion queryNewVersion(int localVersion){ // return mProvider.queryNewVersion(localVersion); // } // // public FaqData queryFaqList(){ // return mProvider.queryFaqList(); // } // // // //check if the app run in dev mode via the config file on SDCARD // private boolean isInDevMode(){ // return mProvider.isInDevMode(); // } // } // Path: src/com/xiaomi/mitv/soundbarapp/upgrade/VersionSelectFragment.java import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.xiaomi.mitv.content.FirmwareVersion; import com.xiaomi.mitv.soundbar.provider.SoundBarORM; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.provider.DataProvider; import java.util.ArrayList; import java.util.Collections; import java.util.List; final ViewGroup item = (ViewGroup)inflater.inflate(R.layout.upgrade_version_item, parent, false); ViewHolder holder = new ViewHolder(); holder.mVersionName = (TextView)item.findViewById(R.id.version_name); holder.mVersionRelease = (TextView)item.findViewById(R.id.release_flag); holder.mVersionDesc = (TextView)mMainView.findViewById(R.id.version_desc); item.setTag(holder); convertView = item; } ViewHolder holder = (ViewHolder)convertView.getTag(); FirmwareVersion version = mVersions.get(position); holder.mVersionName.setText("版本:"+version.codeName + "(" + version.code + ")"); holder.mVersionRelease.setText(version.strFlag()); holder.mVersion = version; return convertView; } } private class VersionLoader extends AsyncTask<Void,Void,List<FirmwareVersion>>{ @Override protected void onPreExecute() { mMainView.findViewById(R.id.progress).setVisibility(View.VISIBLE); mMainView.findViewById(R.id.upgrade_execute).setVisibility(View.GONE); mMainView.findViewById(R.id.upgrade_version_list).setVisibility(View.GONE); mMainView.findViewById(R.id.version_desc).setVisibility(View.GONE); } @Override protected List<FirmwareVersion> doInBackground(Void... params) { List<FirmwareVersion> targets = new ArrayList<FirmwareVersion>();
List<FirmwareVersion> versions = new DataProvider().listVersion();
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/diagnosis/ViewWrapper.java
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/OrderedList.java // public class OrderedList<T extends Comparable<T>> extends ArrayList<T> { // @Override // public boolean add(T element){ // add(findPos(element), element); // return true; // } // // private int findPos(T element){ // int pos = size(); // for(int i=0; i<size(); i++){ // if(get(i).compareTo(element)>0){ // pos = i; // } // } // return pos; // } // }
import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.OrderedList; import org.w3c.dom.Text; import java.util.*;
public void hideAll(boolean hidden){ int flag = hidden?View.GONE: View.VISIBLE; mCategoryLayout.setVisibility(flag); mQuestionsLayout.setVisibility(flag); mFixViewLayout.setVisibility(flag); } public void showCategories(){ mTitleView.setText(R.string.main_entry_diagnose); mCategoryLayout.setVisibility(View.VISIBLE); mQuestionsLayout.setVisibility(View.GONE); mFixViewLayout.setVisibility(View.GONE); } public void showQuestions(String title){ if(!TextUtils.isEmpty(title)) mTitleView.setText(title); mCategoryLayout.setVisibility(View.GONE); mQuestionsLayout.setVisibility(View.VISIBLE); mFixViewLayout.setVisibility(View.GONE); } public void showFixSuggestion(String title){ if(!TextUtils.isEmpty(title)){ ((TextView)mFixActionBar.findViewById(R.id.action_bar_text)).setText(title); } mCategoryLayout.setVisibility(View.GONE); mQuestionsLayout.setVisibility(View.GONE); mFixViewLayout.setVisibility(View.VISIBLE); }
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/OrderedList.java // public class OrderedList<T extends Comparable<T>> extends ArrayList<T> { // @Override // public boolean add(T element){ // add(findPos(element), element); // return true; // } // // private int findPos(T element){ // int pos = size(); // for(int i=0; i<size(); i++){ // if(get(i).compareTo(element)>0){ // pos = i; // } // } // return pos; // } // } // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/ViewWrapper.java import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.OrderedList; import org.w3c.dom.Text; import java.util.*; public void hideAll(boolean hidden){ int flag = hidden?View.GONE: View.VISIBLE; mCategoryLayout.setVisibility(flag); mQuestionsLayout.setVisibility(flag); mFixViewLayout.setVisibility(flag); } public void showCategories(){ mTitleView.setText(R.string.main_entry_diagnose); mCategoryLayout.setVisibility(View.VISIBLE); mQuestionsLayout.setVisibility(View.GONE); mFixViewLayout.setVisibility(View.GONE); } public void showQuestions(String title){ if(!TextUtils.isEmpty(title)) mTitleView.setText(title); mCategoryLayout.setVisibility(View.GONE); mQuestionsLayout.setVisibility(View.VISIBLE); mFixViewLayout.setVisibility(View.GONE); } public void showFixSuggestion(String title){ if(!TextUtils.isEmpty(title)){ ((TextView)mFixActionBar.findViewById(R.id.action_bar_text)).setText(title); } mCategoryLayout.setVisibility(View.GONE); mQuestionsLayout.setVisibility(View.GONE); mFixViewLayout.setVisibility(View.VISIBLE); }
public void initCategory(HashMap<Integer, Entry> categories, View.OnClickListener listener){
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/diagnosis/ViewWrapper.java
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/OrderedList.java // public class OrderedList<T extends Comparable<T>> extends ArrayList<T> { // @Override // public boolean add(T element){ // add(findPos(element), element); // return true; // } // // private int findPos(T element){ // int pos = size(); // for(int i=0; i<size(); i++){ // if(get(i).compareTo(element)>0){ // pos = i; // } // } // return pos; // } // }
import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.OrderedList; import org.w3c.dom.Text; import java.util.*;
mFixViewLayout.setVisibility(View.GONE); } public void showFixSuggestion(String title){ if(!TextUtils.isEmpty(title)){ ((TextView)mFixActionBar.findViewById(R.id.action_bar_text)).setText(title); } mCategoryLayout.setVisibility(View.GONE); mQuestionsLayout.setVisibility(View.GONE); mFixViewLayout.setVisibility(View.VISIBLE); } public void initCategory(HashMap<Integer, Entry> categories, View.OnClickListener listener){ Set<Integer> keys = categories.keySet(); for(Integer id : keys){ View actionView = null; switch (id){ case 1: actionView = mMainView.findViewById(R.id.category_connection);break; case 2: actionView = mMainView.findViewById(R.id.category_no_sound);break; case 3: actionView = mMainView.findViewById(R.id.category_quality);break; case 4: actionView = mMainView.findViewById(R.id.category_upgrade);break; default:continue; } actionView.setTag(categories.get(id).getRoot()); actionView.setOnClickListener(listener); } mMainView.findViewById(R.id.category_faq).setOnClickListener(mFragment); mMainView.findViewById(R.id.category_bbs).setOnClickListener(mFragment); }
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/OrderedList.java // public class OrderedList<T extends Comparable<T>> extends ArrayList<T> { // @Override // public boolean add(T element){ // add(findPos(element), element); // return true; // } // // private int findPos(T element){ // int pos = size(); // for(int i=0; i<size(); i++){ // if(get(i).compareTo(element)>0){ // pos = i; // } // } // return pos; // } // } // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/ViewWrapper.java import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.OrderedList; import org.w3c.dom.Text; import java.util.*; mFixViewLayout.setVisibility(View.GONE); } public void showFixSuggestion(String title){ if(!TextUtils.isEmpty(title)){ ((TextView)mFixActionBar.findViewById(R.id.action_bar_text)).setText(title); } mCategoryLayout.setVisibility(View.GONE); mQuestionsLayout.setVisibility(View.GONE); mFixViewLayout.setVisibility(View.VISIBLE); } public void initCategory(HashMap<Integer, Entry> categories, View.OnClickListener listener){ Set<Integer> keys = categories.keySet(); for(Integer id : keys){ View actionView = null; switch (id){ case 1: actionView = mMainView.findViewById(R.id.category_connection);break; case 2: actionView = mMainView.findViewById(R.id.category_no_sound);break; case 3: actionView = mMainView.findViewById(R.id.category_quality);break; case 4: actionView = mMainView.findViewById(R.id.category_upgrade);break; default:continue; } actionView.setTag(categories.get(id).getRoot()); actionView.setOnClickListener(listener); } mMainView.findViewById(R.id.category_faq).setOnClickListener(mFragment); mMainView.findViewById(R.id.category_bbs).setOnClickListener(mFragment); }
public void setQuestions(List<Node> questions, View.OnClickListener listener){
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/player/PlayerService.java
// Path: src/com/xiaomi/mitv/soundbarapp/util/Worker.java // public class Worker implements Runnable { // private final Object mLock = new Object(); // private Looper mLooper; // // /** // * Creates a worker thread with the given name. The thread // * then runs a {@link android.os.Looper}. // * @param name A name for the new thread // */ // public Worker(String name) { // Thread t = new Thread(null, this, name); // t.setPriority(Thread.MIN_PRIORITY); // t.start(); // synchronized (mLock) { // while (mLooper == null) { // try { // mLock.wait(); // } catch (InterruptedException ex) { // } // } // } // } // // public Looper getLooper() { // return mLooper; // } // // public void run() { // synchronized (mLock) { // Looper.prepare(); // mLooper = Looper.myLooper(); // mLock.notifyAll(); // } // Looper.loop(); // } // // public void quit() { // mLooper.quit(); // } // }
import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.*; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.audiofx.AudioEffect; import android.net.Uri; import android.os.*; import android.provider.MediaStore; import android.util.Log; import android.widget.RemoteViews; import android.widget.Toast; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.util.Worker; import java.io.FileDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.util.Random; import java.util.Vector;
private long [] mAutoShuffleList = null; private long [] mPlayList = null; private int mPlayListLen = 0; private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE); private Cursor mCursor; private int mPlayPos = -1; private int mNextPlayPos = -1; private final Shuffler mRand = new Shuffler(); private int mOpenFailedCounter = 0; private final static int IDCOLIDX = 0; private final static int PODCASTCOLIDX = 8; private final static int BOOKMARKCOLIDX = 9; private BroadcastReceiver mUnmountReceiver = null; private PowerManager.WakeLock mWakeLock; private int mServiceStartId = -1; private boolean mServiceInUse = false; private boolean mIsSupposedToBePlaying = false; private boolean mQuietMode = false; private AudioManager mAudioManager; // used to track what type of audio focus loss caused the playback to pause private boolean mPausedByTransientLossOfFocus = false; private SharedPreferences mPreferences; // We use this to distinguish between different cards when saving/restoring playlists. // This will have to change if we want to support multiple simultaneous cards. private int mCardId; // interval after which we stop the service when idle private static final int IDLE_DELAY = 60000;
// Path: src/com/xiaomi/mitv/soundbarapp/util/Worker.java // public class Worker implements Runnable { // private final Object mLock = new Object(); // private Looper mLooper; // // /** // * Creates a worker thread with the given name. The thread // * then runs a {@link android.os.Looper}. // * @param name A name for the new thread // */ // public Worker(String name) { // Thread t = new Thread(null, this, name); // t.setPriority(Thread.MIN_PRIORITY); // t.start(); // synchronized (mLock) { // while (mLooper == null) { // try { // mLock.wait(); // } catch (InterruptedException ex) { // } // } // } // } // // public Looper getLooper() { // return mLooper; // } // // public void run() { // synchronized (mLock) { // Looper.prepare(); // mLooper = Looper.myLooper(); // mLock.notifyAll(); // } // Looper.loop(); // } // // public void quit() { // mLooper.quit(); // } // } // Path: src/com/xiaomi/mitv/soundbarapp/player/PlayerService.java import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.*; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.audiofx.AudioEffect; import android.net.Uri; import android.os.*; import android.provider.MediaStore; import android.util.Log; import android.widget.RemoteViews; import android.widget.Toast; import com.xiaomi.mitv.soundbarapp.R; import com.xiaomi.mitv.soundbarapp.util.Worker; import java.io.FileDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.util.Random; import java.util.Vector; private long [] mAutoShuffleList = null; private long [] mPlayList = null; private int mPlayListLen = 0; private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE); private Cursor mCursor; private int mPlayPos = -1; private int mNextPlayPos = -1; private final Shuffler mRand = new Shuffler(); private int mOpenFailedCounter = 0; private final static int IDCOLIDX = 0; private final static int PODCASTCOLIDX = 8; private final static int BOOKMARKCOLIDX = 9; private BroadcastReceiver mUnmountReceiver = null; private PowerManager.WakeLock mWakeLock; private int mServiceStartId = -1; private boolean mServiceInUse = false; private boolean mIsSupposedToBePlaying = false; private boolean mQuietMode = false; private AudioManager mAudioManager; // used to track what type of audio focus loss caused the playback to pause private boolean mPausedByTransientLossOfFocus = false; private SharedPreferences mPreferences; // We use this to distinguish between different cards when saving/restoring playlists. // This will have to change if we want to support multiple simultaneous cards. private int mCardId; // interval after which we stop the service when idle private static final int IDLE_DELAY = 60000;
private Worker mWorker;
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/upgrade/FirmwareManager.java
// Path: src/com/xiaomi/mitv/soundbarapp/provider/DataProvider.java // public class DataProvider { // private GalaxyProvider mProvider = new GalaxyProvider(); // public List<FirmwareVersion> listVersion(){ // return mProvider.listVersion(); // } // // public FirmwareVersion queryNewVersion(int localVersion){ // return mProvider.queryNewVersion(localVersion); // } // // public FaqData queryFaqList(){ // return mProvider.queryFaqList(); // } // // // //check if the app run in dev mode via the config file on SDCARD // private boolean isInDevMode(){ // return mProvider.isInDevMode(); // } // }
import android.content.Context; import android.util.Log; import com.xiaomi.mitv.content.FirmwareVersion; import com.xiaomi.mitv.soundbarapp.provider.DataProvider; import com.xiaomi.mitv.soundbar.provider.SoundBarORM; import java.io.*; import java.net.*;
package com.xiaomi.mitv.soundbarapp.upgrade; /** * Created by chenxuetong on 6/24/14. * the functions in this class are synchronized call */ public class FirmwareManager { private static final String TAG = "Soundbar_firmware"; private static final int BUFFER_SIZE = 1024; private Context mContext; public interface ProgressListener{ void onProgress(int total, int finished); } public FirmwareManager(Context context){ mContext = context; } //check if the firmware need to upgrade, if true return the Version info, //otherwise null public FirmwareVersion getNewFirmware(){
// Path: src/com/xiaomi/mitv/soundbarapp/provider/DataProvider.java // public class DataProvider { // private GalaxyProvider mProvider = new GalaxyProvider(); // public List<FirmwareVersion> listVersion(){ // return mProvider.listVersion(); // } // // public FirmwareVersion queryNewVersion(int localVersion){ // return mProvider.queryNewVersion(localVersion); // } // // public FaqData queryFaqList(){ // return mProvider.queryFaqList(); // } // // // //check if the app run in dev mode via the config file on SDCARD // private boolean isInDevMode(){ // return mProvider.isInDevMode(); // } // } // Path: src/com/xiaomi/mitv/soundbarapp/upgrade/FirmwareManager.java import android.content.Context; import android.util.Log; import com.xiaomi.mitv.content.FirmwareVersion; import com.xiaomi.mitv.soundbarapp.provider.DataProvider; import com.xiaomi.mitv.soundbar.provider.SoundBarORM; import java.io.*; import java.net.*; package com.xiaomi.mitv.soundbarapp.upgrade; /** * Created by chenxuetong on 6/24/14. * the functions in this class are synchronized call */ public class FirmwareManager { private static final String TAG = "Soundbar_firmware"; private static final int BUFFER_SIZE = 1024; private Context mContext; public interface ProgressListener{ void onProgress(int total, int finished); } public FirmwareManager(Context context){ mContext = context; } //check if the firmware need to upgrade, if true return the Version info, //otherwise null public FirmwareVersion getNewFirmware(){
DataProvider provider = new DataProvider();