private Part bindPart(PartModel model) {
    Part part = null;
    try {
      if (model != null && model.getPartNumber().length() > 0) {
        part = entityManager.find(Part.class, model.getPartNumber());
        if (part != null) {
          part.setName(model.getName());
          part.setCountNeeded(model.getCountNeeded());
          part.setStockCount(model.getStockCount());
          if (model.getPhoto() != null) {
            part.setPhoto(model.getPhoto());
          }
          part.setPhoto(model.getPhoto());
        } else if (part == null) {
          part = new Part();
          part.setName(model.getName());
          part.setPartNumber(model.getPartNumber());
          part.setCountNeeded(model.getCountNeeded());
          part.setStockCount(model.getStockCount());
          if (model.getPhoto() != null) {
            part.setPhoto(model.getPhoto());
          }
          part.setPhoto(model.getPhoto());
        }
      }
    } catch (NullPointerException e) {
      throw new IllegalArgumentException(e.getMessage());
    }

    return part;
  }
  public String[] getSessionHTML(HttpSession session, HttpServletRequest request)
      throws ServletException, IOException {

    String user = null;
    String group = null;
    String userName = null;
    String groupname = null;
    String redirect = "";
    try {

      redirect = UserRecord;
      if (session.getAttribute("user") == null) {

        session.invalidate();
        request.getRequestDispatcher(redirect).include(request, response);
      } else {
        user = (String) session.getAttribute("user");
        group = (String) session.getAttribute("group");
      }
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("user")) sess[0] = cookie.getValue();
          if (cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
          if (cookie.getName().equals("group")) sess[1] = cookie.getValue();
          break;
        }
      }

    } catch (NullPointerException n) {
      n.printStackTrace();
    }
    return sess;
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_details, container, false);
    toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
    posterText = (TextView) rootView.findViewById(R.id.posterTitle);
    posterBar = (ImageView) rootView.findViewById(R.id.posterImage);
    dateText = (TextView) rootView.findViewById(R.id.release_date);
    durationText = (TextView) rootView.findViewById(R.id.duration);
    voteText = (TextView) rootView.findViewById(R.id.average_vote);
    overviewText = (TextView) rootView.findViewById(R.id.overview);
    trailerListView = (ListView) rootView.findViewById(R.id.trailerListView);
    trailerListView.setOnItemClickListener(this);
    reviewListView = (ListView) rootView.findViewById(R.id.reviewListView);
    trailerLinear = (LinearLayout) rootView.findViewById(R.id.trailer_linear);
    reviewLinear = (LinearLayout) rootView.findViewById(R.id.review_linear);
    toggleBtn = (ToggleButton) rootView.findViewById(R.id.toggle);
    toggleBtn.setOnClickListener(this);
    Log.i("isNull", getArguments() == null ? "ok" : "no");

    if (toolbar != null) {
      // onePane Mode
      ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
      try {
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      } catch (NullPointerException e) {
        e.printStackTrace();
      }
    }

    curd = new CURD(getActivity(), movie);
    return rootView;
  }
示例#4
0
  /*
   * This method will open a file that the user chooses,
   * then store the data from the file into a StringBuffer.
   */
  public static StringBuffer openFile() {
    StringBuffer fileContents =
        new StringBuffer(); // Declares the String buffer to hold text in the text file.
    JFileChooser chooser =
        new JFileChooser(); // Declares the JFileChooser object to let the user choose their file.
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");

    chooser.setFileFilter(filter); // Adds the fileNameExtensionFilter into the JFileChooser
    chooser.showOpenDialog(null); // Displays an open dialog window.

    File targetFile =
        chooser.getSelectedFile(); // Assigns the chosen file to the variable targetFile.

    try {
      Scanner myScanner =
          new Scanner(
              targetFile); // Declares and instantiates our Scanner object for reading the file.
      while (myScanner.hasNextLine()) { // Our loop will check to ensure there is a line there.
        // This line of code takes the nextLine of text from the file and appends it to our
        // StringBuffer.
        fileContents.append(myScanner.nextLine() + "\r\n");
      }
      myScanner.close(); // Closes our scanner object so that we're not wasting resources.
    } catch (NullPointerException event) {
      System.out.println("We've encountered a NullPointerException");
      event.printStackTrace();
    } catch (FileNotFoundException event) {
      System.out.println("We've encountered a FileNotFoundException");
      event.printStackTrace();
    }

    return new StringBuffer(
        fileContents); // Returns a new StringBuffer item which will contain the text from the file.
  }
