コード例 #1
0
 public static void main(String[] args) {
   Singleton.getInstance();
   Singleton.getInstance();
   Singleton.getInstance();
   Singleton.getInstance();
   System.out.println(Singleton.getData());
 }
コード例 #2
0
  public static void main(String[] args) throws IOException, ClassNotFoundException {

    Singleton instance = Singleton.getInstance();

    // Serializing the singleton instance
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton.tmp"));
    oos.writeObject(instance);
    oos.close();

    // Recreating the instance by reading the serialized object data store
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("singleton.tmp"));
    Singleton singleton = (Singleton) ois.readObject();
    ois.close();

    // Recreating the instance AGAIN by reading the serialized object data store
    ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("singleton.tmp"));
    Singleton singleton1 = (Singleton) ois2.readObject();
    ois2.close();

    // The singleton behavior have been broken
    System.out.println("Instance reference check : " + singleton.getInstance());
    System.out.println("Instance reference check : " + singleton1.getInstance());
    System.out.println("=========================================================");
    System.out.println("Object reference check : " + singleton);
    System.out.println("Object reference check : " + singleton1);
  }
コード例 #3
0
 public static void main(String[] args) {
   Singleton.getInstance().printSingleton();
   Singleton.getInstance().printSingleton();
   Singleton.getInstance().printSingleton();
   Singleton.getInstance().printSingleton();
   Singleton.getInstance().printSingleton();
 }
コード例 #4
0
ファイル: Singleton.java プロジェクト: GTCoder/GreenTeaCode
  public static void main(String[] args) {
    Singleton s1 = Singleton.getInstance(0);
    Singleton s2 = Singleton.getInstance(1);
    Singleton s3 = Singleton.getInstance(2);

    s1.printData();
    s2.printData();
    s3.printData();
  }
コード例 #5
0
ファイル: ts.java プロジェクト: ansonkang/MYJAVA
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Singleton s = new Singleton();
   s.getInstance();
   System.out.println(s.getInstance().hashCode());
   s = new Singleton();
   s.getInstance();
   System.out.println(s.getInstance().hashCode());
 }
コード例 #6
0
  public static void main(String[] args) {
    Singleton singletonNesne1 = Singleton.getInstance();
    Singleton singletonNesne2 = Singleton.getInstance();

    // Singleton singletonNesne2=new Singleton();
    // yukarýdaki kod hata verir.

    if (singletonNesne1 == singletonNesne2) System.out.println("Nesneler Ayný!");
    else System.out.println("Nesneler Farklý!");
  }
コード例 #7
0
  @Test
  public void test1() {

    System.out.println(Singleton.getInstance());
    System.out.println(Singleton.getInstance());

    System.out.println();

    System.out.println(Singleton2.getInstance());
    System.out.println(Singleton2.getInstance());
  }
コード例 #8
0
  public static void main(String[] args) {
    System.out.println("Start.");
    Singleton obj1 = Singleton.getInstance();
    Singleton obj2 = Singleton.getInstance();

    if (obj1 == obj2) {
      System.out.println("obj1 と obj2 は同じインスタンスです。");
    } else {
      System.out.println("obj1 と obj2 は同じインスタンスではありません。");
    }

    System.out.println("End.");
  }
