Newbie mistake

Hello,
I am new to the cryptography stuff, so please excuse me if I have made any stupid mistakes. I have this simple program that does encryption and decryption. It is supposed to print out the encrypted string as well as the key used. These values will then go into the XML configuration file. When the other application reads this config file, it is supposed to decrypt the stuff. I have a few problems actually.
1. If I run this program, it works sometimes and sometimes it gives me an exception. The strange part is that the input is the same. I run the program 2 times within 3 mins and I get this unexpected behavior.
2. When it does work, the decrypted value displayed is not the same as the input.
Please can someone help and tell me what my stupid mistake is.
You can run it as
java -cp .;<PATH_TO_BASE64_ENCODER>.jar SecurityService <VALUE_TO_ENCRYPT_AND_DECRYPT>
Here is my complete program
import java.io.UnsupportedEncodingException;
import java.security.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import com.Ostermiller.util.Base64;
public class SecurityService {
protected final String DEFAULT_ALGORITHM = "DESede";
protected final String DEFAULT_MODE = "NONE";
protected final String DEFAULT_PADDING = "NoPadding";
public SecurityService() {
* This method will encrypt the value passed to it using the algorithm provided by the user.
* The default algorightm is DESede with no mode or padding. Only if the encoding algorithm is
* specified will the mode and padding be read. Since these two values make most sense with a
* particular algorithm only, there is no reason to read these values if no algorithm is specified.
* @param anEncodingAlgorithm The algorithm to use to encrypt the value. eg. DES, DESede, RSA
* @param aMode The mode to use along with the encryption algorithm. eg. CBC, CFB
* @param aPadding The type of padding to use.
* @param aValueToEncode The value to encode.
* @return The encrypted value and the key separated using ...
public String encrypt(String anEncodingAlgorithm,
String aMode,
String aPadding,
String aValueToEncode)
throws NoSuchAlgorithmException, Exception
String currentAlgorithm = this.DEFAULT_ALGORITHM;
try
StringBuffer transformationBuffer = new StringBuffer();
if ((null != anEncodingAlgorithm) && (0 != anEncodingAlgorithm.trim().length()))
transformationBuffer.append(anEncodingAlgorithm);
currentAlgorithm = anEncodingAlgorithm;
if ((null != aMode) && (0 != aMode.trim().length()))
transformationBuffer.append("/" + aMode);
else
transformationBuffer.append("/" + DEFAULT_MODE);
if ((null != aPadding) && (0 != aPadding.trim().length()))
transformationBuffer.append("/" + aPadding);
else
transformationBuffer.append("/" + DEFAULT_PADDING);
else
transformationBuffer.append(DEFAULT_ALGORITHM);
System.out.println("The transformation to use is : " + transformationBuffer.toString());
//STEP 1: Create the Cipher object that will be used to encrypt the value
Cipher cipherObject = Cipher.getInstance(transformationBuffer.toString());
//STEP 2: Obtain an instance of the KeyGenerator to generate a Key.
KeyGenerator keyGenerator = KeyGenerator.getInstance(currentAlgorithm);
keyGenerator.init(112);
//STEP 3: Generate the secret key
SecretKey keyToUse = keyGenerator.generateKey();
System.out.println("During encryption, the encoded secret key is : " + keyToUse.getEncoded());
System.out.println("During encryption, the secret key format is : " + keyToUse.getFormat());
//STEP 4: Initialize the Cipher object so that it is in the Encryption mode.
cipherObject.init(Cipher.ENCRYPT_MODE, keyToUse);
//STEP 5: Encrypt the value
byte[] encryptedData = cipherObject.doFinal(aValueToEncode.getBytes());
//STEP 6: The encrypted data is in the form of bytes and has no structure. In order to
//convert it to a String, it must be base64 encoded first.
String base64EncryptedString = new String(Base64.encode(encryptedData));
System.out.println("During encryption, the base64 encrypted value is : " + base64EncryptedString);
//STEP 7: Create the buffer to hold the delimited encrypted value and key
StringBuffer resultBuffer = new StringBuffer(base64EncryptedString);
resultBuffer.append("...");
//STEP 8: Convert the SecretKey to a DESede key
SecretKeyFactory desEdeFactory = SecretKeyFactory.getInstance("DESede");
DESedeKeySpec desEdeSpec = (DESedeKeySpec)desEdeFactory.getKeySpec(keyToUse, javax.crypto.spec.DESedeKeySpec.class);
byte[] rawDesEdeKey = desEdeSpec.getKey();
byte[] rawDesEdeKey = keyToUse.getEncoded();
String keyInBase64Format = new String(Base64.encode(rawDesEdeKey));
resultBuffer.append(keyInBase64Format);
System.out.println("During encryption, the secret key is : " + keyInBase64Format);
return resultBuffer.toString();
catch(NoSuchAlgorithmException noSuchAlgorithm)
throw noSuchAlgorithm;
catch(NoSuchPaddingException noSuchPadding)
throw noSuchPadding;
catch(Exception e)
throw e;
public String decrypt(String aDecodingAlgorithm,
String aMode,
String aPadding,
String akeyToUseToDecode,
String aValueToDecode)
throws NoSuchAlgorithmException, Exception
String currentAlgorithm = this.DEFAULT_ALGORITHM;
try
StringBuffer transformationBuffer = new StringBuffer();
if ((null != aDecodingAlgorithm) && (0 != aDecodingAlgorithm.trim().length()))
transformationBuffer.append(aDecodingAlgorithm);
currentAlgorithm = aDecodingAlgorithm;
if ((null != aMode) && (0 != aMode.trim().length()))
transformationBuffer.append("/" + aMode);
else
transformationBuffer.append("/" + DEFAULT_MODE);
if ((null != aPadding) && (0 != aPadding.trim().length()))
transformationBuffer.append("/" + aPadding);
else
transformationBuffer.append("/" + DEFAULT_PADDING);
else
transformationBuffer.append(DEFAULT_ALGORITHM);
System.out.println("Decrypting : The transformation to use is : " + transformationBuffer.toString());
System.out.println("Decrypting : The algorithm to use is : " + currentAlgorithm);
//STEP 1: Create an instance of the Cipher object using the transformation.
Cipher cipherObject = Cipher.getInstance(transformationBuffer.toString());
//STEP 2: Convert the DESede key to a secret key
SecretKeyFactory desEdeFactory = SecretKeyFactory.getInstance("DESede");
//Decode the base64 encoded key to it's raw format first
byte[] rawKey = Base64.decodeToBytes(akeyToUseToDecode);
DESedeKeySpec keyspec = new DESedeKeySpec(rawKey);
// SecretKeySpec keyspec = new SecretKeySpec(rawKey, currentAlgorithm);
System.out.println("Decrypting : Key Spec created...");
SecretKey keyToUse = desEdeFactory.generateSecret(keyspec);
cipherObject.init(Cipher.DECRYPT_MODE, keyToUse);
byte[] decryptedData = cipherObject.doFinal(Base64.decodeToBytes(aValueToDecode));
StringBuffer resultBuffer = new StringBuffer(Base64.encode(decryptedData).toString());
System.out.println("Decrypting: The decrypted value is : " + Base64.decode(resultBuffer.toString()));
resultBuffer.append("...");
// resultBuffer.append(Base64.encode(keyspec.getEncoded()).toString());
resultBuffer.append(Base64.encode(keyspec.getKey()).toString());
return resultBuffer.toString();
catch(NoSuchAlgorithmException noSuchAlgorithm)
throw noSuchAlgorithm;
catch(NoSuchPaddingException noSuchPadding)
throw noSuchPadding;
catch(Exception e)
throw e;
public static void main(String args[])
SecurityService testSecurityService = new SecurityService();
if (args.length <= 0 )
args[0] = "Amitabh";
if (args.length <= 0 )
System.out.println("USAGE: java com.petris.security.SecurityService valueToEncrypt");
System.exit(1);
try
String encryptedValueAndKey = testSecurityService.encrypt(null, null, null,
args[0]);
int indexOfDelimiter = encryptedValueAndKey.indexOf("...");
String encryptedValue = encryptedValueAndKey.substring(0, indexOfDelimiter);
String key = encryptedValueAndKey.substring(indexOfDelimiter + 3);
System.out.println("The value to encrypt is : " + args[0]);
System.out.println("The encrypted value is : " + encryptedValue);
System.out.println("The key used is : " + key);
String decryptedValueAndKey = testSecurityService.decrypt(null, null, null,
key, encryptedValue);
indexOfDelimiter = decryptedValueAndKey.indexOf("...");
String decryptedValue = decryptedValueAndKey.substring(0, indexOfDelimiter);
key = decryptedValueAndKey.substring(indexOfDelimiter + 3);
System.out.println("The complete decrypted string is : " + decryptedValueAndKey);
System.out.println("The decrypted value is : " + Base64.decode(decryptedValue));
System.out.println("The key used is : " + key);
catch(Exception e)
System.out.println(e.getMessage());
e.printStackTrace();
}

1. If I run this program, it works sometimes and
sometimes it gives me an exception. The strange part
is that the input is the same. I run the program 2
times within 3 mins and I get this unexpected
behavior.
Exceptions are your friends so listen to what they say! What exception and which line?

Similar Messages