示例#5
0
  public boolean intersects(int x, int y, Rectangle rectangle) {
    try {
      Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1);
      Rectangle right =
          new Rectangle(
              rectangle.getX() + rectangle.getWidth() + 1,
              rectangle.getY(),
              1,
              rectangle.getHeight());
      Rectangle down =
          new Rectangle(
              rectangle.getX(),
              rectangle.getY() + rectangle.getHeight() + 1,
              rectangle.getWidth(),
              1);
      Rectangle left =
          new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight());
      Rectangle rect = blocks[x][y].getRect();

      return (rect.intersects(up)
          || rect.intersects(right)
          || rect.intersects(down)
          || rect.intersects(left));
    } catch (NullPointerException e) {
      logger.log("NullPointerException in World.intersects(int, int, Rectangle)", Level.DEBUG);
      logger.log("Stack:", Level.DEBUG);
      logger.log(e.getMessage(), Level.DEBUG);
    }
    return false;
  }
示例#6
0
  @Override
  public void onBindViewHolder(final ViewHolder viewHolder, int i) {

    // set text
    if (viewHolder.tvDeviceName != null) {
      if (mDataset.get(i).getBondState() == BluetoothDevice.BOND_BONDED) {

        viewHolder.tvDeviceName.setTextColor(
            ContextCompat.getColor(activity, R.color.forest_green));
      }
      viewHolder.tvDeviceName.setText(mDataset.get(i).getName());
    }
    if (mDataset.get(i) != null) {
      try {
        if (!mDataset.get(i).getName().contains(A108prefix)) {

          viewHolder.ivDeviceIcon.setImageResource(R.mipmap.bt);
        }
      } catch (NullPointerException e) {
        e.printStackTrace();
      }
      if (viewHolder.tvDeviceMac != null)
        viewHolder.tvDeviceMac.setText(mDataset.get(i).getAddress());
    }
  }