コード例 #9
0
ファイル: App.java プロジェクト: ppot/LOG120-TP4
  /** Initialize the contents of the frame. */
  private void initialize() {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame = new JFrame();
    frame.setSize(1050, 781);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    int x = (dim.width - frame.getSize().width) / 2;
    int y = (dim.height - frame.getSize().height) / 2;
    frame.setLocation(x, y);
    // top
    AppMenu mn = new AppMenu();
    JPanel container = new JPanel();
    JPanel top = new JPanel();
    preview = new Canvas("PREVIEW", false, false, new Dimension(200, 200));
    top.add(preview);
    BorderLayout border = new BorderLayout();
    container.setLayout(border);
    container.add(mn, BorderLayout.NORTH);
    container.add(top, BorderLayout.SOUTH);
    frame.getContentPane().add(container, BorderLayout.NORTH);

    // left
    JPanel leftContainner = new JPanel();
    BorderLayout leftLyout = new BorderLayout();
    leftContainner.setLayout(leftLyout);

    JPanel left = new JPanel();
    move = new Canvas("MOVE", true, false, new Dimension(500, 500));
    left.add(move);
    leftContainner.add(left, BorderLayout.SOUTH);
    frame.getContentPane().add(leftContainner, BorderLayout.WEST);

    // right
    JPanel rightContainner = new JPanel();
    BorderLayout rightLyout = new BorderLayout();
    rightContainner.setLayout(rightLyout);
    JPanel right = new JPanel();
    zoom = new Canvas("ZOOM", false, true, new Dimension(500, 500));
    right.add(zoom);
    rightContainner.add(right, BorderLayout.SOUTH);
    frame.getContentPane().add(rightContainner, BorderLayout.EAST);
    Singleton.getInstance().getPreview().register(preview);
    Singleton.getInstance().getEdit().register(move);
    Singleton.getInstance().getEdit().register(zoom);

    preview.setSubject(Singleton.getInstance().getPreview());
    move.setSubject(Singleton.getInstance().getEdit());
    zoom.setSubject(Singleton.getInstance().getEdit());

    Singleton.getInstance().getWarpper().setTopCanvas(this.preview);
    Singleton.getInstance().getWarpper().setLeftCanvas(this.move);
    Singleton.getInstance().getWarpper().setRightCanvas(this.zoom);
  }