  • Newbie mistake, but I can't find it, help appreciated on XML import

    I'm sure I'm making a newbie mistake but I can't find it. If someone could tell me what I'm doing wrong I would appreciate it.
    Step one works (i'm logged as user xdb on the database):
    SQL*Plus: Release 10.1.0.2.0 - Production on Wed Dec 20 13:47:53 2006
    Copyright (c) 1982, 2004, Oracle. All rights reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.2.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    SQL> Declare
    2 ignore boolean;
    3 begin
    4 ignore :=dbms_xdb.createFolder('/datamart');
    5 ignore :=dbms_xdb.createFolder('/datamart/CustomerCare');
    6 ignore :=dbms_xdb.createFolder('/datamart/CustomerCare/xsd');
    7 ignore :=dbms_xdb.createFolder('/datamart/CustomerCare/xml');
    8 commit ;
    9 end;
    10 /
    PL/SQL procedure successfully completed.
    Step two works, where I drag and drop via Windows Explorer my xsd file into http://d01db:8085/datamart/CustomerCare/xsd. It has a size of about 7k or so. Again, when connecting to the respository with Windows Explorer, I'm logging in as xdb.
    Step three works, where I register the schema that I just put into the XML repository. Still logged into SQLPlus as xdb.
    SQL> begin
    2 dbms_xmlschema.registerURI
    3 (schemaURL => 'http://xmlns.oracle.com/xdb/Steton.xsd'
    4 ,schemaDocURI => '/datamart/CustomerCare/xsd/Steton.xsd'
    5 ,genTables => true
    6 ) ;
    7 end;
    8 /
    PL/SQL procedure successfully completed.
    SQL> describe STETONAUDITRESULTS;
    Name Null? Type
    TABLE of SYS.XMLTYPE(XMLSchema "http://xmlns.oracle.com/xdb/Steton.xsd" Element "StetonAuditResults"
    SQL>
    By the way, here is the schema:
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb" id="StetonAuditResults" xdb:storeVarrayAsTable="true">
         <xs:element name="StetonAuditResults" xdb:defaultTable="STETONAUDITRESULTS">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="Control">
                             <xs:complexType>
                                  <xs:sequence>
                                       <xs:element name="ResultCount" type="xs:int"/>
                                  </xs:sequence>
                             </xs:complexType>
                        </xs:element>
                        <xs:element name="AuditResults">
                             <xs:complexType>
                                  <xs:choice maxOccurs="unbounded">
                                       <xs:element name="AuditResult">
                                            <xs:complexType>
                                                 <xs:sequence>
                                                      <xs:element name="AuditResultGlobalID" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditGlobalID" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditName" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AccountID" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AccountName" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditorID" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditorName" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AcctRepName" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditTypeID" type="xs:int" minOccurs="0"/>
                                                      <xs:element name="AuditTypeName" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="DivisionID" type="xs:int" minOccurs="0"/>
                                                      <xs:element name="FaxBack" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="EMailBack" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="StartDateLocal" type="xs:dateTime" minOccurs="0"/>
                                                      <xs:element name="StartDateUTC" type="xs:dateTime" minOccurs="0"/>
                                                      <xs:element name="EndDate" type="xs:dateTime" minOccurs="0"/>
                                                      <xs:element name="UploadDate" type="xs:dateTime" minOccurs="0"/>
                                                      <xs:element name="ProcessDate" type="xs:dateTime" minOccurs="0"/>
                                                      <xs:element name="ApplicationVersion" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditResultNotes" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="AuditorSignature" type="xs:base64Binary" minOccurs="0"/>
                                                      <xs:element name="AcctRepSignature" type="xs:base64Binary" minOccurs="0"/>
                                                      <xs:element name="InitialAuditResultGlobalID" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="RecordType" type="xs:string" minOccurs="0"/>
                                                      <xs:element name="ModifiedDate" type="xs:dateTime" minOccurs="0"/>
                                                      <xs:element name="CategoryResults">
                                                           <xs:complexType>
                                                                <xs:choice minOccurs="0" maxOccurs="unbounded">
                                                                     <xs:element name="CategoryResult">
                                                                          <xs:complexType>
                                                                               <xs:sequence>
                                                                                    <xs:element name="AuditResultGlobalID" type="xs:string"/>
                                                                                    <xs:element name="CategoryGlobalID" type="xs:string" minOccurs="0"/>
                                                                                    <xs:element name="CategoryName" type="xs:string" minOccurs="0"/>
                                                                                    <xs:element name="CategoryReference" type="xs:string" minOccurs="0"/>
                                                                                    <xs:element name="CategoryResultNotes" type="xs:string" minOccurs="0"/>
                                                                                    <xs:element name="QuestionResults">
                                                                                         <xs:complexType>
                                                                                              <xs:choice minOccurs="0" maxOccurs="unbounded">
                                                                                                   <xs:element name="QuestionResult">
                                                                                                        <xs:complexType>
                                                                                                             <xs:sequence>
                                                                                                                  <xs:element name="AuditResultGlobalID" type="xs:string"/>
                                                                                                                  <xs:element name="CategoryGlobalID" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="QuestionGlobalID" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="QuestionText" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="QuestionReference" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="ChoiceGlobalID" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="ChoiceText" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="ChoicePointsPossible" type="xs:double" minOccurs="0"/>
                                                                                                                  <xs:element name="ChoicePointsEarned" type="xs:double" minOccurs="0"/>
                                                                                                                  <xs:element name="QuestionResultNotes" type="xs:string" minOccurs="0"/>
                                                                                                                  <xs:element name="QuestionCommentResults">
                                                                                                                       <xs:complexType>
                                                                                                                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                                                                                                                 <xs:element name="QuestionCommentResult">
                                                                                                                                      <xs:complexType>
                                                                                                                                           <xs:sequence>
                                                                                                                                                <xs:element name="AuditResultGlobalID" type="xs:string"/>
                                                                                                                                                <xs:element name="CategoryGlobalID" type="xs:string" minOccurs="0"/>
                                                                                                                                                <xs:element name="QuestionGlobalID" type="xs:string" minOccurs="0"/>
                                                                                                                                                <xs:element name="QuestionCommentGlobalID" type="xs:string" minOccurs="0"/>
                                                                                                                                                <xs:element name="QuestionCommentText" type="xs:string" minOccurs="0"/>
                                                                                                                                                <xs:element name="QuestionCommentResultNotes" type="xs:string" minOccurs="0"/>
                                                                                                                                           </xs:sequence>
                                                                                                                                      </xs:complexType>
                                                                                                                                 </xs:element>
                                                                                                                            </xs:choice>
                                                                                                                       </xs:complexType>
                                                                                                                  </xs:element>
                                                                                                             </xs:sequence>
                                                                                                        </xs:complexType>
                                                                                                   </xs:element>
                                                                                              </xs:choice>
                                                                                         </xs:complexType>
                                                                                    </xs:element>
                                                                               </xs:sequence>
                                                                          </xs:complexType>
                                                                     </xs:element>
                                                                </xs:choice>
                                                           </xs:complexType>
                                                      </xs:element>
                                                 </xs:sequence>
                                            </xs:complexType>
                                       </xs:element>
                                  </xs:choice>
                             </xs:complexType>
                        </xs:element>
                   </xs:sequence>
              </xs:complexType>
              <xs:key name="StetonAuditResultsKey_AuditResult">
                   <xs:selector xpath=".//AuditResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
              </xs:key>
              <xs:key name="StetonAuditResultsKey_CategoryResult">
                   <xs:selector xpath=".//CategoryResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
                   <xs:field xpath="CategoryGlobalID"/>
              </xs:key>
              <xs:key name="StetonAuditResultsKey_QuestionResult">
                   <xs:selector xpath=".//QuestionResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
                   <xs:field xpath="CategoryGlobalID"/>
                   <xs:field xpath="QuestionGlobalID"/>
              </xs:key>
              <xs:keyref name="AuditResultCategoryResult" refer="StetonAuditResultsKey_AuditResult">
                   <xs:selector xpath=".//CategoryResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
              </xs:keyref>
              <xs:keyref name="CategoryResultQuestionResult" refer="StetonAuditResultsKey_CategoryResult">
                   <xs:selector xpath=".//QuestionResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
                   <xs:field xpath="CategoryGlobalID"/>
              </xs:keyref>
              <xs:key name="StetonAuditResultsKey_QuestionCommentResult">
                   <xs:selector xpath=".//QuestionCommentResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
                   <xs:field xpath="CategoryGlobalID"/>
                   <xs:field xpath="QuestionGlobalID"/>
                   <xs:field xpath="QuestionCommentGlobalID"/>
              </xs:key>
              <xs:keyref name="QuestionResultlQuestionCommentResult" refer="StetonAuditResultsKey_QuestionResult">
                   <xs:selector xpath=".//QuestionCommentResult"/>
                   <xs:field xpath="AuditResultGlobalID"/>
                   <xs:field xpath="CategoryGlobalID"/>
                   <xs:field xpath="QuestionGlobalID"/>
              </xs:keyref>
         </xs:element>
    </xs:schema>
    Step four is where I have problems. I'm using Windows Explorer to drag and drop an XML instance document into http://d01db:8085/datamart/CustomerCare/xml while logged into the repository as xdb.
    Here's some of the test file that I'm using.
    <?xml version="1.0" standalone="no"?>
    <StetonAuditResults xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/xdb/Steton.xsd">
         <Control>
              <ResultCount>112</ResultCount>
         </Control>
    </StetonAuditResults>
    Note, the test XML file is 427k in size and I can't post it here. There is a lot of data between the </Control> tag and the </StetonAuditResults> tag.
    During the Drag and Drop I get the message "An error occured copying some or all of the selected files."
    My first suspicision was that the XML document failed validation. So I changed the namespace line to
    <StetonAuditResults xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="H:\StetonCustomerCare\Steton.xsd">
    I then started Altova's XMLSpy and the XML document is well formed and it validates.
    I then changed the namespace line in the XML document to
    <StetonAuditResults xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    and I could use Windows Explorer to drag and drop the file into the XML DB respository of http://d01db:8085/datamart/CustomerCare/xml, but this version doesn't shred the XML document into the SQL tables that I need.
    I then deleted the file from the repository.
    I then changed the namespace line in the XML document to <StetonAuditResults xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Steton.xsd">
    because someone told me to, and because I have seen an FAQ in this forum suggest this approach. I can copy using Windows Explorer into the http://d01db:8085/datamart/CustomerCare/xml. However, the file size via Windows Explorer is 427kb. Also "select count(*) from STETONAUDITRESULTS;" returns zero.
    What am I doing wrong?
    My background, I'm not an Oracle DBA, but I can code SQL select statements. So if I need to do something involving Oracle DBA privileges, please document it well. I will have to get the DBA's involved.
    My goal is import this XML file so that I can use it as a feed for a datamart. The first XML file in text format is 27mb.
    Thanks again for reading this far.

    I guess you have a namespace issue...(schema registered is not the same as the layout in your XML instance/doc, therefor will not be inserted). You have access to the XDB account...thats all you need (more then enough, i mean, you don't need dba privs).
    on the FAQ Mark explains...
    Why is the size of my XML document 0 bytes when viewed via HTTP or FTP ?
    Posted: Sep 1, 2006 6:07 AM in response to: mdrake in response to: mdrake      
    When a schema based XML is loaded into the XML DB repository via HTTP, FTP or dbms_xdb.createResource() the document is converted from a textual serialization of XML into a series of objects. At this point the size of the document becomes (a) meaningless and (b) difficult / expensive to calculate.
    The first question is what is meant by the size of the document once it has been stored using object-based persistence ? There are two possibilities
    (1) The number of bytes used the text serialization of the XML document.
    (2) The number of bytes required to store the internal object representation of the document. In this case the does the size include the bytes used for keys, refs indexes, etc ?
    Since (1) would be expensive to maintain as the document is updated (particularly in the case of partial updates) and (2) is expensive to calculate on a document by document basis, XML DB shows the size of all schema based XML documents as 'zero' bytes.
    Note that this also applies to the size of the registered version of XML Schema documents, which can be found in the folder tree /sys/schemas.
    If a schema based XML document is loaded into the repository and does not appear as 0 bytes long when viewed via HTTP or WebDAV this means that XML DB was unable to identifiy the XML schema the XML document is associated with.
    Note that immediatlely after uploading a document in Windows Explorer using the WebDAV protocol the size of the document will be non-zero, since the original size is cached by the Microsoft WebDAV client. However once a refresh of the folder is performed in Windows Explorer the size should be shown as zero if the document was recognized as a schema based document.

  • None of my "paid" books will open in iBooks.  They show they are there, but when I open them all I get is a blank page.  I have checked all the newbie mistakes.  Mavericks will not let me uninstall and reinstall iBooks.

    All the books I paid money for will not open in iBooks on my MAC.  Mavericks will not let me uninstall iBooks, so I cannot uninstall and reinstall it on my Pro.  I have deleted and re-loaded the books and they show in my library (as they always did), but when I open them, all I get is a blank page with three dots at the bottom, flashing in sequence.  This does not affect the free books from the book store nor does it affect the PDF I have loaded myself.  (I had this problem on my iPad when the latest big software came out about a year or two ago, but I was able to re-initalize the complete iPad from my Pro Book.)  I have tried just about everything I can think of, but all to no avail.  To save time, I have reset my iTunes password and performed all the other "Apple Tips" in the support section, but after 5 hours I am giving up.  Surely someone else must be having the same issue??

    Yup, same issue since installing Mavericks.  iBooks works fine on my wife's Macbook Pro, but on my Mac Pro none of my purchased (protected) books will open - only the free/unprotected ones.
    I'm asked for my AppleID password, but nothing happens when I try to open a purchased and downloaded book.   I deauthorized, reauthorized, etc ... nothing.  Each purchased book that I double-click gives me a dialog asking for my Apple ID password.  Nothing else.
    I was already buying more books via Kindle than iTunes and this just seals the deal for me.  At least I can read my already-purchased iBooks books on my iPad still...

  • Is this a bug or a simple Newbie mistake?

    Hi.
    I'm brand new to JavaFX, so I'm probably misunderstanding something. I've searched the web looking for information concerning it, but since it involves the 'new' operator, it's hard to filter down.
    Anyhow, here is the problem:
    I'm getting different results when I instantiate an object
    using the 'new' operator vs. the declaring it the more
    accepted JavaFX way.
    This is how I found the "problem".
    In order to learn how to program in JavaFX, I found a simple game from the Internet, "Blasteroids", to look at (http://www.remwebdevelopment.com/dev/a41/Programming-Games-in-JavaFX-Part-1.html). I copied and pasted this into:
    NetBeans IDE 6.9 (Build 201006101454)
    JavaFX 1.3 and got the game to work.
    In playing around with it, I converted instantiating an object from the "normal" way:
        var a: Asteroid = Asteroid
            type: type
            posX: x
            posY: y
            moveAngle: moveAngle
            velocityX: Math.sin(Math.toRadians(moveAngle))
                * randomVelocity
            velocityY: -Math.cos(Math.toRadians(moveAngle))
                * randomVelocity
            rotation_increment: rotation_increment
            active: true;
            return a;To using the "new" operator:
            var a:Asteroid = new Asteroid();
            a.type = type;
            a.posX = x;
            a.posY = y;
            a.moveAngle = moveAngle;
            a.velocityX = Math.sin(Math.toRadians(moveAngle)) * randomVelocity;
            a.velocityY = -Math.cos(Math.toRadians(moveAngle))* randomVelocity;
            a.rotation_increment = rotation_increment;
            a.active = true;
            return a;This is the only changes I made. I would "toggle" back and forth between the two, and I would always get the same results.
    When I did this conversion, the ship would show up, but the asteroids were gone. Actually, I think they were invisible because every once and a while, my ship would "blow up" and get reset to it's starting position. I tried adding:
    a.visible = true;
    But that didn't help.
    Indecently, I did the same thing with defining the "Stage" using a new operator, and got differing results:
    1. the window would open in the bottom right of my screen (vs filling up
    most of my screen. I would have to drag it up to play.
    2. it had a regular windows border with the minimize, maximize, close
    buttons in the top right (vs. a non-movable, border less window with no
    maximize, minimize, close buttons.)
    Is this a bug, or am I doing something wrong?
    Thank you

    I suspect you've run into bugs in the Blasteroids program and possibly in Stage in the JavaFX runtime.
    For simple cases one would think there should be no difference between this:
    var so = SomeObject {
        a: 1
        b: 2
        c: 3
    }and this:
    var so = SomeObject { }; // or var so = new SomeObject();
    so.a = 1;
    so.b = 2;
    so.c = 3;However, these cases do run through different code paths. In the first case, the init-block of SomeObject sees all the values provided by the caller. In the second case, the triggers on the a, b, and c variables would have to modify the internal state of the object appropriately. If the object has a lot of complex state, the result at the end of setting the three variables (and running their triggers) might not be identical to the object literal after initialization. This is most likely a bug. If an object isn't prepared to have its state variables modified after initialization, it should make them public-init instead of public.
    Depending on the object, though, initializing things via an object literal vs. setting variables after initialization might actually have different semantics. This seems to be the case with Stage. The Stage's size is established by its contents at initialization time, and its location at initialization time is determined by using its contents' size and the screen size to center the Stage on the screen. If you create the Stage empty, and then later add contents, the sizing/centering calculations will be based on an empty Stage and will thus give a different result.
    Using the object literal technique is idiomatic JavaFX Script, and it's probably more efficient than setting variables after initialization, so I'd recommend sticking with object literals.

  • Bug or Newbie mistake?

    Last night I attached my MacBook Pro to our tv (doubles as a 64 inch external monitor). I used the DVI adapter and connected the cable before booting. When I powered on and went to type in my password, it wouldn't respond to some of the keys. I'd type and...nothing. I finally realized that both the caps lock and num lock lights were on. (I didn't do it.) I turned them off and tried the password again. Now it wouldn't accept keys from the left side of the keyboard unless num lock was on. To use the right side of the keyboard, I had to turn num lock off. I finally disconnected the DVI cable and was able to type in my password. Did I forget an important procedure or could this be a bug?

    i believe its a bug it happened to me but it "fix itself" just by turn it off and on again...

  • My mistake but I need your help (Y70}

    Dear all, I have made a super newbie mistake - powering off my laptop during windows upgrade process. But it was stuck at 99% for over 2 hours. So I just got the Y70 Touch, I upgraded to Win10 without problems. However, I want to have a clean install, so I opt to RESET to windows 10 original settings with a clean installation. So the Resetting was going slow, and it was stuck at 99% for over 2 hours and I shut it off. Now, it can't find the boot device. It says "check online for INACESSIBLE_BOOT_DEVICE" I have created the Lenovo Bootable Generator,  but it's no help since it still go through USB within the startup cycle. What can I do? Please help! thanksJack

    hi Jack,
    It looks like you created a bootable legacy Windows 10 flashdrive.
    For you to be able to install Windows 10 on top of your previous Windows 10 installation (repair install) or format the Drive C:\ and do a clean install of Windows 10 (without formatting/deleting the other partitions) then you will need to specifically create a bootable UEFI Windows 10 flashdrive (see Option 2 -Step 6 of this guide)
    Note:
    You will need to change Boot Mode back to UEFI in the BIOS to read the bootable UEFI Win10 flashdrive.
    Alternatively, you can also stick with your current bootable legacy Windows 10 flashdrive but you will need to wipe all partitions to reinstall Windows 10 (this coverts the drive to an MBR disk).
    Let me know if the above steps works for you.
    Regards

  • Newbie learning swing

    Hello all. I am trying my hand at swing development for the first time. My experience with C++ has made my transition to java alot simpler. But I am having a problem with a simple little test program. I have a JComboBox, a JList, and a JTextField control. When the combobox gets a new selection, I want it to set the selection in the listbox. This is working. I also want the combobox to be updated when the list selection is updated. This is not working. I know there are probably tons of newbie mistakes so please take it easy on me. I have pasted the class below. Any and all help is appreciated.
    class windemo extends JFrame {
         JTextField jt = new JTextField(150);
         JLabel jl = new JLabel("Foobar");
         JList jl3 = new JList();
         JComboBox jb = new JComboBox();
         public windemo(){
              super("This is my frame");
              addWindowListener(new WindowAdapter() {
                             public void windowClosing(WindowEvent e) {
                                  System.exit(0);
              JPanel jp = new JPanel();
              setContentPane(jp);
              jp.add(jl);
              jt.setSize(new Dimension(100,200));
              jp.add(jt);
              String s[] = {"one", "two","three"};
              jl3 = new JList(s);
              jl3.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
              jl3.setSelectedIndex(0);
              jl3.addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e){
                        JList jl2 = (JList) e.getSource();
                        jt.setText((String) jl2.getSelectedValue());
                        if(jb.getItemCount() >0){
                             jb.setSelectedItem((String)jl2.getSelectedValue());
              JComboBox jb = new JComboBox(s);
              jb.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e){
                        JComboBox<String> jb2 = (JComboBox<String>)e.getSource();
                        jt.setText((String) jb2.getSelectedItem());
                        jl3.setSelectedValue(jb2.getSelectedItem(),true);
              jb.addItem(s);
              jb.setSelectedIndex(0);
              jp.add(jb);
              jp.add(jt);
              jp.add(new JScrollPane(jl3));
              pack();
              setVisible(true);
    }

    gimbal2 wrote:
    T.PD wrote:
    2. never use <tt>System.exit()</tt> accept in your main method (and even there if only you really need to return an exit code). Correct way to close a window is <tt>setVisible(false)</tt> or <tt>dispose()</tt>.I have to nitpick. setVisible() does not close the window, it just makes it invisible. The window is still there, using up resources.Of course, this depends on which you want to do ... get rid of the window, or make it invisible so it can be used later.
    ¦{Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Missing method body or declare abstract error

    Hi!
    I have been working on this simple Java 1.3.1 program for three days now and cannot figure out what I am doing wrong. If anyone has done the "Building an Application" tutorial in the New to Java Programming Center, you might recognize the code. I am trying to set up a frame with panels first using the BorderLayout and then the FlowLayout within each section of the BorderLayout. It will have textfields and checkboxes. I am working on the code to retrieve the user input from the text boxes and also to determine which checkbox the user has checked. Here is my code: (ignore my irrelivent comments!)
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    import java.awt.Color.*;
    import java.awt.Image.*;
    //Header Comment for a Routine/Method
    //This method gathers the input text supplied by the user from five text fields on the Current
    //Purchase tab of the tabbed pane of the MPGLog.java program. The way it gathers the text
    //depends on the current processing state, which it retrieves on its own. It saves the text to
    //a text file called textinput.txt.
    public class CollectTextInput extends JPanel implements ActionListener
    { // Begin class
         //Declare all the objects needed first.
         // These are the text fields
         private JTextField currentMileage;
         private JTextField numofGallonsBought;
         private JTextField dateofPurchase;
         private JTextField pricePerGallon;
         private JTextField gasBrand;
         // Declaring the Labels to go with each TextField
         private JLabel lblcurrentMileage;
         private JLabel lblnumofGallonsBought;
         private JLabel lbldateofPurchase;
         private JLabel lblpricePerGallon;
         private JLabel lblgasBrand;
         // Declaring the Checkboxes for the types of gas bought
         private JCheckBox chbxReg;
         private JCheckBox chbxSuper;
         private JCheckBox chbxUltra;
         private JCheckBox chbxOther;
         private JCheckBox chbxHigher;
         private JCheckBox chbxLower;
         // Declaring the Buttons and images needed
         private JButton enter;
         private JButton edit;
         //private JButton report; //Will be used later
         private JLabel bluecar;          //Used with the ImageIcon to create CRV image
         private JPanel carimage;     //Used in buildImagePanel method
         private JPanel datum;          //Used in buildDatumPanel method
         private JPanel gasgrade;     //Used in buildGasTypePanel method.
         //Declaring the Panels that need to be built and added
         //to the border layout of this panel.
         //private JPanel panlimages;
         //private JPanel panltextinputs;
         //private JPanel panlchkBoxes;
         // Class to handle functionality of checkboxes
         ItemListener handler = new CheckBoxHandler();
         // This is where you add the constructor for the class - I THINK!!
         public CollectTextInput()
         { // Opens collectTextInput constructor
              // Must set layout for collectTextInput here
              // Choosing a BorderLayout because we simply want to
              // add panels to the North, Center and South borders, which, by
              // default, will fill the layout with the three panels
              // we are creating
              setLayout(new BorderLayout());
              //Initialize the objects in the constructor of the class.
              //Initialize the textfields
              currentMileage = new JTextField();
              numofGallonsBought = new JTextField();
              dateofPurchase = new JTextField();
              pricePerGallon = new JTextField();
              gasBrand = new JTextField();
              // Initialize the labels that go with each TextField
              lblcurrentMileage = new JLabel("Enter the mileage at the time of gas purchase: ");
              lblnumofGallonsBought = new JLabel("Enter the number of gallons of gas bought: ");
              lbldateofPurchase = new JLabel("Enter the date of the purchase: ");
              lblpricePerGallon = new JLabel("Enter the price per gallon you paid for the gas: ");
              lblgasBrand = new JLabel("Enter the brand name of the gas: ");
              //Initialize the labels for the checkboxes.
              chbxReg = new JCheckBox("Regular ", true);
              chbxSuper = new JCheckBox("Super ");
              chbxUltra = new JCheckBox("Ultra ");
              chbxOther = new JCheckBox("Other: (Choose one from below) ");
              chbxHigher = new JCheckBox("Higher than Ultra ");
              chbxLower = new JCheckBox("Lower than Ultra ");
              //Initialize the buttons that go on the panel.
              enter = new JButton("Save Data");
              edit = new JButton("Edit Data");
              //Initialize the image that oges on the panel.
              bluecar = new JLabel("2002 Honda CR-V", new ImageIcon("CRVBlue.jpg"),JLabel.CENTER);
              // Now bring it all together by calling the other methods
              // that build the other panels and menu.
              buildImagePanel();
              buildDatumPanel();
              buildGasTypePanel();
              // Once the methods above build the panels, this call to add
              //  them will add the panels to the main panel's border
              // layout manager.
              add(datum, BorderLayout.NORTH);
              add(carimage, BorderLayout.EAST);
              add(gasgrade, BorderLayout.CENTER);
         } // Ends the constructor.
            // This method creates a panel called images that holds the car image.
         public void buildImagePanel();
         { // Opens buildImagePanel.
              // First, create the Panel
              carimage = new JPanel();
              //Second, set the color and layout.
              carimage.setBackground(Color.white);
              carimage.setLayout(new FlowLayout());
              // Third, add the image to the panel.
              carimage.add(bluecar);
         }// Closes buildImagePanel
         //This method creates a panel called datum that holds the text input.
         public void buildDatumPanel();
         { //Opens buildDatumPanel
              // First, create the Panel.
              datum = new JPanel();
              //Second, set the background color and layout.
              datum.setBackground(Color.white);
              datum.setLayout(new GridLayout(2, 4, 20, 20));
              //Third, add the textfields and text labels to the panel.
              datum.add(lblcurrentMileage);
              datum.add(currentMileage);
              datum.add(lblnumofGallonsBought);
              datum.add(numofGallonsBought);
              datum.add(lbldateofPurchase);
              datum.add(dateofPurchase);
              datum.add(lblpricePerGallon);
              datum.add(pricePerGallon);
              datum.add(lblgasBrand);
              datum.add(gasBrand);
              //Optionally - Fourth -set a border around the panel, including
              // a title.
              datum.setBorder(BorderFactory.createTitledBorder("Per Purchase Information"));
              //Fifth - Add listeners to each text field to be able to
              //  know when data is input into them.
              currentMileage.addActionListener(this);
              numofGallonsBought.addActionListener(this);
              dateofPurchase.addActionListener(this);
              pricePerGallon.addActionListener(this);
              gasBrand.addActionListener(this);
         }// Closes buildDatumPanel
         // This method builds a panel called gasTypePanel that holds the checkboxes.
         public void buildGasTypePanel()
         { // Opens buildGasTypePanel method
              // First, create the panel.
              gasgrade = new JPanel();
              // Second, set its background color and its layout.
              gasgrade.setBackground(Color.white);
              gasgrade.setLayout(new GridLayout(5, 1, 10, 20));
              // Third, add all the checkboxes to the panel.
              gasgrade.add(chbxReg);
              gasgrade.add(chbxSuper);
              gasgrade.add(chbxUltra);
              gasgrade.add(chbxOther);
              gasgrade.add(chbxHigher);
              gasgrade.add(chbxLower);
              //Optionally, - Fourth - set a border around the panel, including
              // a title.
              gasgrade.setBorder(BorderFactory.createTitledBorder("Gas Type Information"));
              // Fifth - CheckBoxes require a CheckBox Handler.
              // This is a method created separately
              // outside of the method where the checkboxes are added to
              // the panel or where the checkboxes are even created.
              // This method (CheckBox Handler) implements and ItemListener
              // and is a self-contained method all on its own. See
              // the CheckBox Handler methods following the
              // actionPerformed method which follows.-SLM
         } // Closes the buildGasTypePanel method
    // Create the functionality to capture and react to an event
    //   for the checkboxes when they are checked by the user and
    //   the text fields to know when text is entered. Also to react to the
    //   Enter button being pushed and the edit button being pushed.
    public void actionPerformed(ActionEvent evt)
    { // Opens actionPerformed method.
         if((evt.getSource() == currentMileage) || (evt.getSource() == enter))
              { // Opens if statement.
                // Retrieves the text from the currentMileage text field
                //  and assigns it to the variable currentMileageText of
                //  type String.
                String currentMileageText = currentMileage.getText();
                lblcurrentMileage.setText("Current Mileage is:    " + currentMileageText);
                // After printing text to JLabel, hide the text field.
                currentMileage.setVisible(false);
           } // Ends if statement.
          if((evt.getSource() == numofGallonsBought) || (evt.getSource() == enter))
              { // Opens if statement.
                // Retrieves the text from the numofGallonsBought text field
                //  and assigns it to the variable numofGallonsBoughtText of
                //  type String.
                String numofGallonsBoughtText = numofGallonsBought.getText();
                lblnumofGallonsBought.setText("The number of gallons of gas bought is:    " + numofGallonsBoughtText);
                // After printing text to JLabel, hide the text field.
                numofGallonsBought.setVisible(false);
           } // Ends if statement.
           if((evt.getSource() == dateofPurchase) || (evt.getSource() == enter))
                     { // Opens if statement.
                       // Retrieves the text from the dateofPurchase text field
                       //  and assigns it to the variable dateofPurchaseText of
                       //  type String.
                       String dateofPurchaseText = dateofPurchase.getText();
                       lbldateofPurchase.setText("The date of this purchase is:    " + dateofPurchaseText);
                       // After printing text to JLabel, hide the text field.
                       dateofPurchase.setVisible(false);
           } // Ends if statement.
           if((evt.getSource() == pricePerGallon) || (evt.getSource() == enter))
                            { // Opens if statement.
                              // Retrieves the text from the pricePerGallon text field
                              //  and assigns it to the variable pricePerGallonText of
                              //  type String.
                              String pricePerGallonText = pricePerGallon.getText();
                              lblpricePerGallon.setText("The price per gallon of gas for this purchase is:    " + pricePerGallonText);
                              // After printing text to JLabel, hide the text field.
                              pricePerGallon.setVisible(false);
           } // Ends if statement.
           if((evt.getSource() == gasBrand) || (evt.getSource() == enter))
                       { // Opens if statement.
                         // Retrieves the text from the gasBrand text field
                         //  and assigns it to the variable gasBrandText of
                         //  type String.
                         String gasBrandText = gasBrand.getText();
                         lblgasBrand.setText("The Brand of gas for this purchase is:    " + gasBrandText);
                         // After printing text to JLabel, hide the text field.
                         gasBrand.setVisible(false);
           } // Ends if statement.
           // This provides control statements for the Edit button. If the
           //  Edit button is clicked, then the text fields are visible again.
           if(evt.getSource() == edit)
           { // Opens if statement.
             // If the edit button is pressed, the following are set to
             //  visible.
                currentMileage.setVisible(true);
                numofGallonsBought.setVisible(true);
                dateofPurchase.setVisible(true);
                pricePerGallon.setVisible(true);
                gasBrand.setVisible(true);
         }// Closes if statement.
    } // Closes actionPerformed method.
         private class CheckBoxHandler implements ItemListener
         { // Opens inner class
              public void itemStateChanged (ItemEvent e)
              {// Opens the itemStateChanged method.
                   JCheckBox source = (JCheckBox) e.getSource();
                        if(e.getStateChange() == ItemEvent.SELECTED)
                             source.setForeground(Color.blue);
                        else
                             source.setForeground(Color.black);
                        }// Closes the itemStateChanged method
                   }// Closes the CheckBoxHandler class.
    } //Ends the public class collectTextInput classThe error I keep receiving is as follows:
    C:\jdk131\CollectTextInput.java:128: missing method body, or declare abstract
         public void buildImagePanel();
    ^
    C:\jdk131\CollectTextInput.java:142: missing method body, or declare abstract
         public void buildDatumPanel();
    ^
    2 errors
    I have looked this error up in three different places but the solutions do not apply to what I am trying to accomplish.
    Any help would be greatly appreciated!! Thanks!
    Susan

    C:\jdk131\CollectTextInput.java:128: missing methodbody, or declare ?abstract
    public void buildImagePanel();^
    C:\jdk131\CollectTextInput.java:142: missing methodbody, or declare abstract
    public void buildDatumPanel();Just remove the semicolons.
    Geesh! If I had a hammer I would be hitting myself over the head with it right now!!! What an obviously DUMB newbie mistake!!!
    Thanks so much for not making me feel stupid! :-)
    Susan

  • How many apple ids can I have on one icloud account

    I have one apple ID.  My iphone is linked to this apple ID and so is our Ipad.  The ipad gets all of my mail, but also gets all of my text messages.  This is not the greatest situation.  When my husband got his work iphone, he was told to use my apple id so he would have access to all of my music and purchased items.  That really messed things up because he was getting all of my mail and suddenly all of our contacts were shared.  Not good!
    We are now trying to set up a new ipod touch for one of the kids.  Don't want the same situation as above.  I want this to have a separate identity but still be on our account so it can share all of my apple purchases. 
    What is the best way to do this?  I briefly talked to someone at the apple store a few months back and he said that you can have multiple apple ids on one account.  Anyone have any tips on setting these up?  Want to avoid any unnecessary newbie mistakes.

    You can't have multiple IDs on one account, but you can use multiple IDs for different purposes on the same device.
    Just use the one AppleID for iTunes and the AppStore so you can all share your music and app purchases. Then each person should have their own individual AppleID with associated iCloud account for mail, contacts, calendars, iMessage and FaceTime.
    You don't have to use the same AppleID for all services.

  • High CPU Usage while getting input from JTextArea

    I have a core class (emulator) that can receive and handle command strings of varying sorts. I have an Interface that, when implemented, can be used to work with this emulator.
    I have code that works, but the CPU is pegged. The emulator has its own thread, and my GUI, which implements the aforementioned Interface and extends JFrame, clearly has its own as well.
    So, the emulator calls the gatherResponse(prompt) method of the interface driving it, in order to find out the next command :
    Here is the code for this method (note that the console member variable is referring to the JTextArea that is within the JFrame) :
         public String gatherResponse(String prompt) {
              printPrompt(prompt);          
              lastPrompt = prompt;
              class ResponseListener extends Thread implements KeyListener {
                   public volatile String response = null;
                   public ResponseListener() {
                        super();
                   public void run() {
                        while (getResponse() == null) {
                             try {
                                       Thread.sleep((int)Math.random() * 100);
                             catch (InterruptedException ie) {
                                  System.out.println("ResponseListener.run==>"+ie.toString());
                   public String getResponse() {
                        return response;
                   public void keyPressed(KeyEvent e) {
                        System.out.println("ResponseListener.keyPressed==>"+e.getKeyCode());
                        if (e.getKeyCode() == 10) {
                             try {
                                  response = getLastConsoleLine();
                                  System.out.println("response found:"+response);
                             catch (Exception exc) {}
                   } //end public void keyPressed(KeyEvent e)
                   public void keyTyped(KeyEvent e) {}
                   public void keyReleased(KeyEvent e) {}
              } //end class ResponseListener implements KeyListener
              ResponseListener rl = new ResponseListener();
              console.addKeyListener(rl);
              System.out.println("Starting ResponseListener");
              rl.start();
              String response = null;
              while ((response = rl.getResponse()) == null) {
                   try {
                        Thread.sleep((int)Math.random() * 1000);
                   catch (InterruptedException ie) {
                        System.out.println(ie.toString());
              } //end while((response = rl.getResponse())==null)
              console.removeKeyListener(rl);
              System.out.println("returning "+response);
              return response;
         } //end public void gatherResponse(String prompt)     Like I said, this works just fine, but I don't want to go with it when it pegs the CPU. I've never really done any work w/ Threads, so I could be making a real newbie mistake here...

    Code adapted from The Producer/Consumer Example
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class Listening
        Scheduler scheduler;
        JTextField north, south;
        public Listening(Scheduler s)
            scheduler = s;
            north = new JTextField();
            south = new JTextField();
            north.setName("north");
            south.setName("south");
            scheduler.register(north);
            scheduler.register(south);
        private JTextField getNorth() { return north; }
        private JTextField getSouth() { return south; };
        public static void main(String[] args)
            Scheduler scheduler = new Scheduler();
            Listening test = new Listening(scheduler);
            Monitor monitor = new Monitor(scheduler);
            JFrame f = new JFrame("Listening");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getNorth(), "North");
            f.getContentPane().add(test.getSouth(), "South");
            f.setSize(240,125);
            f.setLocation(200,200);
            f.setVisible(true);
            monitor.start();
    class Scheduler
        private String contents;
        private boolean available = false;
        public synchronized String get(String caller)
            while(!available)
                try
                    wait();
                catch (InterruptedException ie)
                    System.err.println("Scheduler.get interrupted: " + ie.getMessage());
            available = false;
            System.out.println(caller + " get: " + contents);
            notifyAll();
            return contents;
        public synchronized void put(String sender, String input)
            while(available)
                try
                    wait();
                catch (InterruptedException ie)
                    System.err.println("Scheduler.put interrupted: " + ie.getMessage());
            contents = input;
            available = true;
            System.out.println(sender + " put: " + contents);
            notifyAll();
        protected void register(final JTextComponent tc)
            Document doc = tc.getDocument();
            doc.addDocumentListener(new DocumentListener()
                public void changedUpdate(DocumentEvent e) { /*styles*/ }
                public void insertUpdate(DocumentEvent e)  { report(); }
                public void removeUpdate(DocumentEvent  e) { report(); }
                private void report()
                    put(tc.getName(), tc.getText());
    class Monitor extends Thread
        Scheduler scheduler;
        JTextField  listenerField;
        public Monitor(Scheduler s)
            scheduler = s;
            launchDialog();
        public void run()
            boolean continueToMonitor = true;
            while(continueToMonitor)
                try
                    Thread.sleep(10);
                catch(InterruptedException ie)
                    System.err.println("Monitor.run interrupted: " + ie.getMessage());
                    continueToMonitor = false;
                String text = scheduler.get(this.getClass().getName());
                listenerField.setText(text);
        private void launchDialog()
            listenerField = new JTextField();
            JDialog d = new JDialog(new Frame(), getClass().getName(), false);
            d.getContentPane().add(listenerField, "North");
            d.setSize(300,100);
            d.setLocation(585,200);
            d.setVisible(true);
    }

  • How to force validator method instead of data type validation in af:table

    This post will probably once again illustrate exactly how new I am to the Java/JDeveloper world so thanks in advance for any help! I have tried searching but couldn't find anything that seemed to mirror my problem.
    I am using a modification of Frank's idea on how to individually color table cell backgrounds.
    http://thepeninsulasedge.com/frank_nimphius/2008/04/10/adf-faces-conditionally-color-table-cell-background-2/
    My intention was to use this along with custom validation to color cells with invalid values. It was a user request that it be done so as to quickly spot input errors (when updating records) if someone had missed the initial faces message and was no longer in the field that generated the error. It works fine for fields in my af:table based on VO attributes with varchar2 types but the 2 values with float and number types handle character input with a faces message "Not a number" and then do not seem to process the validator. The reason I (think I) need to use the validator in addition to Franks code is that in the validator code I use an addpartialtarget to the uicomponent that refreshes the background color if it changed in the backing bean.
    FYI the project is based on ADF BC/JSF.
    I tried gave the full use case as suggested so you understand what I am trying to accomplish and if you have a better way to accomplish this please let me know as well.
    Thanks,
    Rich
    Managed-Bean
        public String getMODELColorString() {
            MODELColorString = "width:125px;";
            Object MODEL = getRowValue("#{row.ModelType}");
            if (MODEL != null) {
                if (!isValidMODEL(MODEL.toString())) {
                    MODELColorString = "background-color:red;width:125px;";
            return MODELColorString;
        }Backing-Bean
            if (!myValidation.isValidMODEL(object.toString())) {
                System.out.println("InValid Data");
            AdfFacesContext.getCurrentInstance().addPartialTarget(uiComponent);P.S. If I made any newbie mistakes in my code please let me know, although this is obviously not production code yet by any means.
    Message was edited by:
    BengalGuy

    Frank (or anyone else who might offer some advice),
    I thought that solved my issue as I could see the validator getting triggered, however something else is now happening. It seems to pass through the validator once for each of the values on my table with the invalid input I entered on one of the numbers, "a" in this case, and then once again through the color change backing bean but at that time the invalid input reverts to the original input and the change is rendered on the af:table as well. Any thoughts ? I put a print in the validator method, in the method that gets called from the validator (checks to see if value can be converted to float) , and then the color change bean (which also calls the float validation test) and pasted the output below.
    Validator Triggered \Current Value = 0.037178375 \FloatTestOn: 0.037178375 \Result: Valid Data
    Validator Triggered \Current Value = 0.109212324 \FloatTestOn: 0.109212324 \Result: Valid Data
    Validator Triggered \Current Value = 0.18624917 \FloatTestOn: 0.18624917 \Result: Valid Data
    Validator Triggered \Current Value = 0.26863635 \FloatTestOn: 0.26863635 \Result: Valid Data
    Validator Triggered \Current Value = 0.35674548 \FloatTestOn: 0.35674548 \Result: Valid Data
    Validator Triggered \Current Value = -0.38118127 \FloatTestOn: -0.38118127 \Result: Valid Data
    Validator Triggered \Current Value = -0.3382032a \FloatTestOn: -0.3382032a NumberFormatException: For input string: "-0.3382032a"
    08/04/16 10:03:14 \Result: InValid Data
    Validator Triggered \Current Value = -0.29224017 \FloatTestOn: -0.29224017 \Result: Valid Data
    Validator Triggered \Current Value = -0.24308495 \FloatTestOn: -0.24308495 \Result: Valid Data
    Validator Triggered \Current Value = -0.1905158 \FloatTestOn: -0.1905158 \Result: Valid Data
    Validator Triggered \Current Value = -0.13429564 \FloatTestOn: -0.13429564 \Result: Valid Data
    Validator Triggered \Current Value = -0.07417088 \FloatTestOn: -0.07417088 \Result: Valid Data
    Validator Triggered \Current Value = -0.009870344 \FloatTestOn: -0.009870344 \Result: Valid Data
    \Checking for color change \FloatTestOn: 0.037178375
    \Checking for color change \FloatTestOn: 0.109212324
    \Checking for color change \FloatTestOn: 0.18624917
    \Checking for color change \FloatTestOn: 0.26863635
    \Checking for color change \FloatTestOn: 0.35674548
    \Checking for color change \FloatTestOn: -0.38118127
    \Checking for color change \FloatTestOn: -0.3382032 <- "a" is no longer there ?
    \Checking for color change \FloatTestOn: -0.29224017
    \Checking for color change \FloatTestOn: -0.24308495
    \Checking for color change \FloatTestOn: -0.1905158
    \Checking for color change \FloatTestOn: -0.13429564
    \Checking for color change \FloatTestOn: -0.07417088
    \Checking for color change \FloatTestOn: -0.009870344

  • Need advice on repairs after wine spill - won't boot

    Trying to help a friend fix her MacBook Pro 17" mid-2009 laptop.  A fairly small amount of wine was spilled on the keyboard and it was turned off, however not knowing what else to do they used canned air to dry it out.  They did not turn it upside down so wine could have been blown deeper into the laptop.  She took it to a repair shop and they apparently cleaned it but said the upper assembly containing the keyboard needed to be replaced.  It powered up once after this incident but never got passed the start scene with the Apple logo.  Since then it won't power up.  My question it this... is the power button integrated with the keyboard assembly and possibly damaged?  Would buying a used keyboard assembly fix the problem or could there be more unseen damage.  Any ideas will be appreciated.  Thanks.

    Hi everyone,
    I've been using forums like this one looking for advice on what to do, expect and what not to do when faced with a spillage on your mac and I appreciate everyone's stories and advice from their experience so, I'll gladly reciprocate.
    So, I spilled soda pop on my macbook air recently. It was about 2/3 of a shot glass full of diet root beer in the upper right hand corner. I was completely devastated. I thought: "not only would this be a unnecessary and expensive waste of money, but all of my intake files were on that Mac and I'll lose literally thousands of dollars in potential sales if my data is corrupted too!"
    Under pressure, I succumb to the two newbie mistakes that almost every newbie makes. First, I froze.  Completely. "Maybe is the liquid didn't make it's way into the system? - it really wasn't that much.." I then waited to see what would happen (stupid). The Mac shut off. In a panic, i switched it back on (STUPID) and a blank white screen appeared with a text in the middle. the first paragraph was in english and read "There was a problem attempting to turn your device on … etc, etc". There was a paragraph beneath it written in Chinese or Korean characters. Then, mac shut off again. I frantically ran down stairs to get a bag of rice. I return to our room and, in a panic, i wanted to try turing on the macbook one more time before dumping it in rice (very STUPID). My Mac was working and I was thrilled (for about 5 minutes). All of a sudden, my keys strokes stopped registering, everything froze and it shut down. I did not turn it back on after that. I closed it and quickly flipped it over to let it dry and attempt to save it's life. About 30 seconds later, a motor like noise emanated from the Mac. It started quiet and then quickly got louder and louder. It got so loud that it sounded like the fan was screaming (i've never heard it that loud before). Then, it quickly simmered right down. I THEN submersed it into a rice coffin.
    I was so upset, I had so many potential customer intakes on that device and, due to the volume i get on a daily basis, didn't back it up. I made sure rice got in every visible crevice without actually opening up the device. 3 hours later, I put my ear up to the back of the mac. I could hear a faint motor hum still active in the device (like the normal sign it makes when it's on). I though "ok, ok… that's a good sign right?!". It's about that time where I started surfing forums likes these to have a better idea of how to handle this, what to expect and shared/common signs from others experiences that indicate damage has been done.
    I kept it closed, tipped over and submersed in it's rice coffin for 37 hours until I took it to the Apply store. All great new and I had the best possible scenario happen to me
    The tech said there were no signs of any liquid damage in the system (not even the spill detectors picked it up) and that it's running perfectly fine.
    So, to recap:
    1. I spilled 2/3 of a shot glass full of diet root beer in the upper right hand corner of my Macbook Air (where the power button is.
    2. The computer shut itself down.
    3.I tried to turn it back on twice. Once right after and I got blank screen with text saying it's experiencing difficulties trying to start - then it shut itself off. A second time, I attempted to turn it back on 10 minutes later and it ran smoothly for 5 minutes then, keys stopped registering, the computer froze and shut itself off again.
    4. Mac let out a very loud scream and then the sound died down (but still lightly hummed for hours later).
    5. I closed it and turned it upside down (with the shell closed).
    5. I submersed it in a bag of rice (I made sure it got into every possible visible crevice).
    6. I left it in it's rice coffin for 37 hours.
    7. Took it to the Apple store - and turns out it was perfectly fine and there were no fees!
    I'm also really impressed with Apple. It would have been so easy and profitable for them to take advantage of the situation and at least charge and assessment fee - but they didn't. It was completely free. They even replaced one of my screws before sending me off. Apple is honest and respectful with their customers! it if it's broke - they really don't "fix" it like a lot of these other mainstream stores who sell computer repair services. Apple, you rule in so many ways. You know what you're doing as a business and are owning the market for it. Great service and great products Apple.
    So that is my spillage story, hope you all find it as usefully as I found your stories (these forums gave me the idea to use rice and it worked!).
    Wish you all good luck with your macbook spillage issues. Don't be so quick to write it off as a loss just yet

  • Cannot access my external hard drive!

    A few month ago when I was transferring my files from a PC via a Seagate external hard drive (originally formatted on that PC) to my then new Intel iMac OS X 10.5.6, I made a newbie mistake in not properly "dismounting" before I pulled the USB. Now I cannot access the files on the Seagate external hard drive either from my iMac nor on my PC.
    Are there simple ways I can fix this without spending money on new software? Or would Apple Genius Bar be able to take care of this? Thanks!

    1) disconnect that external cables and all
    2) power cycle that Seagate, power on power off a few times
    3) zap pram on imac
    4) reset the power manager on the imac look that up on apple/support and type in search window
    when done:
    1) power on imac
    2)power on seagate
    3) connect usb to imac first
    4) connect usb to seagate should mount if it does not then no luck.

  • Speedgrade cc 2014 color wheel not showing an outer ring

    This is probably a very basic question but how do you get the outer rings of the color wheels in speedgrade cc 2014 to appear?

    Thanks for that. If I were running the Adobe code shop, the speed grade team would have received an "Aw ****". They fixed something that wasn't broke and in the process they broke it. In that now all the documentation and training videos are wrong. What is even more perplexing is that in their interface they have two other methods for doing the same thing. They could have created the new method and kept the old method for backwards compatibility. Instead of having to explain the loss of a well understood interface to existing loyal users, they could have presented a new choice.
    That software development team needs to go back to the bush league. They made a newbie mistake.

  • Adobe Media Encoder won't take mov. files!?

    My Adobe Media Encoder will not take mov. files! That should not be a problem, right? When I click the Add-button the mov. files is not listed up unless I choose to show all files. And when selecting the file, the program says the file could not be imported -_-
    Probably a stupid newbie mistake, but can anyone tell me what it is?
    I have downloaded the latest flash CS4 trial package, which include the encoder, and am trying to encode files provided with adobe's book "Adobe flash CS4 professional - Classroom in a book"

    I found the answer. I needed to install Quicktime lol

Maybe you are looking for

  • Does the new digital av adapter work on iPad 2 iOS 5.0.1?

    Hi all,I read some threads on forum. Someone said that the new digital av adapter required IOS 5.1, is that true?

  • Transfer attachment from SRM SHC to ECC PO

    Hi, Im working on SRM 7.0.Classic scenario.I need to enable the transfer of attachments from SRM SC to R/3 PO.Can anyone explain the steps to achieve the above? Also in case of extended classic scenario,is the attachment transferred automatically fro

  • Set item property

    Dear All Any one tell me. Can i use SET_ITEM_PROPERTY('ALLAWANCES.TXT_TEST', VISIBLE, PROPERTY_TRUE); in when list change trigger thanks in advance Regards,

  • Functional Input required

    Hi All, I need your functional inputs on one of the client requirement. They want to do cost planning for project components at the time of bidding / quotation stage. At this time, they dont have even created material master so we cant assign materia

  • Switch protection to Secondary DPM if Primary DPM fails

    Hello,       I have one Primary DPM 2012 R2 server and one Secondary DPM 2012 R2 server.  I have not found a step by step guide to switch protection over to the Secondary DPM in an event when the Primary Server is not available (gone belly up).  Look