示例#7
0
  /**
   * This function takes an OMGraphicList and loads each one with the array representing the records
   * in the dbf file. Each graphics stores the graphic in its object slot.
   */
  public void loadDbfModelIntoGraphics(OMGraphicList list) {
    if (list != null && dbfModel.getRowCount() > 0) {
      int numgraphics = list.size();

      for (int i = 0; i < numgraphics; i++) {
        try {
          OMGraphic omg = list.getOMGraphicAt(i);
          Integer recnum = (Integer) (omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE));
          // OFF BY ONE!!! The shape record numbers
          // assigned to the records start with 0, while
          // everything else we do starts with 0. The DbfTableModel
          // follows java convention and starts at 0. The integer
          // stored in the OMG should know it too.
          Object inforec = dbfModel.getRecord(recnum.intValue());
          omg.putAttribute(ShapeConstants.SHAPE_DBF_INFO_ATTRIBUTE, inforec);
        } catch (ClassCastException cce) {
          if (Debug.debugging("shape")) {
            cce.printStackTrace();
          }
        } catch (NullPointerException npe) {
          npe.printStackTrace();
        }
      }
    }
  }
 public List<ArrayList<Object>> getDataFromDB(String tableName) {
   List<ArrayList<Object>> dataDB = new ArrayList<ArrayList<Object>>();
   ResultSet res;
   try {
     int i = 0;
     res = statement.executeQuery("SELECT * FROM  " + tableName);
     ResultSetMetaData rsMetaData = res.getMetaData();
     int numberOfColumns = rsMetaData.getColumnCount();
     for (int u = 0; u < numberOfColumns; u++) {
       dataDB.add(new ArrayList<Object>());
     }
     while (res.next()) {
       for (int j = 1; j <= numberOfColumns /* cols size */; j++) {
         dataDB.get(j - 1).add("" + res.getString(j));
       }
       i++;
     }
     return dataDB;
   } catch (SQLException e) {
     e.printStackTrace();
     return null;
   } catch (NullPointerException k) {
     k.printStackTrace();
   }
   return null;
 }
 /**
  * Gets the connection.
  *
  * @param databaseName the database name
  * @param databaseIP the database ip
  * @return the connection
  * @throws Exception the exception
  */
 public Connection getConnection(String databaseName, String databaseIP) /*    */ throws Exception
       /*    */ {
   StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
   Properties properties = new EncryptableProperties(encryptor);
   try {
     properties.load(this.getClass().getClassLoader().getResourceAsStream("mysql.properties"));
   } catch (FileNotFoundException fnfe) {
     fnfe.printStackTrace();
     throw fnfe;
   } catch (NullPointerException fnfe) {
     fnfe.printStackTrace();
     throw fnfe;
   }
   String username = properties.getProperty("mysql.user");
   encryptor.setPassword(username); // could be got from web, env variable...
   String passwd = properties.getProperty("mysql.password");
   String port = properties.getProperty("mysql.port");
   databaseIP = properties.getProperty("mysql.databaseIP", databaseIP);
   databaseName = properties.getProperty("mysql.databaseName", databaseName);
   /*    */
   try {
     /* 49 */ Connection connection =
         DriverManager.getConnection(
             "jdbc:mysql://" + databaseIP + ":" + port + "/" + databaseName, username, passwd);
     /* 50 */ return connection;
     /*    */ }
   /*    */ catch (SQLException e)
   /*    */ {
     /* 59 */ e.printStackTrace();
     /* 60 */ throw e;
     /*    */ }
   /*    */ }
  private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See:
    // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
      try {
        makeRequest();
        return;
      } catch (IOException e) {
        cause = e;
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      } catch (NullPointerException e) {
        // there's a bug in HttpClient 4.0.x that on some occasions causes
        // DefaultRequestExecutor to throw an NPE, see
        // http://code.google.com/p/android/issues/detail?id=5255
        cause = new IOException("NPE in HttpClient" + e.getMessage());
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      }
    }

    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
  }
示例#11
0
 /**
  * Returns the response body as string.<br>
  * Disconnects the internal HttpURLConnection silently.
  *
  * @return response body
  * @throws WeiboException
  */
 public String asString() throws WeiboException {
   if (null == responseAsString) {
     BufferedReader br;
     try {
       InputStream stream = asStream();
       if (null == stream) {
         return null;
       }
       br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
       StringBuffer buf = new StringBuffer();
       String line;
       while (null != (line = br.readLine())) {
         buf.append(line).append("\n");
       }
       this.responseAsString = buf.toString();
       if (Configuration.isDalvik()) {
         this.responseAsString = unescape(responseAsString);
       }
       log(responseAsString);
       stream.close();
       con.disconnect();
       streamConsumed = true;
     } catch (NullPointerException npe) {
       // don't remember in which case npe can be thrown
       throw new WeiboException(npe.getMessage(), npe);
     } catch (IOException ioe) {
       throw new WeiboException(ioe.getMessage(), ioe);
     }
   }
   return responseAsString;
 }
 /**
  * @param clazz
  * @param constantName
  * @param declared
  * @return
  */
 public static String getStringConstant(Class<?> clazz, String constantName, boolean declared) {
   Field compType = null;
   try {
     // check if there's a
     // public static final String COMPONENT_TYPE = "...";
     compType = declared ? clazz.getDeclaredField(constantName) : clazz.getField(constantName);
   } catch (SecurityException e) {
     // if no such field, fall through
   } catch (NoSuchFieldException e) {
     // if no such field, fall through
   }
   if (null == compType) return null;
   int modifiers = compType.getModifiers();
   if (!Modifier.isStatic(modifiers)
       || !Modifier.isPublic(modifiers)
       || !Modifier.isFinal(modifiers)
       || String.class != compType.getType()) {
     return null;
   }
   try {
     return (String) compType.get(null);
   } catch (IllegalArgumentException e1) {
     // shouldn't happen - the arg is of the correct type
     e1.printStackTrace();
   } catch (IllegalAccessException e1) {
     // shouldn't happen - the method is public
     e1.printStackTrace();
   } catch (NullPointerException e1) {
     // shouldn't happen - allowed a null arg when
     // the field is static
     e1.printStackTrace();
   }
   return null;
 }
  public void setCertificate(String KeyStore, String KeyPass, String TrustStore, String TrustPass) {
    this.keyStore = KeyStore;
    this.keyPass = KeyPass;
    this.trustStore = TrustStore;
    this.trustPass = TrustPass;

    try {
      ClassLoader loader = getClass().getClassLoader();
      String certificate = "";
      URL kURL = loader.getResource("certificate/" + KeyStore);
      certificate = kURL.toString().replace("file:/", "");
      System.setProperty("javax.net.ssl.keyStore", certificate);
      System.setProperty("javax.net.ssl.keyStorePassword", KeyPass);
      System.setProperty("javax.net.ssl.keyStoreType", "JKS");

      URL tURL = loader.getResource("certificate/" + TrustStore);
      certificate = tURL.toString().replace("file:/", "");
      System.setProperty("javax.net.ssl.trustStore", certificate);
      System.setProperty("javax.net.ssl.trustStorePassword", TrustPass);
      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    } catch (NullPointerException e) {
      e.printStackTrace();
      logger.error(e.toString());
    }
  }