コード例 #10
0
ファイル: BreakSingleton.java プロジェクト: rslakra/Projects
  public static void breakSingletonWithSerialization() {
    System.out.println();

    final String fileName = "singleton.ser";
    // getting singleton instance
    Singleton instanceOne = Singleton.getInstance();
    instanceOne.setValue(10);

    try {
      // Serialize to a file
      ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream(fileName));
      objectOutput.writeObject(instanceOne);
      objectOutput.close();

      // now changed the value of singleton
      instanceOne.setValue(20);

      // Serialize to a file
      ObjectInput objectInput = new ObjectInputStream(new FileInputStream(fileName));
      Singleton instanceTwo = (Singleton) objectInput.readObject();
      objectInput.close();

      System.out.println("Instance One Value= " + instanceOne.getValue());
      System.out.println("Instance Two Value= " + instanceTwo.getValue());

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
コード例 #11
0
  public static void ImprimirFiguras() {
    Singleton x = Singleton.getInstance();

    for (FiguraGeometrica figura : x.getFiguras()) {
      System.out.println(figura);
      System.out.println();
    }
  }
コード例 #12
0
ファイル: BreakSingleton.java プロジェクト: rslakra/Projects
    public void run() {
      Singleton threadSingleton = Singleton.getInstance();
      synchronized (BreakSingleton.class) {
        if (singleton == null) singleton = threadSingleton;
      }

      System.out.println("Thread 1st Object Hash:" + singleton.hashCode());
      System.out.println("Thread 2nd Object Hash:" + threadSingleton.hashCode());
    }
コード例 #13
0
ファイル: Job.java プロジェクト: lokinell/apiTest
 @Override
 public void run() {
   // TODO Auto-generated method stub
   try {
     System.out.println(Singleton.getInstance(a).getName());
   } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #14
0
  public FormAddFolderFromButton(IHMcodeMirror IHM) {
    super();
    this.IHMcodeMirror = IHM;

    WindowFactory.setParameters(this, "Create New Folder", 350, 280);

    this.addCloseClickHandler(
        new CloseClickHandler() {
          @Override
          public void onCloseClick(CloseClientEvent closeClientEvent) {
            hide();
          }
        });

    DynamicForm form = new DynamicForm();
    form.setPadding(5);
    form.setLayoutAlign(VerticalAlignment.BOTTOM);

    textItem = new TextItem();
    textItem.setTitle("Name");
    textItem.setRequired(true);

    IButton ok = new IButton("Ok");
    form.setFields(textItem);
    this.addItem(form);
    this.addItem(ok);

    treeGrid = Singleton.getInstance().loadFileSystemLight(IHMcodeMirror.getAbstractItemRoot());
    this.addItem(treeGrid);

    ok.addClickHandler(
        new ClickHandler() {
          @Override
          public void onClick(ClickEvent clickEvent) {
            AbstractItem item =
                (AbstractItem) treeGrid.getSelectedRecord().getAttributeAsObject("abstractItem");
            item.setPath(item.getPath() + textItem.getEnteredValue());

            repositoryToolsServices.createFolderIntoLocalRepository(
                item,
                new AsyncCallback<Boolean>() {
                  @Override
                  public void onFailure(Throwable throwable) {}

                  @Override
                  public void onSuccess(Boolean bool) {
                    hide();
                    Singleton.getInstance()
                        .loadFileSystem(
                            IHMcodeMirror.getAbstractItemRoot(), IHMcodeMirror.getSystemFileRoot());
                  }
                });
          }
        });
  }
コード例 #15
0
ファイル: Featured.java プロジェクト: sammyplexus/MajorApp
  public void update_profile(View view) {
    progressDialog.setMessage("Loading");
    progressDialog.show();
    phone_number = (TextView) findViewById(R.id.phone_number_update);
    location = (TextView) findViewById(R.id.location);
    phone_number1 = phone_number.getText().toString();
    location1 = location.getText().toString();

    if (phone_number1.length() < 10 || location1.length() < 3) {
      Toast.makeText(this, "Please ensure you have inserted all your details", Toast.LENGTH_LONG)
          .show();
    } else {
      try {
        StringRequest theReq =
            new StringRequest(
                Request.Method.POST,
                "http://www.samuelagbede.com/coza_social/update_profile_details.php",
                new Response.Listener<String>() {
                  @Override
                  public void onResponse(String response) {
                    progressDialog.hide();
                    Toast.makeText(Featured.this, "Successfully updated", Toast.LENGTH_LONG).show();
                    phone_number.setText("");
                    location.setText("");
                  }
                },
                new Response.ErrorListener() {
                  @Override
                  public void onErrorResponse(VolleyError error) {
                    progressDialog.hide();
                    Toast.makeText(
                            Featured.this,
                            "Not updated. Check your internet connection please",
                            Toast.LENGTH_LONG)
                        .show();
                  }
                }) {
              @Override
              protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", username1);
                params.put("phone_number", phone_number1);
                params.put("location", location1);

                return params;
              }
            };
        Singleton.getInstance(this).addToRequestQueue(theReq);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #16
0
  @Test
  public void singletonTest() {
    // create singleton instances
    final Singleton singleton1 = Singleton.getInstance();
    final Singleton singleton2 = Singleton.getInstance();
    final Singleton singleton3 = Singleton.getInstance();

    // assert that the random number is the same thereby
    // ensuring we are dealing with a single object instance
    final int rand = singleton1.getRand();
    assertEquals(rand, singleton2.getRand());
    assertEquals(rand, singleton3.getRand());

    // set a string message on a singleton
    final String message = "Singleton2 message";
    singleton2.setMessage(message);

    // read the string message from the singletons
    assertEquals(message, singleton1.getMessage());
    assertEquals(message, singleton3.getMessage());
  }
コード例 #17
0
ファイル: BreakSingleton.java プロジェクト: rslakra/Projects
 public static void breakSingletonWithClone() {
   System.out.println();
   final String fileName = "singleton.ser";
   // getting singleton instance
   Singleton singleton = Singleton.getInstance();
   singleton.setValue(10);
   try {
     Singleton clonedObject = (Singleton) singleton.clone();
     System.out.println(clonedObject);
     System.out.println(clonedObject.hashCode());
   } catch (CloneNotSupportedException e) {
     e.printStackTrace();
   }
 }
コード例 #18
0
ファイル: Singleton.java プロジェクト: Sebb767/Prog
  public static void main(String[] args) {

    System.out.println("Start der Tests...");

    Singleton s1 = Singleton.getInstance();
    Singleton s2 = Singleton.getInstance();

    if (s1 == null) {
      System.out.println("Fehler: getInstance liefert beim ersten Aufruf null zurueck.");
      return;
    }

    if (s2 == null) {
      System.out.println("Fehler: getInstance liefert beim zweiten Aufruf null zurueck.");
      return;
    }

    s1.i = 17;

    if (s2.i == 17) System.out.println("Ihre Singleton-Implementierung ist korrekt.");
    else System.out.println("Ihre Singleton-Implementierung ist fehlerhaft.");

    System.out.println("Testende");
  }
コード例 #19
0
ファイル: Featured.java プロジェクト: sammyplexus/MajorApp
  public void comments_enter(View view) {
    progressDialog.setMessage("Please hold on");
    progressDialog.show();
    final TextView comments = (TextView) findViewById(R.id.devo_comments);
    comments1 = comments.getText().toString();
    final String devo_id = Devotional.devotional_id;

    if (comments1.equals("") || comments1.length() < 4) {
      progressDialog.hide();
      Toast.makeText(this, "Please enter a valid comment", Toast.LENGTH_LONG).show();
    } else {
      connectUrl = "http://www.samuelagbede.com/coza_social/insert_devotional_comments.php";

      StringRequest jor =
          new StringRequest(
              Request.Method.POST,
              connectUrl,
              new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                  Log.d("Comments Inserted", response);
                  progressDialog.hide();
                  Toast.makeText(Featured.this, "Comments entered successfully", Toast.LENGTH_LONG)
                      .show();
                  comments.setText(" ");
                }
              },
              new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  Log.d("Error", error.toString());
                }
              }) {

            @Override
            protected Map<String, String> getParams() {
              Map<String, String> params = new HashMap<String, String>();
              params.put("username", username1);
              params.put("comments", comments1);
              params.put("email_add", email_address1);
              params.put("devotional", devo_id);

              return params;
            }
          };
      Singleton.getInstance(this).addToRequestQueue(jor);
    }
  }
