/** * 累計給油量をTextViewへセットする * * @param carId int型、取得するクルマのCAR_ID */ private void setTotalAmountOfOil(int carId) { float totalFuel = dbman.getTotalOfRefuelById(db, carId); String unit = dbman.getVolumeUnitById(db, carId); tv_value_totalAmountOfOil.setText(String.valueOf(totalFuel)); tv_unit_totalAmountOfOil.setText(unit); }
/** * Main method. * * @param args */ public static void main(String[] args) throws Exception { String tempDirPath = new File(PlatformUtil.getSystemTempDir(), "empty_doc_db").toString(); String arg; for (int i = 0; i < args.length; i++) { arg = args[i]; if (i < args.length - 1 && "-d".equals(arg)) { tempDirPath = args[++i]; } } ConfigManager.makeConfigManager(); Logger.resetLogs(); MockLockssDaemon daemon = new MockLockssDaemon() {}; // Set the database log. System.setProperty( "derby.stream.error.file", new File(tempDirPath, "derby.log").getAbsolutePath()); Properties props = new Properties(); props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath); props.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath); ConfigurationUtil.setCurrentConfigFromProps(props); DbManager dbManager = new DbManager(true); daemon.setDbManager(dbManager); dbManager.initService(daemon); dbManager.startService(); dbManager.waitForThreadsToFinish(500); System.exit(0); }
public static boolean addComment(Comment comment) { ResultSet rs; try { Connection conn = DbManager.getConnection(); String sql = "INSERT INTO comment(user_Id , content , writtenTime , diagram_Id) VALUES(?,?,?,?);"; PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setInt(1, comment.getUserId()); pstmt.setString(2, comment.getContent()); pstmt.setString(3, comment.getCommentTime()); pstmt.setInt(4, comment.getDiagramId()); pstmt.executeUpdate(); // Get and set the auto-generated PK rs = pstmt.getGeneratedKeys(); if (rs.next()) { int newId = rs.getInt(1); comment.setCommentId(newId); } rs.close(); pstmt.close(); conn.close(); } catch (SQLException ex) { Logger.getLogger(CommentDAO.class.getName()).log(Level.SEVERE, null, ex); } return true; }
public static ArrayList<Comment> getComment(int diagram_id) { ArrayList<Comment> searchResult = new ArrayList<>(); try { Connection conn = DbManager.getConnection(); String sql = "SELECT * FROM comment where diagram_Id = ?;"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, diagram_id); ResultSet rs = pstmt.executeQuery(); // Initiate a list to get all returned comment objects and set attributes while (rs.next()) { Comment comt = new Comment(); comt.setCommentId(rs.getInt("comment_Id")); comt.setContent(rs.getString("content")); comt.setUserId(rs.getInt("user_Id")); comt.setDiagramId(rs.getInt("diagram_Id")); comt.setCommentTime(rs.getString("writtenTime")); searchResult.add(comt); } rs.close(); pstmt.close(); conn.close(); return searchResult; } catch (SQLException ex) { Logger.getLogger(CommentDAO.class.getName()).log(Level.SEVERE, null, ex); } return null; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rank); setTitle("Quiz Rank"); ListView list = (ListView) findViewById(R.id.listView); final DbManager db = new DbManager(this); ArrayList<String> array = db.getAllScores(); RankAdapter adapter2 = new RankAdapter(this, R.layout.row, array); /*ArrayAdapter<String> adapter2 = new ArrayAdapter<>( this, // The current context (this activity) android.R.layout.simple_list_item_1, // The name of the layout ID. array);*/ list.setAdapter(adapter2); }
public void initialize() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Error setting LookAndFeelClassName: " + e); } // create and initialize the connectivity dbManager = new DbManager(); dbManager.openConnection(); queryManager = new QueryManager(dbManager); }
private synchronized int handleDBData(String aSql, String[] aParams) { int result = DBValue.SUCCESS; if (null == mDbManager || null == aSql) { return DBValue.FAILURE; } mDbManager.beginTransaction(); if (mDbManager.execute(aSql, aParams) < 0) { result = DBValue.FAILURE; } if (DBValue.SUCCESS == result) { mDbManager.setTransactionSuccessful(); } mDbManager.endTransaction(); return result; }
public int selectCountDB(int aSelectType, String aParam) { int count = 0; Cursor cursor = null; String[] selectionArgs = {aParam + ""}; switch (aSelectType) { case DBValue.TYPE_SELECT_DAY_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_DAY_COUNT, null); break; case DBValue.TYPE_SELECT_PRE_DAY_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_PRE_DAY_COUNT, selectionArgs); break; case DBValue.TYPE_SELECT_TOTAL_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_TOTAL_COUNT, null); break; case DBValue.TYPE_SELECT_URL_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_URL_COUNT, null); break; case DBValue.TYPE_SELECT_DISLIKE_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_DISLIKE_COUNT, null); break; case DBValue.TYPE_SELECT_LIKE_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_LIKE_COUNT, null); break; case DBValue.TYPE_SELECT_DISLIKE_PACKAGE_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_DISLIKE_PACKAGE_COUNT, null); break; case DBValue.TYPE_SELECT_PACKAGE_INFO_COUNT: cursor = mDbManager.query(DBValue.SQL_SELECT_PACKAGE_INFO_COUNT, selectionArgs); break; default: break; } if (null == cursor) { return count; } cursor.moveToFirst(); count = cursor.getInt(0); cursor.close(); return count; }
public static boolean deleteComment(Comment comment) { try { Connection conn = DbManager.getConnection(); String sql = "DELETE FROM comment WHERE comment_Id = ? ;"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, comment.getCommentId()); pstmt.executeUpdate(); pstmt.close(); conn.close(); return true; } catch (SQLException ex) { Logger.getLogger(CommentDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; }
public static boolean updateComment(Comment comment) { try { Connection conn = DbManager.getConnection(); String sql = "UPDATE comment SET content = ? , writtenTime = ? WHERE comment_Id = ?;"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, comment.getContent()); pstmt.setString(2, comment.getCommentTime()); pstmt.setInt(3, comment.getCommentId()); pstmt.executeUpdate(); pstmt.close(); conn.close(); return true; } catch (SQLException ex) { Logger.getLogger(CommentDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; }
public static void menu2() { System.out.println("¿En qué tabla quieres añadir el elemento?"); System.out.println( "1.Trabajador \n" + "2.Aerolínea \n" + "3.Modelo \n" + "4.Pista \n" + "5.Billete \n" + "6.Pasajero \n" + "7.Equipaje \n" + "8.Terminal \n" + "9.Vuelo \n" + "10.Avión"); int a = sc.nextInt(); sc.nextLine(); switch (a) { case 1: System.out.println("¿A qué tripulación pertenece: "); String tripulacion = sc.nextLine(); System.out.println("Nombre del trabajador: "); String nombre = sc.nextLine(); System.out.println("Fecha de nacimiento (yyyy-MM-dd)"); String fechaNacimiento1 = sc.nextLine(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate p = LocalDate.parse(fechaNacimiento1, formatter); Date fechaNacimiento = Date.valueOf(p); System.out.println("Fecha inicio contrato (yyyy-MM-dd"); String fechaContrato1 = sc.nextLine(); LocalDate p2 = LocalDate.parse(fechaContrato1, formatter); Date fechaContrato = Date.valueOf(p2); Trabajador trabajador1 = new Trabajador(tripulacion, nombre, fechaNacimiento, fechaContrato); gestor.insertTablaTripulacion(trabajador1); case 2: } }
public Cursor selectDBData(int aSelectType, String aParam) { String[] selectionArgs = {aParam + ""}; switch (aSelectType) { case DBValue.TYPE_SELECT_PACKAGE_INFO: return mDbManager.query(DBValue.SQL_SELECT_PACKAGE_INFO, selectionArgs); case DBValue.TYPE_SELECT_FILTER_PACKAGE: return mDbManager.query(DBValue.SQL_SELECT_FILTERPKG_PACKAGENAME, selectionArgs); case DBValue.TYPE_SELECT_FILTERWORD_INFO: return mDbManager.query(DBValue.SQL_SELECT_FILTERWORD_INFO, selectionArgs); case DBValue.TYPE_SELECT_FILTERPKG_INFO: return mDbManager.query(DBValue.SQL_SELECT_FILTERPKG_INFO, null); case DBValue.TYPE_SELECT_DAILY_NOTI_INFO: return mDbManager.query(DBValue.SQL_SELECT_DAILY_NOTI_INFO, null); case DBValue.TYPE_SELECT_PACKAGE_NOTI_INFO: return mDbManager.query(DBValue.SQL_SELECT_PACKAGE_NOTI_COUNT, null); case DBValue.TYPE_SELECT_DISLIKE_PKG_INFO: return mDbManager.query(DBValue.SQL_SELECT_DISLIKE_PKG_INFO, null); case DBValue.TYPE_SELECT_NOTI_INFO: return mDbManager.query(DBValue.SQL_SELECT_NOTI_INFO, null); default: break; } return null; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); final BufferedWriter out = new BufferedWriter(resp.getWriter()); final String username = req.getParameter("loginUsername"); final String password = req.getParameter("loginPassword"); if (username == null || password == null) { out.write(LOGIN_FAIL_JSON); } else { try { final List<User> userList = DbManager.getUsers(false); User currentUser = null; for (User u : userList) { if (username.equals(u.getUsername())) { currentUser = u; } } if (currentUser != null && password.equals(currentUser.getPassword())) { /* Success! */ final HttpSession session = req.getSession(); session.setAttribute("user", currentUser); out.write("{ success: true, role: '" + currentUser.getRole().toString() + "' }"); } else { /* Fail! */ out.write(LOGIN_FAIL_JSON); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SQLException e) { throw new RuntimeException(e); } catch (NamingException e) { throw new RuntimeException(e); } } out.close(); }
// Open database connection public void open() throws SQLException { database = dbManager.getWritableDatabase(); }
public static void opcion1() { System.out.println("¿Quieres crear las tablas? (y/n)"); String crearTablas = sc.nextLine(); if (crearTablas.equalsIgnoreCase("y") || crearTablas.equalsIgnoreCase("s")) { gestor.createTablaModelo(); gestor.createTablaPista(); gestor.createTablaTripulacion(); } System.out.println( "¿Qué quieres hacer? \n" + "1.Añadir elemento \n" + "2.Ver tabla \n" + "3.Salir"); int opcion1 = Integer.parseInt(sc.nextLine()); switch (opcion1) { case 1: menu2(); /* // String estado = sc.nextLine(); System.out.println("Introduzca los datos de la pista:"); System.out.println("Estado:"); String estado = sc.nextLine(); System.out.println("AAAAAA:"+estado); System.out.println("Orientacion:"); String orientacion = sc.nextLine(); System.out.println("Longitud:"); int longitud = sc.nextInt(); Pista p1 = new Pista(estado, orientacion, longitud); gestor.insertTablaPista(p1); */ break; case 2: List<Trabajador> trabajador1 = gestor.selectTrabajador(); for (Trabajador trabajador : trabajador1) { System.out.println(trabajador.toString()); } /* List<Pista> listaPista = gestor.selectPista(); for (Pista pista : listaPista) { System.out.println(pista.toString()); } break; */ break; // menu3(); case 3: opcion1(); break; default: System.out.println("Opción no válida"); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow() .setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); setContentView(R.layout.activity_cageinfo); Intent intent = getIntent(); final String cage_id = intent.getStringExtra("id"); final DbManager dbm = ((MyApplication) getApplication()).getDbManager(); EditText editText = (EditText) findViewById(R.id.cagesn); editText.setText(intent.getStringExtra("sn")); Spinner statusSpinner = (Spinner) findViewById(R.id.status); statusSpinner.setAdapter( new ArrayAdapter<String>( this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.cage_status))); statusSpinner.setSelection(Integer.parseInt(intent.getStringExtra("status"))); statusSpinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (initing_) { initing_ = false; return; } dbm.updateCage(cage_id, (int) id); } @Override public void onNothingSelected(AdapterView<?> parent) {} }); List<Map<String, String>> group_data = new ArrayList<Map<String, String>>(); store_ = new ArrayList<List<Map<String, String>>>(); Map<String, String> group_info = new HashMap<String, String>(); List<Map<String, String>> children = dbm.getCageHistory(intent.getStringExtra("sn")); store_.add(children); group_info.put( "name", getResources().getString(R.string.txt_feed_record) + "(" + children.size() + ")"); group_data.add(group_info); ExpandableListView listView = (ExpandableListView) findViewById(R.id.history); adapter_ = new CageHistoryListAdapter( this, group_data, R.layout.expandablelist_group, new String[] {"name"}, new int[] {R.id.group_name}, store_, R.layout.expandablelist_item, new String[] {"dt", "stage"}, new int[] {R.id.text1, R.id.text2}, this); listView.setAdapter(adapter_); listView.expandGroup(0); }
/* (非 Javadoc) * @see android.app.Activity#onContextItemSelected(android.view.MenuItem) */ @Override public boolean onContextItemSelected(MenuItem item) { // TODO 自動生成されたメソッド・スタブ switch (item.getItemId()) { case R.id.ctxitem_edit_refuel_record: // 燃費記録を修正する処理 callEditMileage(currentRecordId, getCAR_ID(), getCAR_NAME()); break; case R.id.ctxitem_delete_refuel_record: // 燃費記録を削除する処理 DateManager dmngr = new DateManager(); Cursor record = dbman.getLUBRecordByRecordId(db, currentRecordId); final String refuelDate = dmngr.getISO8601Date(record.getDouble(1)); record.close(); AlertDialog.Builder adbuilder = new AlertDialog.Builder(this); adbuilder.setTitle(refuelDate); adbuilder.setMessage(getString(R.string.adbuilder_confirm_deletefuelrecord)); // [back]キーでキャンセルできるようにする adbuilder.setCancelable(true); // 「はい」ボタンの処理 adbuilder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int ret; ret = dbman.deleteLubsByCarId(db, getCAR_ID(), currentRecordId); Log.i( "onContextItemSelected", "Lub record has deleted, RECORD_ID = " + String.valueOf(currentRecordId)); ret = dbman.deleteCostsByCarId(db, getCAR_ID(), currentRecordId); Log.i( "onContextItemSelected", "Costs record has deleted, RECORD_ID = " + String.valueOf(currentRecordId)); // レコードを消したというトーストを表示する。 String line = refuelDate + getString(R.string.adbuilder_toast_deletefuel); Toast.makeText(getApplicationContext(), line, Toast.LENGTH_LONG).show(); // トータルのランニングコストと燃費を再計算する dbman.updateCurrentFuelMileageById(db, getCAR_ID()); dbman.updateCurrentRunningCostById(db, getCAR_ID()); // DBとCursorを閉じてActivityを再始動する closeCursor(cMileageList); closeDb(db); onResume(); } }); // 「キャンセル」ボタンの処理 // noなので「いいえ」かと思ったのだが....。 // 何もせずに終了する。 adbuilder.setNegativeButton( android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO 自動生成されたメソッド・スタブ } }); // AlertDialogを表示する adbuilder.show(); break; default: return super.onContextItemSelected(item); } return true; }
private void shutdown() { mainWindow.dispose(); dbManager.closeConnection(); }
public SearchResult[] advancedSearch( SearchConstraint[] constraints, int numResultsToSkip, int numResultsToReturn) { // Handle Lucene querying Map<String, String> luceneResult = new HashMap<String, String>(); try { String luceneQuery = buildLuceneQuery(constraints); System.out.println("lucene Query is " + luceneQuery); if (!luceneQuery.isEmpty()) { // Access the lucene index // Query Parser has no default field because // query will specify fields. String parent = new File("").getAbsolutePath(); File path = new File("C:\\Users\\Tony\\workspace\\ebayBidSearchService\\index-directory"); Directory index = FSDirectory.open(path); IndexReader reader = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(reader); parser = new QueryParser("content", new StandardAnalyzer()); // Execute Query Query q = parser.parse(luceneQuery); TopDocs hits = searcher.search(q, numResultsToReturn + numResultsToSkip); ScoreDoc[] sd = hits.scoreDocs; // Iterators for the hits(matches found) // And for resultsStore to return System.out.println("advanced search found " + sd.length + " results"); for (int i = numResultsToSkip; i < numResultsToReturn + numResultsToSkip && i < sd.length; i++) { int docId = sd[i].doc; Document doc = searcher.doc(docId); luceneResult.put(doc.get("id"), doc.get("name")); System.out.println("I found a item "); } } } catch (Exception e) { System.out.println(e); } // Handle SQL querying Map<String, String> sqlResult = new HashMap<String, String>(); Connection conn = null; try { String sqlQuery = buildSqlQuery(constraints); conn = DbManager.getConnection(true); Statement stmt = conn.createStatement(); // Execute query if (sqlQuery.length() > 0) { ResultSet items = stmt.executeQuery(sqlQuery); while (items.next()) { sqlResult.put(items.getString("Item_ID"), items.getString("Item_name")); } } } catch (Exception e) { System.out.println(e); } // Create the final SearchResult // Determine if we must do an intersection Set<String> itemIds; Map<String, String> result; if (sqlResult.isEmpty()) { itemIds = luceneResult.keySet(); result = luceneResult; } else if (luceneResult.isEmpty()) { itemIds = sqlResult.keySet(); result = sqlResult; } else { // In this case do an intersection of the keys itemIds = luceneResult.keySet(); itemIds.retainAll(sqlResult.keySet()); result = new HashMap<String, String>(); for (String item : luceneResult.keySet()) { result.put(item, luceneResult.get(item)); } for (String item : sqlResult.keySet()) { result.put(item, sqlResult.get(item)); } } // Add the keys and itemIds to the SearchResult array SearchResult[] resultstore = new SearchResult[itemIds.size()]; Iterator<String> i = itemIds.iterator(); int resultIndex = 0; while (i.hasNext()) { String itemId = i.next(); resultstore[resultIndex] = new SearchResult(itemId, result.get(itemId)); resultIndex++; } return resultstore; }
// Close database connection public void close() { dbManager.close(); }
public String getXMLDataForItemId(String itemId) { String xmlstore = ""; Connection conn = null; // Create a connection to the database try { // System.out.print("before connection"); // Connection to db manager conn = DbManager.getConnection(true); Statement statement = conn.createStatement(); // System.out.print("successfully connected to database"); // Geting the items ResultSet result = statement.executeQuery("SELECT * FROM Items " + "WHERE Items.Item_ID = " + itemId); result.first(); // Somethings in it if (result.getRow() != 0) { // System.out.println("I found a item " ); DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); DocumentBuilder b = fac.newDocumentBuilder(); org.w3c.dom.Document doc = b.newDocument(); // root element Element root = doc.createElement("Item"); root.setAttribute("ItemID", itemId); doc.appendChild(root); Element element_name = doc.createElement("Name"); element_name.appendChild(doc.createTextNode(replacespecial(result.getString("Item_name")))); root.appendChild(element_name); /* // Build Category Elements // Get the Categories Statement catstatement = conn.createStatement(); ResultSet catresult = catstatement.executeQuery("SELECT Category " + "FROM Category,Item_Category " + "WHERE Item_Category.Item_ID = " + itemId + " " + "AND Item_Category.Category_ID = Category.Category_ID"); Element category_element; while (catresult.next()) { category_element = doc.createElement("Category"); category_element.appendChild(doc.createTextNode(replacespecial(catresult.getString("Category")))); root.appendChild(category_element); } catresult.close(); catstatement.close();*/ // Build Item price elements if (result.getString("Currently") != null) { Element currently_element = doc.createElement("Currently"); currently_element.appendChild(doc.createTextNode("$" + result.getString("Currently"))); root.appendChild(currently_element); } if (result.getString("Buy_Price") != null) { Element buyprice_element = doc.createElement("Buy_Price"); buyprice_element.appendChild(doc.createTextNode("$" + result.getString("Buy_Price"))); root.appendChild(buyprice_element); } if (result.getString("First_Bid") != null) { Element start_element = doc.createElement("First_Bid"); start_element.appendChild(doc.createTextNode("$" + result.getString("First_Bid"))); root.appendChild(start_element); } // num bids if (result.getString("Number_of_Bids") != null) { Element numberbids_elements = doc.createElement("Number_of_Bids"); numberbids_elements.appendChild(doc.createTextNode(result.getString("Number_of_Bids"))); root.appendChild(numberbids_elements); } // description if (result.getString("Description") != null) { Element description_element = doc.createElement("Description"); description_element.appendChild( doc.createTextNode(replacespecial(result.getString("Description")))); root.appendChild(description_element); } /* // location Element location_element = doc.createElement("Location"); location_element.appendChild(doc.createTextNode((replacespecial(result.getString("Location"))))); root.appendChild(location_element); // country Element country_element = doc.createElement("Country"); country_element.appendChild(doc.createTextNode((replacespecial(result.getString("Country"))))); root.appendChild(country_element); // started Element started_elem = doc.createElement("Started"); started_elem.appendChild(doc.createTextNode(convertDate(result.getString("Started"), "yyyy-MM-dd HH:mm:ss", "MMM-dd-yy HH:mm:ss"))); root.appendChild(started_elem); // ends Element ends_element = doc.createElement("Ends"); ends_element.appendChild(doc.createTextNode(convertDate(result.getString("Ends"), "yyyy-MM-dd HH:mm:ss", "MMM-dd-yy HH:mm:ss"))); root.appendChild(ends_element);*/ /* // Build Bid Elements Statement bidstatement = conn.createStatement(); ResultSet bidresult = bidstatement.executeQuery("SELECT * " + "FROM Auctions, AuctionUser " + "WHERE Auctions.Item_Id = " + itemId + " " + "AND Auctions.User_ID = AuctionUser.User_ID"); Element bids_element = doc.createElement("Bids"); while (bidresult.next()) { try { Element bid_element = doc.createElement("Bid"); Element bidder_element = doc.createElement("Bidder"); bidder_element.setAttribute("UserID", replacespecial(bidresult.getString("User_ID"))); // bidder_element.setAttribute("Rating", bidresult.getString("Rating")); // Add Location and Country elements if they aren't NULL if (!bidresult.getString("Location").equals("")) { Element location_element = doc.createElement("Location"); location_element.appendChild(doc.createTextNode((replacespecial(bidresult.getString("Location"))))); bidder_element.appendChild(location_element); } if (!bidresult.getString("Country").equals("")) { Element country_element = doc.createElement("Country"); country_element.appendChild(doc.createTextNode((replacespecial(bidresult.getString("Country"))))); bidder_element.appendChild(country_element); } bid_element.appendChild(bidder_element); // time Element time_element = doc.createElement("Time"); time_element.appendChild(doc.createTextNode(convertDate(bidresult.getString("Bid_Time"), "yyyy-MM-dd HH:mm:ss", "MMM-dd-yy HH:mm:ss"))); bid_element.appendChild(time_element); // amount Element amount_element = doc.createElement("Amount"); amount_element.appendChild(doc.createTextNode(bidresult.getString("Bid_Time"))); bid_element.appendChild(amount_element); bids_element.appendChild(bid_element); } catch (SQLException e) { System.out.println(e); } } root.appendChild(bids_element); bidresult.close(); bidstatement.close();*/ /* // Get the Seller data Statement sellstatement = conn.createStatement(); ResultSet sellres = sellstatement.executeQuery("SELECT User_ID, Rating, Location, Country " + "FROM Items, AuctionUser " + "WHERE Items.Item_ID" + " = " + itemId + " " + "AND Items.Seller_Id = AuctionUser.User_ID"); sellres.first(); // seller Element sellerElem = doc.createElement("Seller"); sellerElem.setAttribute("UserID", (replacespecial(sellres.getString("UserID")))); sellerElem.setAttribute("Rating", sellres.getString("Rating")); root.appendChild(sellerElem); sellres.close(); sellstatement.close();*/ // Write the XML TransformerFactory newfactory = TransformerFactory.newInstance(); Transformer transform = newfactory.newTransformer(); DOMSource source = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult res = new StreamResult(writer); transform.setOutputProperty(OutputKeys.INDENT, "yes"); transform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transform.transform(source, res); xmlstore = writer.toString(); xmlstore = replacespecial1(xmlstore); } result.close(); statement.close(); conn.close(); } catch (SQLException e) { System.out.println(e); } catch (ParserConfigurationException e) { System.out.println("oops"); } catch (TransformerException e) { System.out.println("oops"); } return xmlstore; }
@Override public void start() throws IOException { if (_log.isInfoEnabled()) { _log.info("Starting DB service..."); } // Suppress Sonar violation of Lazy initialization of static fields should be synchronized // start() method will be only called one time when startup dbsvc, so it's safe to ignore sonar // violation instance = this; // NOSONAR ("squid:S2444") if (backCompatPreYoda) { _log.info( "Pre-yoda back compatible flag detected. Initialize local keystore/truststore for Cassandra native encryption"); initKeystoreAndTruststore(); _schemaUtil.setBackCompatPreYoda(true); } System.setProperty("cassandra.config", _config); System.setProperty("cassandra.config.loader", CassandraConfigLoader.class.getName()); // Set to false to clear all gossip state for the node on restart. // // We encounter a weird Cassandra grossip issue(COP-19246) - some nodes are missing from gossip // when rebooting the entire cluster simultaneously. Critical Gossip // fields(ApplicationState.STATUS, ApplicationState.TOKENS) // are not synchronized during handshaking. It looks like some problem caused by incorrect // gossip version/generation // at system local table. So add this option to cleanup local gossip state during reboot // // Make sure add-vdc/add-standby passed when you would remove this option in the future. // // We need make sure majority local nodes are added as seed nodes. Otherwise cassandra may not // see other nodes if it loses // connection to other sites System.setProperty("cassandra.load_ring_state", "false"); // Nodes in new data center should not auto-bootstrap. // See // https://docs.datastax.com/en/cassandra/2.0/cassandra/operations/ops_add_dc_to_cluster_t.html if (_schemaUtil.isStandby()) { System.setProperty("cassandra.auto_bootstrap", "false"); } InterProcessLock lock = null; Configuration config = null; StartupMode mode = null; try { // we use this lock to discourage more than one node bootstrapping / joining at the same time // Cassandra can handle this but it's generally not recommended to make changes to schema // concurrently lock = getLock(getSchemaLockName()); config = checkConfiguration(); checkGlobalConfiguration(); checkVersionedConfiguration(); removeStaleConfiguration(); mode = checkStartupMode(config); _log.info("Current startup mode is {}", mode); // Check if service is allowed to get started by querying db offline info to avoid bringing // back stale data. // Skipping hibernate mode for node recovery procedure to recover the overdue node. int nodeCount = ((CoordinatorClientImpl) _coordinator).getNodeCount(); if (nodeCount != 1 && mode.type != StartupMode.StartupModeType.HIBERNATE_MODE) { checkDBOfflineInfo(); } // this call causes instantiation of a seed provider instance, so the check*Configuration // calls must be preceed it removeCassandraSavedCaches(); mode.onPreStart(); if (_jmxServer != null) { _jmxServer.start(); System.setProperty( "com.sun.management.jmxremote.port", Integer.toString(_jmxServer.getPort())); } _service = new CassandraDaemon(); _service.init(null); _service.start(); cassandraInitialized = true; mode.onPostStart(); } catch (Exception e) { if (mode != null && mode.type == StartupMode.StartupModeType.HIBERNATE_MODE) { printRecoveryWorkAround(e); } _log.error("e=", e); throw new IllegalStateException(e); } finally { if (lock != null) { try { lock.release(); } catch (Exception ignore) { _log.debug("lock release failed"); } } } if (config.getConfig(DbConfigConstants.JOINED) == null) { config.setConfig(DbConfigConstants.JOINED, Boolean.TRUE.toString()); _coordinator.persistServiceConfiguration(_coordinator.getSiteId(), config); } _statusChecker.waitForAllNodesJoined(); _svcBeacon.start(); if (backCompatPreYoda) { _log.info("Enable duplicated beacon in global area during pre-yoda upgrade"); startDupBeacon(); } setDbInitializedFlag(); setDbConfigInitDone(); _dbClient.start(); if (_schemaUtil.isStandby()) { String localDataRevision = getLocalDataRevision(); if (localDataRevision != null) { _schemaUtil.checkDataRevision(localDataRevision); } } // Setup the vdc information, so that login enabled before migration if (!isGeoDbsvc()) { _schemaUtil.checkAndSetupBootStrapInfo(_dbClient); } dbMgr.init(); if (_handler.run()) { // Setup the bootstrap info root tenant, if root tenant migrated from local db, then skip it if (isGeoDbsvc()) { _schemaUtil.checkAndSetupBootStrapInfo(_dbClient); } else { _schemaUtil.checkAndInitStorageSystemTypes(_dbClient); } startBackgroundTasks(); _log.info("DB service started"); } else { _log.error("DB migration failed. Skipping starting background tasks."); } }
/* (非 Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); db = dbman.getReadableDatabase(); hasRecord = dbman.hasLubRecords(db, getCAR_ID()); // プリファレンスのSortOrderの値を読み出し、invertOrderに反映する。 boolean invertOrder = getMileageOrder(); // 画面幅を取得 int displayWidth = getWindowManager().getDefaultDisplay().getWidth(); // ボタン幅の修正 btn_add_mileage.setWidth(displayWidth / 2); btn_show_stats.setWidth(displayWidth / 2); // 各種単位の取得 priceUnit = dbman.getPriceUnitById(db, getCAR_ID()); distanceUnit = dbman.getDistanceUnitById(db, getCAR_ID()); volumeUnit = dbman.getVolumeUnitById(db, getCAR_ID()); cMileageList = dbman.getRefuelRecordsById(db, getCAR_ID(), invertOrder); // Cursorのレコード数に応じ、「統計を表示」ボタンをロックする処理 if (cMileageList.getCount() == 0) { btn_show_stats.setEnabled(false); } else { btn_show_stats.setEnabled(true); } String[] from = { // "_id", "DATE_OF_REFUEL", "LUB_AMOUNT", "VOLUMEUNIT" }; int[] to = { // R.id.tv_value_number_refuel, R.id.tv_value_dateOfRefuel, R.id.tv_value_amountOfOil, R.id.tv_unit_amountOfOil }; SimpleCursorAdapter sca = new SimpleCursorAdapter( getApplicationContext(), R.layout.listviewelemnt_mileagelist, cMileageList, from, to); lv_mileagelist.setAdapter(sca); // ListViewの要素を長押しした時のコンテキストメニューのリスナーをセット registerForContextMenu(lv_mileagelist); // ListViewの要素をクリックしたときのリスナーを宣言する // implementしてないので匿名メソッド lv_mileagelist.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // 取得したCursorから給油記録の詳細を取得する cLvRow = (Cursor) lv_mileagelist.getItemAtPosition(position); for (int i = 0; i < cLvRow.getColumnCount(); i++) { Log.i( "onItemClick", "name of Column Index " + String.valueOf(i) + ":" + cLvRow.getColumnName(i) + " value = " + cLvRow.getString(i)); } int rowId = Integer.parseInt(cLvRow.getString(cLvRow.getColumnIndex("_id"))); Log.d("onItemClick", "rowid is " + String.valueOf(rowId)); // 給油記録の元ネタをDBから取得する Cursor cRefuelRecord = dbman.getRefuelRecordById(db, getCAR_ID(), rowId); Log.d("onItemClick", "returned rows = " + cRefuelRecord.getCount()); for (int i = 0; i < cRefuelRecord.getColumnCount(); i++) { Log.i( "onItemClick", "name of Column Index " + String.valueOf(i) + ":" + cRefuelRecord.getColumnName(i) + " value = " + cRefuelRecord.getString(i)); } // AlertDialogに差し込むテキストの生成 // 値の取得:計算用 double dblDistance = cRefuelRecord.getDouble(5); // 走行距離 double dblOilAmount = cRefuelRecord.getDouble(3); // 給油量 double dblUnitprice = cRefuelRecord.getDouble(4); // 給油単価 // 給油時の燃費 double dblMileage = dblDistance / dblOilAmount; BigDecimal bd1 = new BigDecimal(dblMileage); String strMileage = String.valueOf(bd1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); // 給油時のランニングコスト double dblRunning = dblOilAmount * dblUnitprice / dblDistance; BigDecimal bd2 = new BigDecimal(dblRunning); String strRunningCost = String.valueOf(bd2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); // 値の取得 String strRefuelDate = cLvRow.getString(1); // 給油日時 String strDistance = String.valueOf(dblDistance); // 走行距離 String strOilAmount = String.valueOf(dblOilAmount); // 給油量 String strUnitPrice = String.valueOf(dblUnitprice); // 給油単価 // AlertDialog内にセットするテキストの生成 String adtext = getString(R.string.label_dateOfRefuel) + " : " + strRefuelDate + "\n" + getString(R.string.label_odometer) + " : " + strDistance + " " + distanceUnit + "\n" + getString(R.string.label_amountOfOil) + " : " + strOilAmount + " " + volumeUnit + "\n" + getString(R.string.label_unitPrice) + " : " + strUnitPrice + " " + priceUnit + "\n" + getString(R.string.label_fuelmileage) + strMileage + " " + distanceUnit + "/" + volumeUnit + "\n" + getString(R.string.label_runningcost) + strRunningCost + " " + priceUnit + "/" + distanceUnit; adbuilder.setMessage(adtext); // AlertDialogを表示する adbuilder.create(); adbuilder.show(); cRefuelRecord.close(); } }); btn_add_mileage.setOnClickListener(this); btn_show_stats.setOnClickListener(this); // 燃費とランニングコストの値を差し込む double txtMileage = dbman.getCurrentMileageById(db, getCAR_ID()); double txtRunning = dbman.getCurrentRunningCostById(db, getCAR_ID()); tv_value_FuelMileage2.setText(String.valueOf(txtMileage)); tv_value_RunningCosts2.setText(String.valueOf(txtRunning)); // 燃費とランニングコストの単位を差し込む tv_unit_fuelMileage2.setText(distanceUnit + "/" + volumeUnit); tv_unit_runningCosts2.setText(priceUnit + "/" + distanceUnit); setTotalAmountOfOil(getCAR_ID()); }