示例#14
0
  private boolean isdifferent(Document testDoc, Document controlDoc) {
    boolean isdifferent = false;

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setNormalize(true);

    Diff myDiff = new Diff(controlDoc, testDoc);
    DetailedDiff myComparisonController = new DetailedDiff(myDiff);
    DifferenceEngine engine = new DifferenceEngine(myComparisonController);
    XmlDifferenceListener listener = new XmlDifferenceListener();
    ElementNameAndAttributeQualifier myElementQualifier = new ElementNameAndAttributeQualifier();
    try { // debug
      engine.compare(
          controlDoc.getDocumentElement(),
          testDoc.getDocumentElement(),
          listener,
          myElementQualifier);
    } catch (NullPointerException ne) {
      LOG.error("NPE: " + ne.getMessage(), ne);
    }

    isdifferent = listener.called();
    return isdifferent;
  }
  public void saveInfo() {
    PrintWriter writer;
    boolean isOpen = false;

    try {
      writer = new PrintWriter(userFile);
      isOpen = true;
    } catch (Exception ex) {
      System.out.println("there was an error");
      System.out.println(ex.getMessage());
      isOpen = false;
      writer = null;
    }

    try {
      writer.write(toString());
      writer.close();
    } catch (NullPointerException ex) {
      System.out.println("there was a null pointer with the writer");
      System.out.println(ex.getMessage());
    } catch (Exception ex) {
      System.out.println("there was an error");
      System.out.println(ex.getMessage());
    }
  }