コード例 #20
0
ファイル: BreakSingleton.java プロジェクト: rslakra/Projects
  public static void breakSingletonWithReflection() {
    System.out.println();

    Singleton instanceOne = Singleton.getInstance();
    instanceOne.printHashCode();
    System.out.println(instanceOne.hashCode());

    Singleton instanceTwo = null;
    try {
      Constructor<?>[] constructors = Singleton.class.getDeclaredConstructors();
      for (Constructor<?> constructor : constructors) {
        // should break the rule here.
        constructor.setAccessible(true);
        instanceTwo = (Singleton) constructor.newInstance();
        break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    instanceTwo.printHashCode();
    System.out.println(instanceTwo.hashCode());
  }
コード例 #21
0
ファイル: SingletonMain.java プロジェクト: nevahn/j2
 public static void main(String[] args) {
   Singleton singleton1 = Singleton.getInstance();
   Singleton singleton2 = Singleton.getInstance();
   Singleton singleton3 = Singleton.getInstance();
 }
コード例 #22
0
public class TestHBObjectMapper {
  List<Triplet<HBRecord, String, Class<? extends IllegalArgumentException>>>
      invalidRecordsAndErrorMessages =
          Arrays.asList(
              triplet(
                  Singleton.getInstance(),
                  "A singleton class",
                  EmptyConstructorInaccessibleException.class),
              triplet(
                  new ClassWithNoEmptyConstructor(1),
                  "Class with no empty constructor",
                  NoEmptyConstructorException.class),
              triplet(
                  new ClassWithPrimitives(1f),
                  "A class with primitives",
                  MappedColumnCantBePrimitiveException.class),
              triplet(
                  new ClassWithTwoFieldsMappedToSameColumn(),
                  "Class with two fields mapped to same column",
                  FieldsMappedToSameColumnException.class),
              triplet(
                  new ClassWithBadAnnotationStatic(),
                  "Class with a static field mapped to HBase column",
                  MappedColumnCantBeStaticException.class),
              triplet(
                  new ClassWithBadAnnotationTransient("James", "Gosling"),
                  "Class with a transient field mapped to HBase column",
                  MappedColumnCantBeTransientException.class),
              triplet(
                  new ClassWithNoHBColumns(),
                  "Class with no fields mapped with HBColumn",
                  MissingHBColumnFieldsException.class),
              triplet(
                  new ClassWithNoHBRowKeys(),
                  "Class with no fields mapped with HBRowKey",
                  MissingHBRowKeyFieldsException.class),
              triplet(
                  new ClassesWithFieldIncomptibleWithHBColumnMultiVersion.NotMap(),
                  "Class with an incompatible field (not Map) annotated with "
                      + HBColumnMultiVersion.class.getName(),
                  IncompatibleFieldForHBColumnMultiVersionAnnotationException.class),
              triplet(
                  new ClassesWithFieldIncomptibleWithHBColumnMultiVersion.NotNavigableMap(),
                  "Class with an incompatible field (not NavigableMap) annotated with "
                      + HBColumnMultiVersion.class.getName(),
                  IncompatibleFieldForHBColumnMultiVersionAnnotationException.class),
              triplet(
                  new ClassesWithFieldIncomptibleWithHBColumnMultiVersion.EntryKeyNotLong(),
                  "Class with an incompatible field (NavigableMap's entry key not Long) annotated with "
                      + HBColumnMultiVersion.class.getName(),
                  IncompatibleFieldForHBColumnMultiVersionAnnotationException.class));

  HBObjectMapper hbMapper = new HBObjectMapper();
  List<Citizen> validObjs = TestObjects.validObjs;

  Result someResult = hbMapper.writeValueAsResult(validObjs.get(0));
  Put somePut = hbMapper.writeValueAsPut(validObjs.get(0));

  @Test
  public void testHBObjectMapper() {
    for (Citizen obj : validObjs) {
      System.out.printf("Original object: %s%n", obj);
      testResult(obj);
      testResultWithRow(obj);
      testPut(obj);
      testPutWithRow(obj);
    }
  }

  public void testResult(HBRecord p) {
    long start, end;
    start = System.currentTimeMillis();
    Result result = hbMapper.writeValueAsResult(p);
    end = System.currentTimeMillis();
    System.out.printf("Time taken for POJO->Result = %dms%n", end - start);
    start = System.currentTimeMillis();
    Citizen pFromResult = hbMapper.readValue(result, Citizen.class);
    end = System.currentTimeMillis();
    assertEquals("Data mismatch after deserialization from Result", p, pFromResult);
    System.out.printf("Time taken for Result->POJO = %dms%n%n", end - start);
  }

  public void testResultWithRow(HBRecord p) {
    long start, end;
    Result result = hbMapper.writeValueAsResult(Arrays.asList(p)).get(0);
    ImmutableBytesWritable rowKey = Util.strToIbw(p.composeRowKey());
    start = System.currentTimeMillis();
    Citizen pFromResult = hbMapper.readValue(rowKey, result, Citizen.class);
    end = System.currentTimeMillis();
    assertEquals("Data mismatch after deserialization from Result+Row", p, pFromResult);
    System.out.printf("Time taken for Result+Row->POJO = %dms%n%n", end - start);
  }

  public void testPut(HBRecord p) {
    long start, end;
    start = System.currentTimeMillis();
    Put put = hbMapper.writeValueAsPut(Arrays.asList(p)).get(0);
    end = System.currentTimeMillis();
    System.out.printf("Time taken for POJO->Put = %dms%n", end - start);
    start = System.currentTimeMillis();
    Citizen pFromPut = hbMapper.readValue(put, Citizen.class);
    end = System.currentTimeMillis();
    assertEquals("Data mismatch after deserialization from Put", p, pFromPut);
    System.out.printf("Time taken for Put->POJO = %dms%n%n", end - start);
  }

  public void testPutWithRow(HBRecord p) {
    long start, end;
    Put put = hbMapper.writeValueAsPut(p);
    ImmutableBytesWritable rowKey = Util.strToIbw(p.composeRowKey());
    start = System.currentTimeMillis();
    Citizen pFromPut = hbMapper.readValue(rowKey, put, Citizen.class);
    end = System.currentTimeMillis();
    assertEquals("Data mismatch after deserialization from Put", p, pFromPut);
    System.out.printf("Time taken for Put->POJO = %dms%n%n", end - start);
  }

  @Test
  public void testInvalidRowKey() {
    Citizen e = TestObjects.validObjs.get(0);
    try {
      hbMapper.readValue("invalid row key", hbMapper.writeValueAsPut(e), Citizen.class);
      fail("Invalid row key should've thrown " + RowKeyCouldNotBeParsedException.class.getName());
    } catch (RowKeyCouldNotBeParsedException ex) {
      System.out.println(
          "For a simulate HBase row with invalid row key, below Exception was thrown as expected:\n"
              + ex.getMessage()
              + "\n");
    }
  }

  @Test
  public void testValidClasses() {
    assertTrue(hbMapper.isValid(Citizen.class));
    assertTrue(hbMapper.isValid(CitizenSummary.class));
  }

  @Test
  public void testInvalidClasses() {
    Set<String> exceptionMessages = new HashSet<String>();
    for (Triplet<HBRecord, String, Class<? extends IllegalArgumentException>> p :
        invalidRecordsAndErrorMessages) {
      HBRecord record = p.getValue0();
      Class recordClass = record.getClass();
      assertFalse(
          "Object mapper couldn't detect invalidity of class " + recordClass.getName(),
          hbMapper.isValid(recordClass));
      String errorMessage =
          p.getValue1()
              + " ("
              + recordClass.getName()
              + ") should have thrown an "
              + IllegalArgumentException.class.getName();
      String exMsgObjToResult = null,
          exMsgObjToPut = null,
          exMsgResultToObj = null,
          exMsgPutToObj = null;
      try {
        hbMapper.writeValueAsResult(record);
        fail(errorMessage + " while converting bean to Result");
      } catch (IllegalArgumentException ex) {
        assertEquals(
            "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
            p.getValue2(),
            ex.getClass());
        exMsgObjToResult = ex.getMessage();
      }
      try {
        hbMapper.writeValueAsPut(record);
        fail(errorMessage + " while converting bean to Put");
      } catch (IllegalArgumentException ex) {
        assertEquals(
            "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
            p.getValue2(),
            ex.getClass());
        exMsgObjToPut = ex.getMessage();
      }
      try {
        hbMapper.readValue(someResult, recordClass);
        fail(errorMessage + " while converting Result to bean");
      } catch (IllegalArgumentException ex) {
        assertEquals(
            "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
            p.getValue2(),
            ex.getClass());
        exMsgResultToObj = ex.getMessage();
      }
      try {
        hbMapper.readValue(
            new ImmutableBytesWritable(someResult.getRow()), someResult, recordClass);
        fail(errorMessage + " while converting Result to bean");
      } catch (IllegalArgumentException ex) {
        assertEquals(
            "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
            p.getValue2(),
            ex.getClass());
      }
      try {
        hbMapper.readValue(somePut, recordClass);
        fail(errorMessage + " while converting Put to bean");
      } catch (IllegalArgumentException ex) {
        assertEquals(
            "Mismatch in type of exception thrown for " + recordClass.getSimpleName(),
            p.getValue2(),
            ex.getClass());
        exMsgPutToObj = ex.getMessage();
      }
      try {
        hbMapper.readValue(new ImmutableBytesWritable(somePut.getRow()), somePut, recordClass);
        fail(errorMessage + " while converting row key and Put combo to bean");
      } catch (IllegalArgumentException ex) {
        assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass());
      }
      assertEquals(
          "Validation for 'conversion to Result' and 'conversion to Put' differ in code path",
          exMsgObjToResult,
          exMsgObjToPut);
      assertEquals(
          "Validation for 'conversion from Result' and 'conversion from Put' differ in code path",
          exMsgResultToObj,
          exMsgPutToObj);
      assertEquals(
          "Validation for 'conversion from bean' and 'conversion to bean' differ in code path",
          exMsgObjToResult,
          exMsgResultToObj);
      System.out.printf(
          "%s threw below Exception as expected:\n%s\n%n", p.getValue1(), exMsgObjToResult);
      if (!exceptionMessages.add(exMsgObjToPut)) {
        fail("Same error message for different invalid inputs");
      }
    }
  }

  @Test
  public void testInvalidObjs() {
    for (Triplet<HBRecord, String, Class<? extends IllegalArgumentException>> p :
        TestObjects.invalidObjs) {
      HBRecord record = p.getValue0();
      String errorMessage =
          "An object with " + p.getValue1() + " should've thrown an " + p.getValue2().getName();
      try {
        hbMapper.writeValueAsResult(record);
        fail(errorMessage + " while converting bean to Result\nFailing object = " + record);
      } catch (IllegalArgumentException ex) {
        assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass());
      }
      try {
        hbMapper.writeValueAsPut(record);
        fail(errorMessage + " while converting bean to Put\nFailing object = " + record);
      } catch (IllegalArgumentException ex) {
        assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass());
      }
    }
  }

  @Test
  public void testEmptyResults() {
    Result nullResult = null,
        emptyResult = new Result(),
        resultWithBlankRowKey = new Result(new ImmutableBytesWritable(new byte[] {}));
    Citizen nullCitizen = hbMapper.readValue(nullResult, Citizen.class);
    assertNull("Null Result object should return null", nullCitizen);
    Citizen emptyCitizen = hbMapper.readValue(emptyResult, Citizen.class);
    assertNull("Empty Result object should return null", emptyCitizen);
    assertNull(hbMapper.readValue(resultWithBlankRowKey, Citizen.class));
  }

  @Test
  public void testEmptyPuts() {
    Put nullPut = null, emptyPut = new Put(), putWithBlankRowKey = new Put(new byte[] {});
    Citizen nullCitizen = hbMapper.readValue(nullPut, Citizen.class);
    assertNull("Null Put object should return null", nullCitizen);
    Citizen emptyCitizen = hbMapper.readValue(emptyPut, Citizen.class);
    assertNull("Empty Put object should return null", emptyCitizen);
    assertNull(hbMapper.readValue(putWithBlankRowKey, Citizen.class));
  }

  @Test
  public void testGetRowKey() {
    ImmutableBytesWritable rowKey =
        hbMapper.getRowKey(
            new HBRecord() {
              @Override
              public String composeRowKey() {
                return "rowkey";
              }

              @Override
              public void parseRowKey(String rowKey) {}
            });
    assertEquals("Row keys don't match", rowKey, Util.strToIbw("rowkey"));
    try {
      hbMapper.getRowKey(
          new HBRecord() {
            @Override
            public String composeRowKey() {
              return null;
            }

            @Override
            public void parseRowKey(String rowKey) {}
          });
      fail("null row key should've thrown a " + RowKeyCantBeEmptyException.class.getName());
    } catch (RowKeyCantBeEmptyException ignored) {

    }
    try {
      hbMapper.getRowKey(
          new HBRecord() {
            @Override
            public String composeRowKey() {
              throw new RuntimeException("Some blah");
            }

            @Override
            public void parseRowKey(String rowKey) {}
          });
      fail(
          "If row key can't be composed, an "
              + RowKeyCantBeComposedException.class.getName()
              + " was expected");
    } catch (RowKeyCantBeComposedException ignored) {

    }
    try {
      hbMapper.getRowKey(null);
      fail("If object is null, a " + NullPointerException.class.getName() + " was expected");
    } catch (NullPointerException ignored) {

    }
  }

  @Test
  public void testUninstantiatableClass() {
    try {
      hbMapper.readValue(someResult, UninstantiatableClass.class);
      fail(
          "If class can't be instantiated, a "
              + ObjectNotInstantiatableException.class.getName()
              + " was expected");
    } catch (ObjectNotInstantiatableException e) {

    }
  }

  @Test
  public void testHBColumnMultiVersion() {
    Double[] testNumbers = new Double[] {3.14159, 2.71828, 0.0};
    for (Double n : testNumbers) {
      // Written as unversioned, read as versioned
      Result result = hbMapper.writeValueAsResult(new CrawlNoVersion("key").setF1(n));
      Crawl versioned = hbMapper.readValue(result, Crawl.class);
      NavigableMap<Long, Double> columnHistory = versioned.getF1();
      assertEquals("Column history size mismatch", 1, columnHistory.size());
      assertEquals(
          String.format(
              "Inconsistency between %s and %s",
              HBColumn.class.getSimpleName(), HBColumnMultiVersion.class.getSimpleName()),
          n,
          columnHistory.lastEntry().getValue());
      // Written as versioned, read as unversioned
      Result result1 =
          hbMapper.writeValueAsResult(
              new Crawl("key")
                  .addF1(Double.MAX_VALUE)
                  .addF1(Double.MAX_VALUE)
                  .addF1(Double.MAX_VALUE)
                  .addF1(n));
      CrawlNoVersion unversioned = hbMapper.readValue(result1, CrawlNoVersion.class);
      Double f1 = unversioned.getF1();
      assertEquals(
          String.format(
              "Inconsistency between %s and %s",
              HBColumnMultiVersion.class.getSimpleName(), HBColumn.class.getSimpleName()),
          n,
          f1);
    }
  }
}
コード例 #23
0
 public static void main(String[] args) {
   Singleton obj = Singleton.getInstance();
   obj.showMessage();
 }
コード例 #24
0
ファイル: Test.java プロジェクト: derbaltasar/java2
 public static void main(String[] args) {
   Singleton singleton = Singleton.getInstance();
   singleton.methode();
 }
コード例 #25
0
 public void run() {
   Singleton obj = Singleton.getInstance();
   System.out.println(getName() + ": obj = " + obj);
 }
コード例 #26
0
 public static void main(String args[]) {
   Singleton tmp = Singleton.getInstance();
 }
コード例 #27
0
 public static void main(String[] args) {
   Singleton s = Singleton.getInstance();
   System.out.println(s.count1);
   System.out.println(s.count2);
 }
コード例 #28
0
ファイル: SingletonTest.java プロジェクト: Kasokaso/test
  public static void main(String[] args) {

    Singleton test = Singleton.getInstance();
  }