示例#16
0
 /**
  * @param pcat
  * @param array
  * @param coordTab
  * @param flagIgnore
  */
 private static void fillXMatchArray(
     Pcat pcat, double[][] array, int[] coordTab, boolean[] flagIgnore) {
   Source o;
   String content;
   Iterator<Obj> it = pcat.iterator();
   for (int i = 0; it.hasNext(); i++) {
     o = (Source) it.next();
     // not needed
     //            flagIgnore[i] = false;
     try {
       // ra
       content = o.getValue(coordTab[0]);
       if (isSexa(content)) content = sexa2Deg(content, true);
       // array[i][0] = Double.parseDouble(content);
       array[i][0] = Double.valueOf(content).doubleValue();
       // dec
       content = o.getValue(coordTab[1]);
       if (isSexa(content)) content = sexa2Deg(content, false);
       // array[i][1] = Double.parseDouble(content);
       array[i][1] = Double.valueOf(content).doubleValue();
     } catch (NumberFormatException e) {
       e.printStackTrace();
       // ignore this source
       flagIgnore[i] = true;
       //                array[i][0] = array[i][1] = 0.0;
     } catch (NullPointerException npe) {
       npe.printStackTrace();
       // ignore this source
       flagIgnore[i] = true;
     }
   }
 }
  public void commit() throws ResourceException {
    if (DEBUG) {
      try {
        throw new NullPointerException("Asif:JCALocalTransaction:commit");
      } catch (NullPointerException npe) {
        npe.printStackTrace();
      }
    }
    LogWriter logger = cache.getLogger();
    if (logger.fineEnabled()) {
      logger.fine("JCALocalTransaction:invoked commit");
    }
    TXStateProxy tsp = this.gfTxMgr.getTXState();
    if (tsp != null && this.tid != tsp.getTransactionId()) {
      throw new IllegalStateException(
          "Local Transaction associated with Tid = "
              + this.tid
              + " attempting to commit a different transaction");
    }
    try {
      this.gfTxMgr.commit();
      this.tid = null;
    } catch (Exception e) {
      throw new LocalTransactionException(e.toString());
    }
    // Iterator<ConnectionEventListener> itr = this.listeners.iterator();
    // ConnectionEvent ce = new
    // ConnectionEvent(this,ConnectionEvent.LOCAL_TRANSACTION_COMMITTED);
    // while( itr.hasNext()) {
    // itr.next().localTransactionCommitted(ce);
    // }

  }
示例#18
0
 /** Test of get method, of class Jsr223JRubyBindings. */
 @Test
 public void testGet() {
   System.out.println("get");
   Object key = null;
   Object result = null;
   JRubyBindings instance =
       new JRubyBindings(new ScriptingContainer(LocalContextScope.THREADSAFE));
   Object expResult = null;
   try {
     result = instance.get(key);
   } catch (NullPointerException e) {
     expResult = "key is null";
     result = e.getMessage();
     assertEquals(expResult, result);
   }
   instance.put("abc", "aabc");
   instance.put("@abc", "abbc");
   instance.put(ScriptEngine.FILENAME, "defdef");
   expResult = "defdef";
   result = instance.get(ScriptEngine.FILENAME);
   assertEquals(expResult, result);
   expResult = "abbc";
   result = instance.get("@abc");
   assertEquals(expResult, result);
 }
示例#19
0
 private void btn_submeterActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btn_submeterActionPerformed
   try {
     if (!this.controller.validarSubmissao()) {
       throw new NullPointerException("A submissão já se encontra submetida.");
     }
     String opcoes[] = {"Sim", "Não"};
     int resposta =
         JOptionPane.showOptionDialog(
             null,
             "Pretende submeter o artigo?",
             "Submeter artigo",
             0,
             JOptionPane.QUESTION_MESSAGE,
             null,
             opcoes,
             opcoes[0]);
     if (resposta == 0) {
       this.controller.adicionarSubmissao();
     }
     dispose();
   } catch (IllegalArgumentException ex) {
     JOptionPane.showMessageDialog(
         this, ex.getMessage(), "Submeter Artigo", JOptionPane.ERROR_MESSAGE);
   } catch (NullPointerException ex) {
     JOptionPane.showMessageDialog(
         this, ex.getMessage(), "Submeter Artigo", JOptionPane.ERROR_MESSAGE);
     dispose();
   }
 } // GEN-LAST:event_btn_submeterActionPerformed
示例#20
0
 /** Test of putAll method, of class Jsr223JRubyBindings. */
 @Test
 public void testPutAll() {
   System.out.println("putAll");
   Map t = null;
   Object expResult = null;
   Object result = null;
   JRubyBindings instance =
       new JRubyBindings(new ScriptingContainer(LocalContextScope.THREADSAFE));
   try {
     instance.putAll(t);
   } catch (NullPointerException e) {
     expResult = "map is null";
     assertEquals(expResult, e.getMessage());
   }
   instance.put("ABC", "aaaa");
   t = new HashMap();
   t.put("abc", "aabc");
   t.put("@abc", "abbc");
   t.put("$abc", "abcc");
   instance.putAll(t);
   expResult = 4;
   result = instance.size();
   assertEquals(expResult, result);
   t.put(ScriptEngine.FILENAME, "filename");
   instance.putAll(t);
   expResult = 5;
   result = instance.size();
   assertEquals(expResult, result);
 }
示例#21
0
 /** Performs dispersal operations associated with the Occupant. */
 public void disperse() {
   try {
     propagules = disperser.disperse();
   } catch (NullPointerException e) {
     e.printStackTrace();
   }
 }
  public BookCatalogImpl() {

    try {

      final String filePath = path + "catalog.json";
      // read the json file
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      InputStream inputStream = classLoader.getResourceAsStream(filePath);

      BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
      bookStrBuilder = new StringBuilder();

      String inputStr;
      while ((inputStr = streamReader.readLine()) != null) bookStrBuilder.append(inputStr);

      final ObjectMapper mapper = new ObjectMapper();

      catalog = mapper.readValue(bookStrBuilder.toString(), new TypeReference<List<Book>>() {});

      hBookDetails = new Hashtable();

      for (Book book : catalog) {

        hBookDetails.put(book.getId(), book);
      }

    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (NullPointerException ex) {
      ex.printStackTrace();
    }
  }
示例#23
0
  @Override
  public View getView(Context context) {

    View view = LayoutInflater.from(context).inflate(getCardLayout(), null);

    mCardLayout = view;

    try {
      ((FrameLayout) view.findViewById(R.id.cardContent)).addView(getCardContent(context));
    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    // ((TextView) view.findViewById(R.id.title)).setText(this.title);

    LinearLayout.LayoutParams lp =
        new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    int bottom = Utils.convertDpToPixelInt(context, 12);
    lp.setMargins(0, 0, 0, bottom);

    view.setLayoutParams(lp);

    return view;
  }
示例#24
0
  private Object makeRequestWithRetries(HttpUriRequest request) throws IOException {

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
      try {
        HttpResponse response = client.execute(request, context);
        return entityHandler.handleEntity(response.getEntity(), null, charset);
      } catch (UnknownHostException e) {
        cause = e;
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      } catch (IOException e) {
        cause = e;
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      } catch (NullPointerException e) {
        // HttpClient 4.0.x 之前的一个bug
        // http://code.google.com/p/android/issues/detail?id=5255
        cause = new IOException("NPE in HttpClient" + e.getMessage());
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      } catch (Exception e) {
        cause = new IOException("Exception" + e.getMessage());
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      }
    }
    if (cause != null) throw cause;
    else throw new IOException("未知网络错误");
  }
示例#25
0
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    try {
      switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
          Drawable drawable = getDrawable();
          if (drawable != null) {
            drawable.mutate().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
          }
          break;
        case MotionEvent.ACTION_MOVE:
          break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
          Drawable drawableUp = getDrawable();
          if (drawableUp != null) {
            drawableUp.mutate().clearColorFilter();
          }
          break;
      }
    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    return super.onTouchEvent(event);
  }
示例#26
0
文件: Vote.java 项目: Tak31337/karma
  @Override
  public void run() {
    if (bot.hasMessage()) {
      message = bot.getMessage();
      channel = bot.getChannel();
      sender = bot.getSender();
    }

    if (this.message.startsWith("~vote")) {
      tokenize(false, 5, this.message);
      try {
        if ((voters != null) && (((Integer) voters.get(this.sender)).intValue() == 1)) {
          return;
        }
      } catch (NullPointerException ex) {
        ex.printStackTrace();
      }
      if (this.parameters.equalsIgnoreCase(" y")) {
        voteYes += 1;
        voters.put(this.sender, Integer.valueOf(1));
      } else if (this.parameters.equalsIgnoreCase(" n")) {
        voteNo += 1;
        voters.put(this.sender, Integer.valueOf(1));
      }

      Main.bot.sendMessage(this.channel, voteYes + " " + voteNo);
    }
  }
  /**
   * Uses {@link uk.ac.aber.cs211.wordladder.Generator} to produce a random word ladder. args[1] is
   * the initial word while args[2] is the depth of the word ladder to produce.
   *
   * @param args Command line arguments from invocation.
   */
  public static void generate(String[] args) {
    String startWord = null;
    int depth = 0;

    try {
      startWord = args[1];
      depth = Integer.parseInt(args[2]);
    } catch (NullPointerException e) {
      if (args.length < 3) {
        System.err.println("Insufficient arguments.");
        printHelp();
        System.exit(-1);
      }
      e.printStackTrace();
      System.exit(-1);
    }

    Generator generator = null;
    try {
      generator = new Generator().setStart(startWord).setDepth(depth);
    } catch (IOException e) {
      System.err.println("Could not load dictionaries. Check current working directory.");
      System.exit(-1);
    }

    List<String> solution = generator.run();
    if (solution == null) {
      System.err.println("A ladder of that depth is not possible.");
      System.exit(-1);
    }
    System.out.println(solution);
    System.exit(0);
  }
  /**
   * Sets up the GUI, ensuring that everything is loaded nicely.
   *
   * @param location
   * @param resources
   */
  public void initialize(URL location, ResourceBundle resources) {
    filter = new Filter();
    Set<String> books = new HashSet<>();
    for (Book book : Book.values()) {
      books.add(book.toString());
    }
    filter.setBooks(books);
    results.setItems(listItems);
    String index = "java_ebook_search/index";
    String home = "/java_ebook_search/view/index.html";

    try {
      search = new Search(index);
      commonTerms = TextFields.bindAutoCompletion(query, search.getAutocomplete());
      commonTerms.setVisibleRowCount(10);
      sc = new SpellCheck();
      webEngine = webView.getEngine();
      webEngine.load(getClass().getResource(home).toString());
      results
          .getSelectionModel()
          .selectedItemProperty()
          .addListener((observable, oldValue, newValue) -> loadResult(newValue));
    } catch (NullPointerException e) {
      System.out.println("It's happened again, ignore it");
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#29
0
  /**
   * @param data the data to store into the buffer
   * @param glBindType where OpenGL binds the buffer
   * @param glDrawType the way OpenGL draws the buffer
   */
  public GLBuffer(ArrayList<N> data, int glBindType, int glDrawType) {
    // First call super constructor
    this(data);

    String bindErr = "BIND";
    String drawErr = "DRAW";
    try {
      // Set fields
      this.glDrawType = GLDrawType.getType(glDrawType);
      this.glBindType = GLBindType.getType(glBindType);

      if (this.glBindType == null || this.glDrawType == null) {
        // Creates a string that indicates which values are null
        throw new NullPointerException(
            (this.glBindType == null ? bindErr : "") + (this.glDrawType == null ? drawErr : ""));
      }
    } catch (NullPointerException ex) {
      System.out.println("Could not match input to enumeration, setting necessary default values.");

      // Set to default whichever field was not configured correctly
      String errorStr = ex.toString();
      // Bind getType
      if (errorStr.contains(bindErr)) {
        System.err.println("glBindType does not match an enumerated type");
        this.glBindType = DEFAULT_BIND;

        // Draw getType
      } else if (errorStr.contains(drawErr)) {
        System.err.println("glDrawType does not match an enumerated type");
        this.glDrawType = DEFAULT_DRAW;
      }
    }
  }
  @Override
  public JSONRPC2Response process(Map<String, Object> params) {
    JSONRPC2Response resp = null;

    try {
      Integer id = HandlerUtils.<Number>fetchField(FSID, params, true, null).intValue();

      String status = FVConfigurationController.instance().flowSpaceStatus(id);
      resp = new JSONRPC2Response(status, 0);
    } catch (ClassCastException e) {
      resp =
          new JSONRPC2Response(
              new JSONRPC2Error(
                  JSONRPC2Error.INVALID_PARAMS.getCode(), cmdName() + ": " + e.getMessage()),
              0);
    } catch (MissingRequiredField e) {
      resp =
          new JSONRPC2Response(
              new JSONRPC2Error(
                  JSONRPC2Error.INVALID_PARAMS.getCode(), cmdName() + ": " + e.getMessage()),
              0);
    } catch (NullPointerException e) {
      e.printStackTrace();
    }
    return resp;
  }