Java Examples for android.location.Geocoder

The following java examples will help you to understand the usage of android.location.Geocoder. These source code samples are taken from different open source projects.

Example 1
Project: tuberun_android-master  File: ReverseGeocodeFetcher.java View source code
private void reverseGeocode(Location l) {
    final Geocoder myLocation = new Geocoder(context, Locale.getDefault());
    if (myLocation != null) {
        task = new AsyncTask<Double, Integer, List<Address>>() {

            @Override
            protected List<Address> doInBackground(Double... params) {
                List<Address> result = new ArrayList<Address>();
                try {
                    result = myLocation.getFromLocation(params[0], params[1], 1);
                } catch (Exception e) {
                    Log.w(getClass().toString(), e);
                }
                return result;
            }

            protected void onPostExecute(List<Address> res) {
                result = res;
                notifyClients();
            }
        };
        task.execute(l.getLatitude(), l.getLongitude());
    }
}
Example 2
Project: android-15-master  File: GeocoderTest.java View source code
public void testGeocoder() throws Exception {
    Locale locale = new Locale("en", "us");
    Geocoder g = new Geocoder(mContext, locale);
    List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
    assertNotNull(addresses1);
    assertEquals(1, addresses1.size());
    Address addr = addresses1.get(0);
    assertEquals("94305", addr.getFeatureName());
    assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
    assertEquals("USA", addr.getAddressLine(1));
    assertEquals("94305", addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
    List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
    assertNotNull(addresses2);
    assertEquals(1, addresses2.size());
    addr = addresses2.get(0);
    assertEquals("San Francisco", addr.getFeatureName());
    assertEquals("San Francisco, CA", addr.getAddressLine(0));
    assertEquals("United States", addr.getAddressLine(1));
    assertEquals("San Francisco", addr.getLocality());
    assertEquals("CA", addr.getAdminArea());
    assertEquals(null, addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}
Example 3
Project: property-db-master  File: GeocoderTest.java View source code
public void testGeocoder() throws Exception {
    Locale locale = new Locale("en", "us");
    Geocoder g = new Geocoder(mContext, locale);
    List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
    assertNotNull(addresses1);
    assertEquals(1, addresses1.size());
    Address addr = addresses1.get(0);
    assertEquals("94305", addr.getFeatureName());
    assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
    assertEquals("USA", addr.getAddressLine(1));
    assertEquals("94305", addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
    List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
    assertNotNull(addresses2);
    assertEquals(1, addresses2.size());
    addr = addresses2.get(0);
    assertEquals("San Francisco", addr.getFeatureName());
    assertEquals("San Francisco, CA", addr.getAddressLine(0));
    assertEquals("United States", addr.getAddressLine(1));
    assertEquals("San Francisco", addr.getLocality());
    assertEquals("CA", addr.getAdminArea());
    assertEquals(null, addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}
Example 4
Project: TweetTopics2.0-master  File: GetGeolocationAddressLoader.java View source code
@Override
public BaseResponse loadInBackground() {
    try {
        GetGeolocationAddressResponse response = new GetGeolocationAddressResponse();
        response.setSingleResult(request.getSingleResult());
        Geocoder geocoder = new Geocoder(request.getContext());
        List<Address> addresses;
        if (request.getSingleResult())
            addresses = geocoder.getFromLocationName(request.getText(), 1);
        else
            addresses = geocoder.getFromLocationName(request.getText(), 5);
        ArrayList<Address> address_list = new ArrayList<Address>();
        for (Address address : addresses) address_list.add(address);
        response.setAddressList(address_list);
        return response;
    } catch (IOException exception) {
        exception.printStackTrace();
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setError(exception, exception.getMessage());
        return errorResponse;
    }
}
Example 5
Project: WS171-frameworks-base-master  File: GeocoderTest.java View source code
public void testGeocoder() throws Exception {
    Locale locale = new Locale("en", "us");
    Geocoder g = new Geocoder(mContext, locale);
    List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
    assertNotNull(addresses1);
    assertEquals(1, addresses1.size());
    Address addr = addresses1.get(0);
    assertEquals("94305", addr.getFeatureName());
    assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
    assertEquals("USA", addr.getAddressLine(1));
    assertEquals("94305", addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
    List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
    assertNotNull(addresses2);
    assertEquals(1, addresses2.size());
    addr = addresses2.get(0);
    assertEquals("San Francisco", addr.getFeatureName());
    assertEquals("San Francisco, CA", addr.getAddressLine(0));
    assertEquals("United States", addr.getAddressLine(1));
    assertEquals("San Francisco", addr.getLocality());
    assertEquals("CA", addr.getAdminArea());
    assertEquals(null, addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}
Example 6
Project: android-sdk-sources-for-api-level-23-master  File: GeocoderTest.java View source code
public void testGeocoder() throws Exception {
    Locale locale = new Locale("en", "us");
    Geocoder g = new Geocoder(mContext, locale);
    List<Address> addresses1 = g.getFromLocation(37.435067, -122.166767, 2);
    assertNotNull(addresses1);
    assertEquals(1, addresses1.size());
    Address addr = addresses1.get(0);
    assertEquals("94305", addr.getFeatureName());
    assertEquals("Palo Alto, CA 94305", addr.getAddressLine(0));
    assertEquals("USA", addr.getAddressLine(1));
    assertEquals("94305", addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.4240385) > 0.1);
    List<Address> addresses2 = g.getFromLocationName("San Francisco, CA", 1);
    assertNotNull(addresses2);
    assertEquals(1, addresses2.size());
    addr = addresses2.get(0);
    assertEquals("San Francisco", addr.getFeatureName());
    assertEquals("San Francisco, CA", addr.getAddressLine(0));
    assertEquals("United States", addr.getAddressLine(1));
    assertEquals("San Francisco", addr.getLocality());
    assertEquals("CA", addr.getAdminArea());
    assertEquals(null, addr.getPostalCode());
    assertFalse(Math.abs(addr.getLatitude() - 37.77916) > 0.1);
}
Example 7
Project: android_packages_apps-master  File: MenuHelper.java View source code
private static void setLatLngDetails(final View d, Activity context, ExifInterface exif) {
    float[] latlng = new float[2];
    if (exif.getLatLong(latlng)) {
        setDetailsValue(d, String.valueOf(latlng[0]), R.id.details_latitude_value);
        setDetailsValue(d, String.valueOf(latlng[1]), R.id.details_longitude_value);
        if (latlng[0] == INVALID_LATLNG || latlng[1] == INVALID_LATLNG) {
            hideDetailsRow(d, R.id.details_latitude_row);
            hideDetailsRow(d, R.id.details_longitude_row);
            hideDetailsRow(d, R.id.details_location_row);
            return;
        }
        UpdateLocationCallback cb = new UpdateLocationCallback(new WeakReference<View>(d));
        Geocoder geocoder = new Geocoder(context);
        new ReverseGeocoderTask(geocoder, latlng, cb).execute();
    } else {
        hideDetailsRow(d, R.id.details_latitude_row);
        hideDetailsRow(d, R.id.details_longitude_row);
        hideDetailsRow(d, R.id.details_location_row);
    }
}
Example 8
Project: WordPress-Android-master  File: GeocoderUtils.java View source code
public static Address getAddressFromCoords(Context context, double latitude, double longitude) {
    Address address = null;
    List<Address> addresses = null;
    Geocoder gcd = getGeocoder(context);
    if (gcd == null) {
        return null;
    }
    try {
        addresses = gcd.getFromLocation(latitude, longitude, 1);
    } catch (IOException e) {
        AppLog.e(AppLog.T.UTILS, "Unable to parse response from server. Is Geocoder service hitting the server too frequently?", e);
    }
    // addresses may be null or empty if network isn't connected
    if (addresses != null && addresses.size() > 0) {
        address = addresses.get(0);
    }
    return address;
}
Example 9
Project: FasterGallery-master  File: MenuHelper.java View source code
private static void setLatLngDetails(final View d, Activity context, ExifInterface exif) {
    float[] latlng = new float[2];
    if (exif.getLatLong(latlng)) {
        setDetailsValue(d, String.valueOf(latlng[0]), R.id.details_latitude_value);
        setDetailsValue(d, String.valueOf(latlng[1]), R.id.details_longitude_value);
        if (latlng[0] == INVALID_LATLNG || latlng[1] == INVALID_LATLNG) {
            hideDetailsRow(d, R.id.details_latitude_row);
            hideDetailsRow(d, R.id.details_longitude_row);
            hideDetailsRow(d, R.id.details_location_row);
            return;
        }
        UpdateLocationCallback cb = new UpdateLocationCallback(new WeakReference<View>(d));
        Geocoder geocoder = new Geocoder(context);
        new ReverseGeocoderTask(geocoder, latlng, cb).execute();
    } else {
        hideDetailsRow(d, R.id.details_latitude_row);
        hideDetailsRow(d, R.id.details_longitude_row);
        hideDetailsRow(d, R.id.details_location_row);
    }
}
Example 10
Project: ARKOST-master  File: Status.java View source code
private void cekGPS(Location loc) {
    TextView tgps = (TextView) findViewById(R.id.lGps);
    TextView tlat = (TextView) findViewById(R.id.lLat);
    TextView tlon = (TextView) findViewById(R.id.lLon);
    TextView ttip = (TextView) findViewById(R.id.lTips);
    TextView tjal = (TextView) findViewById(R.id.lLoc);
    String alamat = "Alamat tidak diketahui";
    // cek posisi
    if (loc != null) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();
        tgps.setText("GPS = Aktif \n");
        tlat.setText("Latitude = " + lat + "\n");
        tlon.setText("Longitude = " + lon + "\n");
        Geocoder gc = new Geocoder(Status.this, Locale.getDefault());
        try {
            List<Address> addresses = gc.getFromLocation(lat, lon, 10);
            StringBuilder sb = new StringBuilder();
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) sb.append(address.getAddressLine(i)).append(", ");
                sb.append(address.getLocality()).append("\n");
            } else {
                sb.append("Unknown");
            }
            alamat = sb.toString();
        } catch (IOException e) {
        }
        tjal.setText("Lokasi = " + alamat);
        ttip.setText("Tips : Tekan Menu - Refresh untuk meng-update status Anda");
    } else {
        tgps.setText("GPS = Non Aktif");
        tlat.setText("Latitude = Tidak diketahui");
        tlon.setText("Longitude = Tidak diketahui");
        tjal.setText("Lokasi = Tidak diketahui");
        ttip.setText("Tips : Nyalakan GPS. Tekan Menu - setting");
    }
// end posisi
}
Example 11
Project: MyTracks-master  File: TrackNameUtils.java View source code
/**
   * Gets the reverse geo coding string for a location.
   * 
   * @param context the context
   * @param location the location
   */
private static String getReverseGeoCoding(Context context, Location location) {
    if (location == null || !ApiAdapterFactory.getApiAdapter().isGeoCoderPresent()) {
        return null;
    }
    Geocoder geocoder = new Geocoder(context);
    try {
        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            int lines = address.getMaxAddressLineIndex();
            if (lines > 0) {
                return address.getAddressLine(0);
            }
            String featureName = address.getFeatureName();
            if (featureName != null) {
                return featureName;
            }
            String thoroughfare = address.getThoroughfare();
            if (thoroughfare != null) {
                return thoroughfare;
            }
            String locality = address.getLocality();
            if (locality != null) {
                return locality;
            }
        }
    } catch (IOException e) {
    }
    return null;
}
Example 12
Project: ohmagePhone-master  File: LocTrigMapsActivity.java View source code
@Override
protected Address doInBackground(String... params) {
    //Search the address
    Geocoder geoCoder = new Geocoder(LocTrigMapsActivity.this, Locale.getDefault());
    for (int i = 0; i < GEOCODING_RETRIES; i++) {
        try {
            List<Address> addrs = geoCoder.getFromLocationName(params[0], 5);
            if (addrs.size() > 0) {
                return addrs.get(0);
            }
        } catch (Exception e) {
        }
        try {
            Thread.sleep(GEOCODING_RETRY_INTERVAL);
        } catch (InterruptedException e) {
        }
    }
    return null;
}
Example 13
Project: Locast-Android-master  File: LocationLink.java View source code
@Override
protected String doInBackground(Location... params) {
    final Location location = params[0];
    final Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
    try {
        final List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (addresses.size() > 0) {
            final Address thisLocation = addresses.get(0);
            // TODO fixme
            return thisLocation.toString();
        //return AddressUtils.addressToName(thisLocation);
        }
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 14
Project: 3380-GAS-App-master  File: StationRequest.java View source code
public static LatLng getGeoCoordsFromAddress(Context c, String address) {
    Geocoder geocoder = new Geocoder(c);
    List<Address> addresses;
    try {
        addresses = geocoder.getFromLocationName(address, 1);
        if (addresses.size() > 0) {
            double latitude = addresses.get(0).getLatitude();
            double longitude = addresses.get(0).getLongitude();
            System.out.println(latitude);
            System.out.println(longitude);
            return new LatLng(latitude, longitude);
        } else {
            return null;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 15
Project: ijoomer-adv-sdk-master  File: IjoomerMapAddress.java View source code
/**
	 * L Class method
	 */
/**
	 * This method used to getting address from lat-lng.
	 * 
	 * @param lat
	 *            represented latitude
	 * @param lng
	 *            represented longitude
	 */
private void setAddressData(double lat, double lng) {
    Geocoder geocoder;
    if (lat != 0 && lng != 0) {
        geocoder = new Geocoder(IjoomerMapAddress.this);
        try {
            List<Address> list = geocoder.getFromLocation(lat, lng, 10);
            if (list != null && list.size() > 0) {
                if (txtMapAddressHints.getVisibility() == View.GONE) {
                    pbrLstMapAddress.setVisibility(View.VISIBLE);
                }
                addressList = new ArrayList<HashMap<String, String>>();
                for (Address address : list) {
                    HashMap<String, String> data = new HashMap<String, String>();
                    if (address.getAddressLine(0).toString().trim().length() > 0) {
                        data.put("address", address.getAddressLine(0));
                        data.put("latitude", String.valueOf(address.getLatitude()));
                        data.put("longitude", String.valueOf(address.getLongitude()));
                        addressList.add(data);
                    } else if (address.getAddressLine(1).toString().trim().length() > 0) {
                        data.put("address", address.getAddressLine(1));
                        data.put("latitude", String.valueOf(address.getLatitude()));
                        data.put("longitude", String.valueOf(address.getLongitude()));
                        addressList.add(data);
                    } else if (address.getLocality().toString().trim().length() > 0) {
                        data.put("address", address.getLocality());
                        data.put("latitude", String.valueOf(address.getLatitude()));
                        data.put("longitude", String.valueOf(address.getLongitude()));
                        addressList.add(data);
                    } else if (address.getAdminArea().toString().trim().length() > 0) {
                        data.put("address", address.getAdminArea());
                        data.put("latitude", String.valueOf(address.getLatitude()));
                        data.put("longitude", String.valueOf(address.getLongitude()));
                        addressList.add(data);
                    } else if (address.getCountryName().toString().trim().length() > 0) {
                        data.put("address", address.getAdminArea());
                        data.put("latitude", String.valueOf(address.getLatitude()));
                        data.put("longitude", String.valueOf(address.getLongitude()));
                        addressList.add(data);
                    }
                }
                lstMapAddress.setAdapter(getListAdapter(prepareList(addressList)));
                if (txtMapAddressHints.getVisibility() == View.VISIBLE) {
                    lstMapAddress.setVisibility(View.VISIBLE);
                    txtMapAddressHints.setVisibility(View.GONE);
                } else {
                    pbrLstMapAddress.setVisibility(View.GONE);
                }
            } else {
                IjoomerUtilities.getCustomOkDialog(getString(R.string.address_from_map), getString(R.string.lat_long_not_found), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {

                    @Override
                    public void NeutralMethod() {
                    }
                });
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
Example 16
Project: WiFi-Automatic-master  File: Locations.java View source code
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (requestCode == REQUEST_LOCATION) {
        if (resultCode == RESULT_OK) {
            LatLng location = data.getParcelableExtra("location");
            String locationName = "UNKNOWN";
            if (Geocoder.isPresent()) {
                Geocoder gc = new Geocoder(this);
                try {
                    List<Address> result = gc.getFromLocation(location.latitude, location.longitude, 1);
                    if (result != null && !result.isEmpty()) {
                        Address address = result.get(0);
                        locationName = address.getAddressLine(0);
                        if (address.getLocality() != null) {
                            locationName += ", " + address.getLocality();
                        }
                    }
                } catch (IOException e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    e.printStackTrace();
                }
            }
            Database db = Database.getInstance(this);
            db.addLocation(locationName, location);
            db.close();
            locations.add(new Location(locationName, location));
            mAdapter.notifyDataSetChanged();
        }
    } else if (requestCode == REQUEST_BUY) {
        if (resultCode == RESULT_OK) {
            if (data.getIntExtra("RESPONSE_CODE", 0) == 0) {
                try {
                    JSONObject jo = new JSONObject(data.getStringExtra("INAPP_PURCHASE_DATA"));
                    PREMIUM_ENABLED = jo.getString("productId").equals("de.j4velin.wifiautomatic.billing.pro") && jo.getString("developerPayload").equals(getPackageName());
                    getSharedPreferences("settings", Context.MODE_PRIVATE).edit().putBoolean("pro", PREMIUM_ENABLED).commit();
                    if (PREMIUM_ENABLED) {
                        Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    Toast.makeText(this, e.getClass().getName() + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
Example 17
Project: android_packages_apps_Gallery3D-master  File: ReverseGeocoder.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Deque<MediaSet> queue = sQueue;
    mGeocoder = new Geocoder(mContext);
    queue.clear();
    try {
        for (; ; ) {
            // Wait for the next request.
            MediaSet set;
            synchronized (queue) {
                while ((set = queue.pollFirst()) == null) {
                    queue.wait();
                }
            }
            // Process the request.
            process(set);
        }
    } catch (InterruptedException e) {
    }
}
Example 18
Project: platform-packages-apps-Gallery3D-master  File: ReverseGeocoder.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Deque<MediaSet> queue = sQueue;
    mGeocoder = new Geocoder(mContext);
    queue.clear();
    try {
        for (; ; ) {
            // Wait for the next request.
            MediaSet set;
            synchronized (queue) {
                while ((set = queue.pollFirst()) == null) {
                    queue.wait();
                }
            }
            // Process the request.
            process(set);
        }
    } catch (InterruptedException e) {
    }
}
Example 19
Project: PhotoPhase-master  File: PhotoViewerActivity.java View source code
@SuppressWarnings("ConstantConditions")
private void updateDetailsInformation() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.US);
    DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
    DateFormat tf = DateFormat.getTimeInstance(DateFormat.SHORT);
    DecimalFormat nf1 = new DecimalFormat("0");
    DecimalFormat nf2 = new DecimalFormat("0.#");
    String notAvailable = getString(R.string.photoviewer_details_not_available);
    String title = mPhoto.getName();
    Date datetime = null;
    String location = null;
    String manufacturer = null;
    String model = null;
    double exposure = -1d;
    double aperture = -1d;
    String iso = null;
    int flash = -1;
    int w = -1;
    int h = -1;
    int orientation = -1;
    ExifInterface exif;
    try {
        exif = new ExifInterface(mPhoto.getAbsolutePath());
        // Title
        if (AndroidHelper.isNougatOrGreater()) {
            title = exif.getAttribute(ExifInterface.TAG_IMAGE_DESCRIPTION);
            if (TextUtils.isEmpty(title)) {
                title = exif.getAttribute(ExifInterface.TAG_USER_COMMENT);
                if (TextUtils.isEmpty(title)) {
                    title = mPhoto.getName();
                }
            }
        }
        // Date
        String date = exif.getAttribute(ExifInterface.TAG_DATETIME);
        if (date != null) {
            try {
                datetime = sdf.parse(date);
            } catch (ParseException e) {
            }
        }
        // Location
        if (exif.getLatLong(mLocation)) {
            mHasLocation = true;
            if (Geocoder.isPresent()) {
                Geocoder geocoder = new Geocoder(this, AndroidHelper.getLocale(getResources()));
                List<Address> addresses = geocoder.getFromLocation(mLocation[0], mLocation[1], 1);
                if (!addresses.isEmpty()) {
                    Address address = addresses.get(0);
                    int max = address.getMaxAddressLineIndex();
                    location = "";
                    for (int i = 0; i <= max; i++) {
                        if (i > 0) {
                            location += ", ";
                        }
                        location += address.getAddressLine(i);
                    }
                }
            }
        }
        // Camera
        manufacturer = exif.getAttribute(ExifInterface.TAG_MAKE);
        model = exif.getAttribute(ExifInterface.TAG_MODEL);
        try {
            exposure = Double.parseDouble(exif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME));
            if (exposure > 0) {
                exposure = Math.floor(1 / exposure);
            }
        } catch (NullPointerExceptionNumberFormatException |  ex) {
        }
        try {
            if (AndroidHelper.isNougatOrGreater()) {
                aperture = Double.parseDouble(exif.getAttribute(ExifInterface.TAG_F_NUMBER));
            } else {
                //noinspection deprecation
                aperture = Double.parseDouble(exif.getAttribute(ExifInterface.TAG_F_NUMBER));
            }
        } catch (NullPointerExceptionNumberFormatException |  ex) {
        }
        if (AndroidHelper.isNougatOrGreater()) {
            iso = exif.getAttribute(ExifInterface.TAG_ISO_SPEED_RATINGS);
        } else {
            //noinspection deprecation
            iso = exif.getAttribute(ExifInterface.TAG_ISO_SPEED_RATINGS);
        }
        flash = exif.getAttributeInt(ExifInterface.TAG_FLASH, -1);
        // Resolution
        w = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, -1);
        h = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, -1);
        // Orientation
        if (orientation == ExifInterface.ORIENTATION_NORMAL) {
            orientation = 0;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            orientation = 90;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            orientation = 180;
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            orientation = 270;
        }
    } catch (IOException ioEx) {
        Log.w(TAG, "Not exif information for " + mPhoto.getAbsolutePath(), ioEx);
    }
    // Ensure we can have information about the picture size
    if (w <= 0 || h <= 0) {
        Rect r = BitmapUtils.getBitmapDimensions(mPhoto);
        w = r.width();
        h = r.height();
    }
    TextView tv;
    // Date
    tv = (TextView) findViewById(R.id.details_datetime);
    tv.setText(datetime == null ? notAvailable : getString(R.string.photoviewer_details_format, df.format(datetime), tf.format(datetime)));
    // Location
    if (!mHasLocation) {
        findViewById(R.id.details_lat_lon).setVisibility(View.GONE);
        findViewById(R.id.details_map_block).setVisibility(View.GONE);
        tv = (TextView) findViewById(R.id.details_location);
        tv.setText(notAvailable);
    } else {
        tv = (TextView) findViewById(R.id.details_location);
        if (location == null) {
            tv.setVisibility(View.GONE);
        } else {
            tv.setText(location);
        }
        tv = (TextView) findViewById(R.id.details_lat_lon);
        tv.setText(getString(R.string.photoviewer_details_latitude_longitude, mLocation[0], mLocation[1]));
        // Check if map can be open in an external app
        if (hasExternalMapApp(mLocation[0], mLocation[1])) {
            View v = findViewById(R.id.details_location_block);
            v.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    openLocationInExternalApp(mLocation[0], mLocation[1]);
                }
            });
        }
    }
    // Camera
    if (manufacturer == null && model == null) {
        findViewById(R.id.details_camera).setVisibility(View.GONE);
    } else {
        tv = (TextView) findViewById(R.id.details_manufacturer);
        tv.setText(manufacturer == null ? getString(R.string.photoviewer_details_manufacturer, notAvailable) : getString(R.string.photoviewer_details_manufacturer, manufacturer));
        tv = (TextView) findViewById(R.id.details_model);
        tv.setText(model == null ? getString(R.string.photoviewer_details_model, notAvailable) : getString(R.string.photoviewer_details_model, model));
        tv = (TextView) findViewById(R.id.details_exposure);
        tv.setText(exposure == -1 ? getString(R.string.photoviewer_details_exposure, notAvailable) : getString(R.string.photoviewer_details_exposure, nf1.format(exposure)));
        tv = (TextView) findViewById(R.id.details_aperture);
        tv.setText(aperture == -1 ? getString(R.string.photoviewer_details_aperture, notAvailable) : getString(R.string.photoviewer_details_aperture, nf2.format(aperture)));
        tv = (TextView) findViewById(R.id.details_iso);
        tv.setText(iso == null ? getString(R.string.photoviewer_details_iso, notAvailable) : getString(R.string.photoviewer_details_iso, iso));
        tv = (TextView) findViewById(R.id.details_flash);
        tv.setText(flash == -1 ? getString(R.string.photoviewer_details_flash, notAvailable) : getString(R.string.photoviewer_details_flash, ((flash & 0x01) == 0x1) ? getString(R.string.photoviewer_details_flash_used) : getString(R.string.photoviewer_details_flash_not_used)));
    }
    // Info
    tv = (TextView) findViewById(R.id.details_name);
    tv.setText(getString(R.string.photoviewer_details_name, title));
    tv = (TextView) findViewById(R.id.details_size);
    tv.setText(getString(R.string.photoviewer_details_size, mPhoto.length() / 1024));
    tv = (TextView) findViewById(R.id.details_resolution);
    if (w == -1 || h == -1) {
        tv.setVisibility(View.GONE);
    } else {
        tv.setText(getString(R.string.photoviewer_details_resolution, w, h));
    }
    tv = (TextView) findViewById(R.id.details_orientation);
    if (orientation == -1) {
        tv.setVisibility(View.GONE);
    } else {
        tv.setText(getString(R.string.photoviewer_details_orientation, orientation));
    }
    tv = (TextView) findViewById(R.id.details_path);
    tv.setText(getString(R.string.photoviewer_details_path, mPhoto.getParent()));
}
Example 20
Project: BioWiki-master  File: EditPostSettingsFragment.java View source code
@Override
protected String doInBackground(Double... args) {
    // args will be the latitude, longitude to look up
    latitude = args[0];
    longitude = args[1];
    // first make sure a Geocoder service exists on this device (requires API 9)
    if (!Geocoder.isPresent())
        return null;
    Geocoder gcd;
    try {
        gcd = new Geocoder(getActivity(), Locale.getDefault());
    } catch (NullPointerException cannotIstantiateEx) {
        AppLog.e(AppLog.T.EDITOR, "Cannot Istantiate Geocoder", cannotIstantiateEx);
        return null;
    }
    List<Address> addresses;
    try {
        addresses = gcd.getFromLocation(latitude, longitude, 1);
        // addresses may be null or empty if network isn't connected
        if (addresses == null || addresses.size() == 0)
            return null;
        String locality = "", adminArea = "", country = "";
        if (addresses.get(0).getLocality() != null)
            locality = addresses.get(0).getLocality();
        if (addresses.get(0).getAdminArea() != null)
            adminArea = addresses.get(0).getAdminArea();
        if (addresses.get(0).getCountryName() != null)
            country = addresses.get(0).getCountryName();
        return ((locality.equals("")) ? locality : locality + ", ") + ((adminArea.equals("")) ? adminArea : adminArea + " ") + country;
    } catch (IOException e) {
        AppLog.e(AppLog.T.EDITOR, "Unable to parse response from server. Is Geocoder service hitting the server too frequently?", e);
        return null;
    }
}
Example 21
Project: viaja-facil-master  File: ViajaFacilActivity.java View source code
protected List<Address> doInBackground(String... s) {
    lastGeocodedAddr[fromOrTo] = s[0];
    Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
    try {
        Log.d("AddressGeoCoder", "Addr: " + s[0]);
        //List<Address> addresses = geoCoder.getFromLocationName(s[0], 5, -35.321848, -59.295959, -34.04697, -57.77298);
        List<Address> addresses = geoCoder.getFromLocationName(s[0], 5);
        return addresses;
    } catch (IOException e) {
        Log.e("ADdressToPointGeocodertask", "Geocoder failed", e);
        return null;
    }
}

Java Examples for javax.activation.DataSource

The following java examples will help you to understand the usage of javax.activation.DataSource. These source code samples are taken from different open source projects.

Example 1
Project: jentrata-msh-master  File: EbxmlMessage.java View source code
/**
     * Gets the messageFromDataSource attribute of the MessageServer class
     * 
     * @param dataSource
     *            Description of the Parameter
     * @param withAttachments
     *            Description of the Parameter
     * @return The messageFromDataSource value
     * @throws SOAPException
     *             Description of the Exception
     */
private static Object getMessageFromDataSource(DataSource dataSource, boolean withAttachments, EbxmlMessage ebxmlMessage) throws SOAPException, IOException {
    InputStream fis = null;
    PushbackInputStream fileStream = null;
    try {
        fis = dataSource.getInputStream();
        MessageSemiParsedOutput parsedOutput = parseSoapEnvelopeOnly(fis);
        fileStream = parsedOutput.getInputStream();
        byte[] soapMessageBytes = parsedOutput.getSoapMessageBytes();
        soapMessageBytes = getSoapEnvelopeBytesFromParsedOutput(parsedOutput);
        int soapMessageFileOffset = 0;
        int soapMessageLength = soapMessageBytes.length;
        int lastIndex = parsedOutput.getLastIndex();
        String boundary = parsedOutput.getBoundary();
        /*
             * final MimeHeaders headers = new MimeHeaders();
             * headers.addHeader(Constants.CONTENT_TYPE,
             * Constants.TEXT_XML_TYPE);
             */
        final MimeHeaders headers = parsedOutput.getMimeHeaders();
        /**
             * added for parsing message without payload. For such case,
             */
        if (headers.getHeader(Constants.CONTENT_TYPE) == null) {
            headers.addHeader(Constants.CONTENT_TYPE, Constants.TEXT_XML_TYPE);
        }
        final SOAPMessage soapMessage;
        soapMessage = MessageFactory.newInstance().createMessage(headers, new ByteArrayInputStream(soapMessageBytes, 0, lastIndex + 1));
        ArrayList payloads = new ArrayList();
        if (boundary != null && withAttachments) {
            byte[] line = parsedOutput.getLastLine();
            long offset = parsedOutput.getOffset();
            lastIndex = line.length - 1;
            for (; lastIndex >= 0; lastIndex--) {
                if (line[lastIndex] != 0xA && line[lastIndex] != 0xD) {
                    break;
                }
            }
            String s = new String(line, 0, lastIndex + 1);
            while (!s.endsWith(boundary + Constants.MIME_BOUNDARY_PREFIX)) {
                /*
                     * Find the empty line delimiter separating the MIME header
                     * and the attachment content
                     */
                final MimeHeaders attachmentHeaders = new MimeHeaders();
                line = readLine(fileStream);
                offset += line.length;
                while (line.length > 0 && line[0] != 0xA && line[0] != 0xD) {
                    String lineString = new String(line).trim(), name;
                    int colonIndex = lineString.indexOf(':');
                    if (colonIndex >= 0) {
                        name = lineString.substring(0, colonIndex).trim();
                        String value = lineString.substring(colonIndex + 1).trim();
                        /*
                             * final StringTokenizer t = new StringTokenizer
                             * (new String(line), "\t\n\r\f: "); if
                             * (t.hasMoreTokens()) { final String name =
                             * t.nextToken(); String value = t.nextToken();
                             */
                        if (name.equalsIgnoreCase(Constants.CONTENT_ID)) {
                            if (value.startsWith("<") && !EbxmlMessage.needPatch) {
                                value = value.substring(1);
                                if (value.endsWith(">")) {
                                    value = value.substring(0, value.length() - 1);
                                }
                            }
                        }
                        attachmentHeaders.addHeader(name, value);
                    }
                    line = readLine(fileStream);
                    offset += line.length;
                }
                if (line.length == 0) {
                    throw new SOAPException("missing empty line delimiter of MIME header");
                }
                long length = 0;
                byte[] previousLine = null;
                line = readLine(fileStream);
                s = new String(line);
                while (line.length > 0 && !(s.startsWith(Constants.MIME_BOUNDARY_PREFIX + boundary))) {
                    length += line.length;
                    previousLine = line;
                    line = readLine(fileStream);
                    s = new String(line);
                }
                if (line.length == 0) {
                    throw new SOAPException("missing ending MIME boundary");
                }
                lastIndex = previousLine.length - 1;
                for (; lastIndex >= 0; lastIndex--) {
                    if (previousLine[lastIndex] != 0xA && previousLine[lastIndex] != 0xD) {
                        break;
                    }
                }
                String[] ahs = attachmentHeaders.getHeader(Constants.CONTENT_TYPE);
                String contentType = null;
                if (ahs == null || ahs.length == 0) {
                    throw new SOAPException("missing " + Constants.CONTENT_TYPE + " attachment");
                } else if (ahs.length == 1) {
                    contentType = ahs[0];
                } else {
                    throw new SOAPException("more than one " + Constants.CONTENT_TYPE + " in attachment");
                }
                ahs = attachmentHeaders.getHeader(Constants.CONTENT_TRANSFER_ENCODING);
                String encoding = null;
                if (ahs != null) {
                    if (ahs.length == 1) {
                        encoding = ahs[0];
                    } else if (ahs.length > 1) {
                        throw new SOAPException("more than one " + Constants.CONTENT_TRANSFER_ENCODING + " in attachment");
                    }
                }
                final AttachmentDataSource ads = new AttachmentDataSource(dataSource, offset, length - (previousLine.length - 1 - lastIndex), contentType, encoding, false);
                final DataHandler dh = new DataHandler(ads);
                String contentId = null;
                ahs = attachmentHeaders.getHeader(Constants.CONTENT_ID);
                if (ahs != null) {
                    contentId = ahs[0];
                }
                PayloadContainer attachment = new PayloadContainer(dh, contentId, null);
                for (Iterator i = attachmentHeaders.getAllHeaders(); i.hasNext(); ) {
                    final MimeHeader header = (MimeHeader) i.next();
                    final String name = header.getName();
                    if (!name.equals(Constants.CONTENT_TYPE) && !name.equals(Constants.CONTENT_ID)) {
                        attachment.setMimeHeader(name, header.getValue());
                    }
                }
                payloads.add(attachment);
                // add the attachment to soap message                    
                AttachmentPart attachmentPart = soapMessage.createAttachmentPart();
                attachmentPart.setContentId(needPatch ? " <" + contentId + ">" : contentId);
                attachmentPart.setDataHandler(dh);
                soapMessage.addAttachmentPart(attachmentPart);
                offset += (length + line.length);
                lastIndex = line.length - 1;
                for (; lastIndex >= 0; lastIndex--) {
                    if (line[lastIndex] != 0xA && line[lastIndex] != 0xD) {
                        break;
                    }
                }
                s = new String(line, 0, lastIndex + 1);
            }
        }
        if (withAttachments) {
            EbxmlMessage message;
            if (ebxmlMessage == null) {
                message = new EbxmlMessage(soapMessage);
            } else {
                ebxmlMessage.init(soapMessage);
                message = ebxmlMessage;
            }
            message.setPayloadContainers(payloads);
            message.setSoapEnvelopeBytes(soapMessageBytes);
            return message;
        }
        return soapMessage;
    } catch (IOException e) {
        throw new SOAPException(e.toString());
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                throw new SOAPException(e.toString());
            }
        }
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
                throw new SOAPException(e.toString());
            }
        }
    }
}
Example 2
Project: openjdk-master  File: MimeUtility.java View source code
/**
     * Get the content-transfer-encoding that should be applied
     * to the input stream of this datasource, to make it mailsafe. <p>
     *
     * The algorithm used here is: <br>
     * <ul>
     * <li>
     * If the primary type of this datasource is "text" and if all
     * the bytes in its input stream are US-ASCII, then the encoding
     * is "7bit". If more than half of the bytes are non-US-ASCII, then
     * the encoding is "base64". If less than half of the bytes are
     * non-US-ASCII, then the encoding is "quoted-printable".
     * <li>
     * If the primary type of this datasource is not "text", then if
     * all the bytes of its input stream are US-ASCII, the encoding
     * is "7bit". If there is even one non-US-ASCII character, the
     * encoding is "base64".
     * </ul>
     *
     * @param   ds      DataSource
     * @return          the encoding. This is either "7bit",
     *                  "quoted-printable" or "base64"
     */
public static String getEncoding(DataSource ds) {
    ContentType cType = null;
    InputStream is = null;
    String encoding = null;
    try {
        cType = new ContentType(ds.getContentType());
        is = ds.getInputStream();
    } catch (Exception ex) {
        return "base64";
    }
    boolean isText = cType.match("text/*");
    // if not text, stop processing when we see non-ASCII
    int i = checkAscii(is, ALL, !isText);
    switch(i) {
        case ALL_ASCII:
            // all ascii
            encoding = "7bit";
            break;
        case MOSTLY_ASCII:
            // mostly ascii
            encoding = "quoted-printable";
            break;
        default:
            // mostly binary
            encoding = "base64";
            break;
    }
    // Close the input stream
    try {
        is.close();
    } catch (IOException ioex) {
    }
    return encoding;
}
Example 3
Project: jaxws-master  File: XMLMessage.java View source code
public static Message create(DataSource ds, WSFeatureList f) {
    try {
        return (ds == null) ? Messages.createEmpty(SOAPVersion.SOAP_11) : create(ds.getContentType(), ds.getInputStream(), f);
    } catch (IOException ioe) {
        throw new WebServiceException(ioe);
    }
}
Example 4
Project: classlib6-master  File: MimeUtility.java View source code
/**
     * Get the content-transfer-encoding that should be applied
     * to the input stream of this datasource, to make it mailsafe. <p>
     *
     * The algorithm used here is: <br>
     * <ul>
     * <li>
     * If the primary type of this datasource is "text" and if all
     * the bytes in its input stream are US-ASCII, then the encoding
     * is "7bit". If more than half of the bytes are non-US-ASCII, then
     * the encoding is "base64". If less than half of the bytes are
     * non-US-ASCII, then the encoding is "quoted-printable".
     * <li>
     * If the primary type of this datasource is not "text", then if
     * all the bytes of its input stream are US-ASCII, the encoding
     * is "7bit". If there is even one non-US-ASCII character, the
     * encoding is "base64".
     * </ul>
     *
     * @param	ds	DataSource
     * @return		the encoding. This is either "7bit",
     *			"quoted-printable" or "base64"
     */
public static String getEncoding(DataSource ds) {
    ContentType cType = null;
    InputStream is = null;
    String encoding = null;
    try {
        cType = new ContentType(ds.getContentType());
        is = ds.getInputStream();
    } catch (Exception ex) {
        return "base64";
    }
    boolean isText = cType.match("text/*");
    // if not text, stop processing when we see non-ASCII
    int i = checkAscii(is, ALL, !isText);
    switch(i) {
        case ALL_ASCII:
            // all ascii
            encoding = "7bit";
            break;
        case MOSTLY_ASCII:
            // mostly ascii
            encoding = "quoted-printable";
            break;
        default:
            // mostly binary
            encoding = "base64";
            break;
    }
    // Close the input stream
    try {
        is.close();
    } catch (IOException ioex) {
    }
    return encoding;
}
Example 5
Project: VaadinUtils-master  File: JasperManager.java View source code
@Override
public void run() {
    JRSwapFileVirtualizer fileVirtualizer = null;
    CleanupCallback cleanupCallback = null;
    boolean initialized = false;
    try {
        logger.warn("{} permits are available", concurrentLimit.availablePermits());
        concurrentLimit.acquire();
        initialized = true;
        inQueue = false;
        queueEntry.setStatus("Gathering report data phase 1");
        reportProperties.initDBConnection();
        cleanupCallback = reportProperties.getCleanupCallback();
        List<ReportParameter<?>> extraParams = reportProperties.prepareData(params, reportProperties.getReportFileName(), cleanupCallback);
        compileReport();
        if (reportProperties.getCustomReportParameterMap() != null) {
            boundParams.putAll(reportProperties.getCustomReportParameterMap());
        }
        if (extraParams != null) {
            params.removeAll(extraParams);
            params.addAll(extraParams);
        }
        logger.info("Running report " + reportProperties.getReportFileName());
        for (ReportParameter<?> param : params) {
            for (String parameterName : param.getParameterNames()) {
                bindParameter(param, parameterName);
                if (param.displayInreport()) {
                    // populate dynamically added parameters to display user
                    // friendly parameters on the report
                    boundParams.put("ParamDisplay-" + parameterName, param.getDisplayValue(parameterName));
                }
                logger.info(parameterName + " " + param.getValue(parameterName));
            }
        }
        reportProperties.prepareForOutputFormat(exportMethod);
        CustomJRHyperlinkProducerFactory.setUseCustomHyperLinks(true);
        @SuppressWarnings("rawtypes") JRAbstractExporter exporter = null;
        queueEntry.setStatus("Gathering report data phase 2");
        // use file virtualizer to prevent out of heap
        String fileName = "/tmp";
        JRSwapFile file = new JRSwapFile(fileName, 100, 10);
        fileVirtualizer = new JRSwapFileVirtualizer(500, file);
        boundParams.put(JRParameter.REPORT_VIRTUALIZER, fileVirtualizer);
        if (stop) {
            return;
        }
        if (exportMethod == OutputFormat.CSV) {
            boundParams.put(JRParameter.IS_IGNORE_PAGINATION, true);
        }
        JasperPrint jasper_print = fillReport(exportMethod);
        switch(exportMethod) {
            case HTML:
                {
                    exporter = new JRHtmlExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, images);
                    if (VaadinServlet.getCurrent() != null) {
                        String context = VaadinServlet.getCurrent().getServletContext().getContextPath();
                        int contextIndex = Page.getCurrent().getLocation().toString().lastIndexOf(context);
                        String baseurl = Page.getCurrent().getLocation().toString().substring(0, contextIndex + context.length() + 1);
                        String imageUrl = baseurl + "VaadinJasperPrintServlet?image=";
                        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl);
                    } else {
                        logger.warn("Vaadin Servlet doens't have a current context");
                    }
                    break;
                }
            case PDF:
                {
                    exporter = new JRPdfExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    break;
                }
            case CSV:
                {
                    exporter = new JRCsvExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    break;
                }
            default:
                {
                    throw new RuntimeException("Unsupported export option " + exportMethod);
                }
        }
        imagesrcs = (images.size() <= 0) ? null : new DataSource[images.size()];
        if (imagesrcs != null) {
            int xi = 0;
            for (Map.Entry<String, byte[]> entry : images.entrySet()) {
                ByteArrayDataSource image = new ByteArrayDataSource(entry.getValue(), "image/gif");
                image.setName(entry.getKey());
                imagesrcs[xi++] = image;
            }
        }
        if (stop) {
            return;
        }
        createPageProgressMonitor(exporter);
        queueEntry.setStatus("Waiting for browser to start streaming");
        progressListener.outputStreamReady();
        if (readerReady.await(10, TimeUnit.SECONDS)) {
            outputStream = new PipedOutputStream(inputStream);
            writerReady.countDown();
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
            exporter.exportReport();
        } else {
            logger.error("Couldn't attach to reader stream");
        }
        Thread.sleep(750);
        queueEntry.setStatus("Cleaning up");
    } catch (Exception e) {
        logger.error(e, e);
    } finally {
        if (queueEntry != null) {
            jobQueue.remove(queueEntry);
            queueEntry = null;
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            logger.error(e, e);
        }
        if (cleanupCallback != null) {
            try {
                cleanupCallback.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        if (fileVirtualizer != null) {
            try {
                fileVirtualizer.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        CustomJRHyperlinkProducerFactory.setUseCustomHyperLinks(false);
        if (initialized) {
            concurrentLimit.release();
            try {
                reportProperties.closeDBConnection();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        completeBarrier.countDown();
        if (progressListener != null) {
            progressListener.completed();
        }
    }
}
Example 6
Project: ikvm-openjdk-master  File: MimeUtility.java View source code
/**
     * Get the content-transfer-encoding that should be applied
     * to the input stream of this datasource, to make it mailsafe. <p>
     *
     * The algorithm used here is: <br>
     * <ul>
     * <li>
     * If the primary type of this datasource is "text" and if all
     * the bytes in its input stream are US-ASCII, then the encoding
     * is "7bit". If more than half of the bytes are non-US-ASCII, then
     * the encoding is "base64". If less than half of the bytes are
     * non-US-ASCII, then the encoding is "quoted-printable".
     * <li>
     * If the primary type of this datasource is not "text", then if
     * all the bytes of its input stream are US-ASCII, the encoding
     * is "7bit". If there is even one non-US-ASCII character, the
     * encoding is "base64".
     * </ul>
     *
     * @param   ds      DataSource
     * @return          the encoding. This is either "7bit",
     *                  "quoted-printable" or "base64"
     */
public static String getEncoding(DataSource ds) {
    ContentType cType = null;
    InputStream is = null;
    String encoding = null;
    try {
        cType = new ContentType(ds.getContentType());
        is = ds.getInputStream();
    } catch (Exception ex) {
        return "base64";
    }
    boolean isText = cType.match("text/*");
    // if not text, stop processing when we see non-ASCII
    int i = checkAscii(is, ALL, !isText);
    switch(i) {
        case ALL_ASCII:
            // all ascii
            encoding = "7bit";
            break;
        case MOSTLY_ASCII:
            // mostly ascii
            encoding = "quoted-printable";
            break;
        default:
            // mostly binary
            encoding = "base64";
            break;
    }
    // Close the input stream
    try {
        is.close();
    } catch (IOException ioex) {
    }
    return encoding;
}
Example 7
Project: ManagedRuntimeInitiative-master  File: MimeUtility.java View source code
/**
     * Get the content-transfer-encoding that should be applied
     * to the input stream of this datasource, to make it mailsafe. <p>
     *
     * The algorithm used here is: <br>
     * <ul>
     * <li>
     * If the primary type of this datasource is "text" and if all
     * the bytes in its input stream are US-ASCII, then the encoding
     * is "7bit". If more than half of the bytes are non-US-ASCII, then
     * the encoding is "base64". If less than half of the bytes are
     * non-US-ASCII, then the encoding is "quoted-printable".
     * <li>
     * If the primary type of this datasource is not "text", then if
     * all the bytes of its input stream are US-ASCII, the encoding
     * is "7bit". If there is even one non-US-ASCII character, the
     * encoding is "base64".
     * </ul>
     *
     * @param	ds	DataSource
     * @return		the encoding. This is either "7bit",
     *			"quoted-printable" or "base64"
     */
public static String getEncoding(DataSource ds) {
    ContentType cType = null;
    InputStream is = null;
    String encoding = null;
    try {
        cType = new ContentType(ds.getContentType());
        is = ds.getInputStream();
    } catch (Exception ex) {
        return "base64";
    }
    boolean isText = cType.match("text/*");
    // if not text, stop processing when we see non-ASCII
    int i = checkAscii(is, ALL, !isText);
    switch(i) {
        case ALL_ASCII:
            // all ascii
            encoding = "7bit";
            break;
        case MOSTLY_ASCII:
            // mostly ascii
            encoding = "quoted-printable";
            break;
        default:
            // mostly binary
            encoding = "base64";
            break;
    }
    // Close the input stream
    try {
        is.close();
    } catch (IOException ioex) {
    }
    return encoding;
}
Example 8
Project: milton2-master  File: StandardMessageFactoryImpl.java View source code
private void addHtmlToMime(Part part, StandardMessage sm) throws MessagingException {
    // need to use a javax.activation.DataSource (!) to set a text
    // with content type "text/html"
    //			part.setDataHandler(new DataHandler(
    //			    new DataSource() {
    //						public InputStream getInputStream() throws IOException {
    //							return new ByteArrayInputStream(encoding != null ? text.getBytes(encoding) : text.getBytes());
    //						}
    //						public OutputStream getOutputStream() throws IOException {
    //							throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
    //						}
    //						public String getContentType() {
    //							return "text/html";
    //						}
    //						public String getName() {
    //							return "text";
    //						}
    //			    }
    //			));
    List<Attachment> htmlInline = findInlineAttachments(sm);
    if (htmlInline == null || htmlInline.isEmpty()) {
        part.setContent(sm.getHtml(), "text/html; charset=\"utf-8\"");
    } else {
        MimeMultipart related = new MimeMultipart("related");
        part.setContent(related);
        BodyPart bpHtml = new MimeBodyPart();
        bpHtml.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        bpHtml.setContent(sm.getHtml(), "text/plain; charset=\"utf-8\"");
        related.addBodyPart(bpHtml);
        for (Attachment att : htmlInline) {
            addAttachmentToMime(related, att);
        }
    }
}
Example 9
Project: spring-framework-2.5.x-master  File: MimeMessageHelper.java View source code
/**
	 * Add an inline element to the MimeMessage, taking the content from a
	 * <code>javax.activation.DataSource</code>.
	 * <p>Note that the InputStream returned by the DataSource implementation
	 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
	 * <code>getInputStream()</code> multiple times.
	 * <p><b>NOTE:</b> Invoke <code>addInline</code> <i>after</i> [email protected] #setText};
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param contentId the content ID to use. Will end up as "Content-ID" header
	 * in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
	 * Can be referenced in HTML source via src="cid:myId" expressions.
	 * @param dataSource the <code>javax.activation.DataSource</code> to take
	 * the content from, determining the InputStream and the content type
	 * @throws MessagingException in case of errors
	 * @see #addInline(String, java.io.File)
	 * @see #addInline(String, org.springframework.core.io.Resource)
	 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
    Assert.notNull(contentId, "Content ID must not be null");
    Assert.notNull(dataSource, "DataSource must not be null");
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
    // We're using setHeader here to remain compatible with JavaMail 1.2,
    // rather than JavaMail 1.3's setContentID.
    mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
    mimeBodyPart.setDataHandler(new DataHandler(dataSource));
    getMimeMultipart().addBodyPart(mimeBodyPart);
}
Example 10
Project: wso2-synapse-master  File: FIXUtils.java View source code
/**
     * FIX messages are non-XML. So convert them into XML using the AXIOM API.
     * Put the FIX message into an Axis2 MessageContext.The basic format of the
     * generated SOAP envelope;
     * <p/>
     * <soapEnvelope>
     * <soapBody>
     * <message>
     * <header> ....</header>
     * <body> .... </body>
     * <trailer> .... </trailer>
     * </message>
     * </soapBody>
     * </soapEnvelope>
     *
     * @param message   the FIX message
     * @param counter   application level sequence number of the message
     * @param sessionID the incoming session
     * @param msgCtx    the Axis2 MessageContext to hold the FIX message
     * @throws AxisFault the exception thrown when invalid soap envelopes are set to the msgCtx
     */
public void setSOAPEnvelope(Message message, int counter, String sessionID, MessageContext msgCtx) throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Creating SOAP envelope for FIX message...");
    }
    SOAPFactory soapFactory = new SOAP11Factory();
    OMElement msg = soapFactory.createOMElement(FIXConstants.FIX_MESSAGE, null);
    msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_INCOMING_SESSION, null, sessionID));
    msg.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_MESSAGE_COUNTER, null, String.valueOf(counter)));
    OMElement header = soapFactory.createOMElement(FIXConstants.FIX_HEADER, null);
    OMElement body = soapFactory.createOMElement(FIXConstants.FIX_BODY, null);
    OMElement trailer = soapFactory.createOMElement(FIXConstants.FIX_TRAILER, null);
    //process FIX header
    Iterator<Field<?>> iter = message.getHeader().iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag())));
            Object value = field.getObject();
            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = msgCtx.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                createOMText(soapFactory, msgField, value.toString());
            }
            header.addChild(msgField);
        }
    }
    //process FIX body
    convertFIXBodyToXML(message, body, soapFactory, msgCtx);
    //process FIX trailer
    iter = message.getTrailer().iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            Field<?> field = iter.next();
            OMElement msgField = soapFactory.createOMElement(FIXConstants.FIX_FIELD, null);
            msgField.addAttribute(soapFactory.createOMAttribute(FIXConstants.FIX_FIELD_ID, null, String.valueOf(field.getTag())));
            Object value = field.getObject();
            if (value instanceof byte[]) {
                DataSource dataSource = new ByteArrayDataSource((byte[]) value);
                DataHandler dataHandler = new DataHandler(dataSource);
                String contentID = msgCtx.addAttachment(dataHandler);
                OMElement binaryData = soapFactory.createOMElement(FIXConstants.FIX_BINARY_FIELD, null);
                String binaryCID = "cid:" + contentID;
                binaryData.addAttribute(FIXConstants.FIX_MESSAGE_REFERENCE, binaryCID, null);
                msgField.addChild(binaryData);
            } else {
                createOMText(soapFactory, msgField, value.toString());
            }
            trailer.addChild(msgField);
        }
    }
    msg.addChild(header);
    msg.addChild(body);
    msg.addChild(trailer);
    SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
    envelope.getBody().addChild(msg);
    msgCtx.setEnvelope(envelope);
}
Example 11
Project: HR-WebServices-Examples-Java-master  File: SWAClient.java View source code
public static void transferFile(File file, String destinationFile) throws Exception {
    Options options = new Options();
    options.setTo(targetEPR);
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // Increase the time out when sending large attachments
    options.setTimeOutInMilliSeconds(10000);
    options.setTo(targetEPR);
    options.setAction("urn:uploadFile");
    // assume the use runs this sample at
    // <axis2home>/samples/soapwithattachments/ dir
    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("../../repository", null);
    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
    MessageContext mc = new MessageContext();
    FileDataSource fileDataSource = new FileDataSource(file);
    // Create a dataHandler using the fileDataSource. Any implementation of
    // javax.activation.DataSource interface can fit here.
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);
    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element = body.getFirstElement().getFirstChildWithName(new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
}
Example 12
Project: dk-master  File: MailNotifyServiceImpl.java View source code
protected void sendContext(MimeMessage msg, NotifyDo message) throws MessagingException {
    // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
    Multipart multipart = new MimeMultipart();
    // 设置邮件的文本内容
    BodyPart contentPart = new MimeBodyPart();
    contentPart.setText(message.MESSAGE_CONTEXT);
    multipart.addBodyPart(contentPart);
    // 添加附件
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(message.getFilePath());
    // 添加附件的内容
    messageBodyPart.setDataHandler(new DataHandler(source));
    // 添加附件的标题
    // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    messageBodyPart.setFileName("=?UTF-8?B?" + enc.encode((message.getFileName() + ".xls").getBytes()) + "?=");
    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);
    msg.saveChanges();
}
Example 13
Project: gcontact-excel-sync-master  File: GDataContentHandler.java View source code
@SuppressWarnings("unchecked")
public Object getContent(DataSource ds) throws IOException {
    // Get the input properties to use when parsing content
    InputProperties inputProperties = getThreadInputProperties();
    // Find the parser to handle the input content type
    ContentType contentType = new ContentType(ds.getContentType());
    AltRegistry altRegistry = inputProperties.getAltRegistry();
    AltFormat altFormat = altRegistry.lookupType(contentType);
    InputParser<?> parser = altRegistry.getParser(altFormat);
    if (parser == null) {
        throw new IOException("Invalid multipart content: " + contentType);
    }
    try {
        return parseAtom(parser, ds.getInputStream(), contentType, inputProperties, inputProperties.getRootType());
    } catch (ServiceException se) {
        IOException ioe = new IOException("Error parsing content");
        ioe.initCause(se);
        throw ioe;
    }
}
Example 14
Project: resin-master  File: ServiceDelegateImpl.java View source code
public <T> Dispatch<T> createDispatch(QName portName, Class<T> type, Service.Mode mode) throws WebServiceException {
    PortInfoImpl port = _portMap.get(portName);
    String bindingId = SOAPBinding.SOAP11HTTP_BINDING;
    String endpointAddress = null;
    if (port != null) {
        bindingId = port.getBindingID();
        endpointAddress = port.getEndpointAddress();
    }
    if (endpointAddress == null)
        endpointAddress = findEndpointAddress();
    Dispatch<T> dispatch = null;
    Binding binding = getBinding(bindingId);
    if (_handlerResolver != null)
        binding.setHandlerChain(_handlerResolver.getHandlerChain(port));
    if (Source.class.equals(type)) {
        dispatch = (Dispatch<T>) new SourceDispatch(bindingId, binding, mode, _executor);
    } else if (SOAPMessage.class.equals(type)) {
        dispatch = (Dispatch<T>) new SOAPMessageDispatch(bindingId, binding, mode, _executor);
    } else if (DataSource.class.equals(type)) {
        dispatch = (Dispatch<T>) new DataSourceDispatch(bindingId, binding, mode, _executor);
    }
    if (dispatch == null) {
        throw new WebServiceException(L.l("{0} is an unsupported Dispatch type", type));
    }
    if (endpointAddress != null) {
        Map<String, Object> requestContext = dispatch.getRequestContext();
        requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
    }
    return dispatch;
}
Example 15
Project: gdata-java-client-master  File: GDataContentHandler.java View source code
@SuppressWarnings("unchecked")
public Object getContent(DataSource ds) throws IOException {
    // Get the input properties to use when parsing content
    InputProperties inputProperties = getThreadInputProperties();
    // Find the parser to handle the input content type
    ContentType contentType = new ContentType(ds.getContentType());
    AltRegistry altRegistry = inputProperties.getAltRegistry();
    AltFormat altFormat = altRegistry.lookupType(contentType);
    InputParser<?> parser = altRegistry.getParser(altFormat);
    if (parser == null) {
        throw new IOException("Invalid multipart content: " + contentType);
    }
    try {
        return parseAtom(parser, ds.getInputStream(), contentType, inputProperties, inputProperties.getRootType());
    } catch (ServiceException se) {
        IOException ioe = new IOException("Error parsing content");
        ioe.initCause(se);
        throw ioe;
    }
}
Example 16
Project: aipo-master  File: ALSmtpMailSender.java View source code
/**
   * 新規作成のメールを取得します。
   * 
   * @param mcontext
   * @return
   */
private ALLocalMailMessage createMessage(ALSmtpMailContext mcontext) {
    System.setProperty("mail.mime.charset", "ISO-2022-JP");
    System.setProperty("mail.mime.decodetext.strict", "false");
    ALLocalMailMessage msg = null;
    smtpServerProp = new Properties();
    smtpServerProp.setProperty(MAIL_SMTP_HOST, scontext.getSmtpHost());
    smtpServerProp.setProperty(MAIL_SMTP_PORT, scontext.getSmtpPort());
    smtpServerProp.put(MAIL_SMTP_CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    smtpServerProp.put(MAIL_SMTP_TIMEOUT, TIMEOUT);
    smtpServerProp.setProperty("mail.mime.address.strict", "false");
    smtpServerProp.put("mail.smtp.localhost", "localhost");
    if (scontext.getEncryptionFlag() == ENCRYPTION_SEND_SSL) {
        /** SSL 暗号化 */
        smtpServerProp.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        smtpServerProp.setProperty("mail.smtp.socketFactory.fallback", "false");
        smtpServerProp.setProperty("mail.smtp.socketFactory.port", scontext.getSmtpPort());
    }
    // SMTP サーバのアドレスをセット
    if (scontext.getAuthSendFlag() == AUTH_SEND_SMTP_AUTH && scontext.getAuthSendUserId() != null && !"".equals(scontext.getAuthSendUserId()) && scontext.getAuthSendUserPassword() != null && !"".equals(scontext.getAuthSendUserPassword())) {
        /** SMTP AUTH */
        smtpServerProp.put("mail.smtp.auth", "true");
        session = Session.getInstance(smtpServerProp, new ALSmtpAuth(scontext.getAuthSendUserId(), scontext.getAuthSendUserPassword()));
    } else {
        session = Session.getInstance(smtpServerProp, null);
    }
    try {
        // メッセージを生成
        msg = new ALLocalMailMessage(session);
        // 送信元メールアドレスと送信者名をセット
        msg.setFrom(new InternetAddress(mcontext.getFrom(), ALMailUtils.encodeWordJIS(mcontext.getName())));
        // メールのあて先(to)をセット
        if (mcontext.getTo() == null) {
            throw new MessagingException();
        }
        setRecipient(msg, Message.RecipientType.TO, mcontext.getTo());
        // メールのあて先(cc)をセット
        if (mcontext.getCc() != null) {
            setRecipient(msg, Message.RecipientType.CC, mcontext.getCc());
        }
        // メールのあて先(bcc)をセット
        if (mcontext.getBcc() != null) {
            setRecipient(msg, Message.RecipientType.BCC, mcontext.getBcc());
        }
        // メールの件名をセット
        msg.setSubject(ALMailUtils.encodeWordJIS(mcontext.getSubject()));
        // メールの送信日時をセット
        msg.setSentDate(new Date());
        if (mcontext.getFilePaths() == null) {
            // メールの本文をセット
            msg.setText(mcontext.getMsgText() + "\r\n", CHARSET_ISO2022JP);
            setHeader(msg, mcontext);
        } else {
            String[] checkedFilePaths = mcontext.getFilePaths();
            int checkedFilePathsLength = checkedFilePaths.length;
            if (checkedFilePathsLength <= 0) {
                // MultiPart にせず,メールの本文をセット
                msg.setText(mcontext.getMsgText() + "\r\n", CHARSET_ISO2022JP);
                setHeader(msg, mcontext);
            } else {
                setHeader(msg, mcontext);
                // 複数のボディを格納するマルチパートオブジェクトを生成
                Multipart multiPart = new MimeMultipart();
                // テキストのボディパートを作成
                MimeBodyPart mimeText = new MimeBodyPart();
                // メールの内容を指定
                mimeText.setText(mcontext.getMsgText(), CHARSET_ISO2022JP);
                // 1つ目のボディパートを追加
                multiPart.addBodyPart(mimeText);
                // 添付ファイルのボディパートを作成
                MimeBodyPart mimeFile = null;
                for (int i = 0; i < checkedFilePathsLength; i++) {
                    final String filePath = checkedFilePaths[i];
                    final String fileName = ALMailUtils.getFileNameFromText(checkedFilePaths[i]);
                    mimeFile = new MimeBodyPart();
                    mimeFile.setDataHandler(new DataHandler(new DataSource() {

                        @Override
                        public String getContentType() {
                            return FileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return ALStorageService.getFile(filePath);
                        }

                        @Override
                        public String getName() {
                            return fileName;
                        }

                        @Override
                        public OutputStream getOutputStream() throws IOException {
                            throw new UnsupportedOperationException("getOutputStream");
                        }
                    }));
                    MailUtility.setFileName(mimeFile, ALMailUtils.getFileNameFromText(checkedFilePaths[i]), "ISO-2022-JP", null);
                    // 添付ファイルをボディパートに追加
                    multiPart.addBodyPart(mimeFile);
                }
                // マルチパートオブジェクトをメッセージに設定
                msg.setContent(multiPart);
            }
        }
    } catch (Exception e) {
        logger.error("ALSmtpMailSender.createMessage", e);
        return null;
    }
    return msg;
}
Example 17
Project: eclipselink.runtime-master  File: MOXyJsonProvider.java View source code
/**
     * @return true indicating that <i>MOXyJsonProvider</i> will
     * be used for the JSON binding if the media type is of the following
     * patterns */json or */*+json, and the type is not assignable from
     * any of (or a Collection or JAXBElement of) the following:
     * <ul>
     * <li>byte[]</li>
     * <li>java.io.File</li>
     * <li>java.io.InputStream</li>
     * <li>java.io.Reader</li>
     * <li>java.lang.Object</li>
     * <li>java.lang.String</li>
     * <li>javax.activation.DataSource</li>
     * </ul>
     */
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    if (!supportsMediaType(mediaType)) {
        return false;
    } else if (CoreClassConstants.APBYTE == type || CoreClassConstants.STRING == type) {
        return false;
    } else if (Map.class.isAssignableFrom(type)) {
        return false;
    } else if (File.class.isAssignableFrom(type)) {
        return false;
    } else if (DataSource.class.isAssignableFrom(type)) {
        return false;
    } else if (InputStream.class.isAssignableFrom(type)) {
        return false;
    } else if (Reader.class.isAssignableFrom(type)) {
        return false;
    } else if (Object.class == type) {
        return false;
    } else if (type.isPrimitive()) {
        return false;
    } else if (type.isArray() && (type.getComponentType().isArray() || type.getComponentType().isPrimitive() || type.getComponentType().getPackage().getName().startsWith("java."))) {
        return false;
    } else if (JAXBElement.class.isAssignableFrom(type)) {
        Set<Class<?>> domainClasses = getDomainClasses(genericType);
        for (Class<?> domainClass : domainClasses) {
            if (isReadable(domainClass, null, annotations, mediaType) || String.class == domainClass) {
                return true;
            }
        }
        return false;
    } else if (Collection.class.isAssignableFrom(type)) {
        Set<Class<?>> domainClasses = getDomainClasses(genericType);
        for (Class<?> domainClass : domainClasses) {
            if (isReadable(domainClass, null, annotations, mediaType) || String.class == domainClass) {
                return true;
            }
        }
        return false;
    } else {
        return null != getJAXBContext(type, genericType, annotations, mediaType);
    }
}
Example 18
Project: iaf-master  File: MailSender.java View source code
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection recipients, Collection attachments) throws SenderException {
    StringBuffer sb = new StringBuffer();
    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]");
    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }
    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }
    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }
        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }
        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }
        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");
        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);
            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url [" + attachmentUrl + "]contents [" + attachmentText + "]");
                messageBodyPart = new MimeBodyPart();
                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }
                messageBodyPart.setFileName(attachmentName);
                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }
                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }
        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

Java Examples for javax.xml.transform.dom.DOMResult

The following java examples will help you to understand the usage of javax.xml.transform.dom.DOMResult. These source code samples are taken from different open source projects.

Example 1
Project: metafacture-core-master  File: DomLoader.java View source code
public static Document parse(String schemaFile, InputSource input) {
    final Document document = createEmptyDocument();
    final XMLReader pipeline = createXmlFilterPipeline(schemaFile, document);
    process(new SAXSource(pipeline, input), new DOMResult(document));
    // Xerces does not use the XSD schema for deciding whether
    // whitespace is ignorable (it requires a DTD for this).
    // Since we do not use a DTD we have to use a different
    // method to remove ignorable whitespace.
    //
    // Note that this method does not only remove ignorable
    // whitespace but all text nodes containing only whitespace.
    removeEmptyTextNodes(document);
    return document;
}
Example 2
Project: JDK-master  File: DOMResultBuilder.java View source code
/*
     * DOMDocumentHandler methods
     */
public void setDOMResult(DOMResult result) {
    fCurrentNode = null;
    fFragmentRoot = null;
    fIgnoreChars = false;
    fTargetChildren.clear();
    if (result != null) {
        fTarget = result.getNode();
        fNextSibling = result.getNextSibling();
        fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument();
        fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null;
        fStorePSVI = (fDocument instanceof PSVIDocumentImpl);
        return;
    }
    fTarget = null;
    fNextSibling = null;
    fDocument = null;
    fDocumentImpl = null;
    fStorePSVI = false;
}
Example 3
Project: classlib6-master  File: DOMResultBuilder.java View source code
/*
     * DOMDocumentHandler methods
     */
public void setDOMResult(DOMResult result) {
    fCurrentNode = null;
    fFragmentRoot = null;
    fIgnoreChars = false;
    fTargetChildren.clear();
    if (result != null) {
        fTarget = result.getNode();
        fNextSibling = result.getNextSibling();
        fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument();
        fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null;
        fStorePSVI = (fDocument instanceof PSVIDocumentImpl);
        return;
    }
    fTarget = null;
    fNextSibling = null;
    fDocument = null;
    fDocumentImpl = null;
    fStorePSVI = false;
}
Example 4
Project: ikvm-openjdk-master  File: DOMResultBuilder.java View source code
/*
     * DOMDocumentHandler methods
     */
public void setDOMResult(DOMResult result) {
    fCurrentNode = null;
    fFragmentRoot = null;
    fIgnoreChars = false;
    fTargetChildren.clear();
    if (result != null) {
        fTarget = result.getNode();
        fNextSibling = result.getNextSibling();
        fDocument = (fTarget.getNodeType() == Node.DOCUMENT_NODE) ? (Document) fTarget : fTarget.getOwnerDocument();
        fDocumentImpl = (fDocument instanceof CoreDocumentImpl) ? (CoreDocumentImpl) fDocument : null;
        fStorePSVI = (fDocument instanceof PSVIDocumentImpl);
        return;
    }
    fTarget = null;
    fNextSibling = null;
    fDocument = null;
    fDocumentImpl = null;
    fStorePSVI = false;
}
Example 5
Project: jlibs-master  File: DOMUtil.java View source code
public static void main(String[] args) throws Exception {
    String file = "/Volumes/Backup/projects/office/trunk/fountainhead/gateway/testsuites/newregression/messagevalidation/resources/anothergsearch.wsdl";
    Document doc = newDocumentBuilder(true, false, false, false).parse(file);
    SAXDelegate delegate = new SAXDelegate();
    TransformerHandler handler = TransformerUtil.newTransformerHandler(null, true, 0, null);
    delegate.setHandler(handler);
    DOMResult result = new DOMResult();
    handler.setResult(result);
    Node node = doc;
    node = doc.getDocumentElement().getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "binding").item(0);
    toSAX(node, delegate);
    node = result.getNode();
    TransformerUtil.newTransformer(null, true, 0, null).transform(new DOMSource(node), new StreamResult(System.out));
}
Example 6
Project: kabeja-master  File: AbstractSAXSerializer.java View source code
/*
     * (non-Javadoc)
     *
     * @see org.xml.sax.ContentHandler#startDocument()
     */
public void startDocument() throws SAXException {
    try {
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler f = factory.newTransformerHandler();
        this.document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        // put the the transformer in the chain
        f.setResult(new DOMResult(document));
        super.setContentHandler(f);
    } catch (TransformerConfigurationException e) {
        throw new SAXException(e);
    } catch (IllegalArgumentException e) {
        throw new SAXException(e);
    } catch (TransformerFactoryConfigurationError e) {
        throw new SAXException(e.getException());
    } catch (ParserConfigurationException e) {
        throw new SAXException(e);
    }
    super.startDocument();
}
Example 7
Project: geotoolkit-master  File: StaxStreamWriterTest.java View source code
@Test
public void testWritingToDom() throws Exception {
    //this test requiere and advanced Stax library, here we use WoodStox stream reader.
    final DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
    final DocumentBuilder constructeur = fabrique.newDocumentBuilder();
    final Document document = constructeur.newDocument();
    final File file = new File("src/test/resources/org/geotoolkit/xml/sampleOutput.xml");
    if (file.exists())
        file.delete();
    final Result res = new DOMResult(document);
    final MockWriter instance = new MockWriter();
    instance.setOutput(res);
    instance.write();
    instance.dispose();
    //check by reading it back
    final Source src = new DOMSource(document);
    final XMLInputFactory XMLfactory = new WstxInputFactory();
    final XMLStreamReader reader = XMLfactory.createXMLStreamReader(src);
    final MockReader mr = new MockReader();
    mr.setInput(reader);
    StaxStreamReaderTest.validate(mr.read());
    mr.dispose();
}
Example 8
Project: JBossAS51-master  File: XSLSubDeployer.java View source code
public void init(DeploymentInfo di) throws DeploymentException {
    if (di.document == null)
        findDd(di);
    try {
        Transformer trans = templates.newTransformer();
        String urlStr = di.url.toString();
        String shortURL = ServerConfigUtil.shortUrlFromServerHome(urlStr);
        trans.setErrorListener(new JBossErrorHandler(shortURL, null));
        Source s = new DOMSource(di.document);
        DOMResult r = new DOMResult();
        setParameters(trans);
        trans.transform(s, r);
        di.document = (Document) r.getNode();
        if (log.isDebugEnabled()) {
            log.debug("transformed into doc: " + di.document);
            String docStr = DOMWriter.printNode(di.document, true);
            int index = docStr.toLowerCase().indexOf("password");
            if (index != -1) {
                docStr = maskPasswords(docStr, index);
            }
            log.debug("transformed into doc: " + docStr);
        }
    } catch (TransformerException ce) {
        throw new DeploymentException("Problem with xsl transformation", ce);
    }
    delegate.init(di);
}
Example 9
Project: JBossAS_5_1_EDG-master  File: XSLSubDeployer.java View source code
public void init(DeploymentInfo di) throws DeploymentException {
    if (di.document == null)
        findDd(di);
    try {
        Transformer trans = templates.newTransformer();
        String urlStr = di.url.toString();
        String shortURL = ServerConfigUtil.shortUrlFromServerHome(urlStr);
        trans.setErrorListener(new JBossErrorHandler(shortURL, null));
        Source s = new DOMSource(di.document);
        DOMResult r = new DOMResult();
        setParameters(trans);
        trans.transform(s, r);
        di.document = (Document) r.getNode();
        if (log.isDebugEnabled()) {
            log.debug("transformed into doc: " + di.document);
            String docStr = DOMWriter.printNode(di.document, true);
            int index = docStr.toLowerCase().indexOf("password");
            if (index != -1) {
                docStr = maskPasswords(docStr, index);
            }
            log.debug("transformed into doc: " + docStr);
        }
    } catch (TransformerException ce) {
        throw new DeploymentException("Problem with xsl transformation", ce);
    }
    delegate.init(di);
}
Example 10
Project: JFugue-for-Android-master  File: SmartTransformerFactoryImpl.java View source code
/**
     * javax.xml.transform.sax.TransformerFactory implementation.
     * Look up the value of a feature (to see if it is supported).
     * This method must be updated as the various methods and features of this
     * class are implemented.
     *
     * @param name The feature name
     * @return 'true' if feature is supported, 'false' if not
     */
public boolean getFeature(String name) {
    // All supported features should be listed here
    String[] features = { DOMSource.FEATURE, DOMResult.FEATURE, SAXSource.FEATURE, SAXResult.FEATURE, StreamSource.FEATURE, StreamResult.FEATURE };
    // feature name cannot be null
    if (name == null) {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_GET_FEATURE_NULL_NAME);
        throw new NullPointerException(err.toString());
    }
    // Inefficient, but it really does not matter in a function like this
    for (int i = 0; i < features.length; i++) {
        if (name.equals(features[i]))
            return true;
    }
    // secure processing?
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return featureSecureProcessing;
    }
    // unknown feature
    return false;
}

Java Examples for java.rmi.registry.LocateRegistry

The following java examples will help you to understand the usage of java.rmi.registry.LocateRegistry. These source code samples are taken from different open source projects.

Example 1
Project: jdk7u-jdk-master  File: AppleUserImpl.java View source code
/**
     * Entry point for the "juicer" server process.  Create and export
     * an apple user implementation in an rmiregistry running on localhost.
     */
public static void main(String[] args) {
    String durationString = null;
    boolean othervm = false;
    boolean exit = false;
    try {
        // parse command line args
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-hours")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                int hours = Integer.parseInt(args[i]);
                durationString = hours + " hours";
                testDuration = hours * 60 * 60 * 1000;
            } else if (arg.equals("-seconds")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                long seconds = Long.parseLong(args[i]);
                durationString = seconds + " seconds";
                testDuration = seconds * 1000;
            } else if (arg.equals("-maxLevel")) {
                i++;
                maxLevel = Integer.parseInt(args[i]);
            } else if (arg.equals("-othervm")) {
                othervm = true;
            } else if (arg.equals("-exit")) {
                exit = true;
            } else {
                usage();
            }
        }
        if (durationString == null) {
            durationString = testDuration + " milliseconds";
        }
    } catch (Throwable t) {
        usage();
        throw new RuntimeException("TEST FAILED: Bad argument");
    }
    AppleUserImpl user = null;
    long startTime = 0;
    Thread server = null;
    int exitValue = 0;
    try {
        user = new AppleUserImpl();
        synchronized (user) {
            // create new registry and bind new AppleUserImpl in registry
            LocateRegistry.createRegistry(2006);
            LocateRegistry.getRegistry(2006).rebind("AppleUser", user);
            // start the other server if applicable
            if (othervm) {
                // the other server must be running in a separate process
                logger.log(Level.INFO, "Application server must be " + "started in separate process");
            } else {
                Class app = Class.forName("ApplicationServer");
                server = new Thread((Runnable) app.newInstance());
                logger.log(Level.INFO, "Starting application server " + "in same process");
                server.start();
            }
            // wait for other server to call startTest method
            logger.log(Level.INFO, "Waiting for application server " + "process to start");
            while (!startTestNotified) {
                user.wait();
            }
        }
        startTime = System.currentTimeMillis();
        logger.log(Level.INFO, "Test starting");
        // wait for exception to be reported or first thread to complete
        logger.log(Level.INFO, "Waiting " + durationString + " for " + "test to complete or exception to be thrown");
        synchronized (lock) {
            while (status == null && !finished) {
                lock.wait();
            }
        }
        if (status != null) {
            throw new RuntimeException("TEST FAILED: " + "juicer server reported an exception", status);
        } else {
            logger.log(Level.INFO, "TEST PASSED");
        }
    } catch (Exception e) {
        logger.log(Level.INFO, "TEST FAILED");
        exitValue = 1;
        if (exit) {
            e.printStackTrace();
        }
        throw new RuntimeException("TEST FAILED: " + "unexpected exception", e);
    } finally {
        long actualDuration = System.currentTimeMillis() - startTime;
        logger.log(Level.INFO, "Test finished");
        try {
            UnicastRemoteObject.unexportObject(user, true);
        } catch (NoSuchObjectException ignore) {
        }
        logger.log(Level.INFO, "Test duration was " + (actualDuration / 1000) + " seconds " + "(" + (actualDuration / 3600000) + " hours)");
        System.gc();
        System.gc();
        if (exit) {
            System.exit(exitValue);
        }
    }
}
Example 2
Project: ManagedRuntimeInitiative-master  File: MapNullValuesTest.java View source code
public static void main(String[] args) throws Exception {
    int errorCount = 0;
    MapNullValuesTest test = new MapNullValuesTest();
    // Create an RMI registry
    //
    echo("");
    echo(dashedMessage("Start RMI registry"));
    Registry reg = null;
    port = 7500;
    while (port++ < 7550) {
        try {
            reg = LocateRegistry.createRegistry(port);
            echo("\nRMI registry running on port " + port);
            break;
        } catch (RemoteException e) {
            echo("\nFailed to create RMI registry on port " + port);
            e.printStackTrace(System.out);
        }
    }
    if (reg == null) {
        System.exit(1);
    }
    // Run tests
    //
    errorCount += test.mapToHashtableTests();
    errorCount += test.jmxConnectorServerFactoryTests();
    errorCount += test.jmxConnectorFactoryTests();
    errorCount += test.nullKeyFactoryTests();
    if (errorCount == 0) {
        echo("\nNull values for key/value pairs in Map Tests PASSED!");
    } else {
        echo("\nNull values for key/value pairs in Map Tests FAILED!");
        System.exit(1);
    }
}
Example 3
Project: openjdk8-jdk-master  File: AppleUserImpl.java View source code
/**
     * Entry point for the "juicer" server process.  Create and export
     * an apple user implementation in an rmiregistry running on localhost.
     */
public static void main(String[] args) {
    String durationString = null;
    boolean othervm = false;
    boolean exit = false;
    try {
        // parse command line args
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-hours")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                int hours = Integer.parseInt(args[i]);
                durationString = hours + " hours";
                testDuration = hours * 60 * 60 * 1000;
            } else if (arg.equals("-seconds")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                long seconds = Long.parseLong(args[i]);
                durationString = seconds + " seconds";
                testDuration = seconds * 1000;
            } else if (arg.equals("-maxLevel")) {
                i++;
                maxLevel = Integer.parseInt(args[i]);
            } else if (arg.equals("-othervm")) {
                othervm = true;
            } else if (arg.equals("-exit")) {
                exit = true;
            } else {
                usage();
            }
        }
        if (durationString == null) {
            durationString = testDuration + " milliseconds";
        }
    } catch (Throwable t) {
        usage();
        throw new RuntimeException("TEST FAILED: Bad argument");
    }
    AppleUserImpl user = null;
    long startTime = 0;
    Thread server = null;
    int exitValue = 0;
    try {
        user = new AppleUserImpl();
        synchronized (user) {
            // create new registry and bind new AppleUserImpl in registry
            Registry registry = TestLibrary.createRegistryOnUnusedPort();
            registryPort = TestLibrary.getRegistryPort(registry);
            LocateRegistry.getRegistry(registryPort).rebind("AppleUser", user);
            // start the other server if applicable
            if (othervm) {
                // the other server must be running in a separate process
                logger.log(Level.INFO, "Application server must be " + "started in separate process");
            } else {
                Class app = Class.forName("ApplicationServer");
                java.lang.reflect.Constructor appConstructor = app.getDeclaredConstructor(new Class[] { Integer.TYPE });
                server = new Thread((Runnable) appConstructor.newInstance(registryPort));
                logger.log(Level.INFO, "Starting application server " + "in same process");
                server.start();
            }
            // wait for other server to call startTest method
            logger.log(Level.INFO, "Waiting for application server " + "process to start");
            while (!startTestNotified) {
                user.wait();
            }
        }
        startTime = System.currentTimeMillis();
        logger.log(Level.INFO, "Test starting");
        // wait for exception to be reported or first thread to complete
        logger.log(Level.INFO, "Waiting " + durationString + " for " + "test to complete or exception to be thrown");
        synchronized (lock) {
            while (status == null && !finished) {
                lock.wait();
            }
        }
        if (status != null) {
            throw new RuntimeException("TEST FAILED: " + "juicer server reported an exception", status);
        } else {
            logger.log(Level.INFO, "TEST PASSED");
        }
    } catch (Exception e) {
        logger.log(Level.INFO, "TEST FAILED");
        exitValue = 1;
        if (exit) {
            e.printStackTrace();
        }
        throw new RuntimeException("TEST FAILED: " + "unexpected exception", e);
    } finally {
        long actualDuration = System.currentTimeMillis() - startTime;
        logger.log(Level.INFO, "Test finished");
        try {
            UnicastRemoteObject.unexportObject(user, true);
        } catch (NoSuchObjectException ignore) {
        }
        logger.log(Level.INFO, "Test duration was " + (actualDuration / 1000) + " seconds " + "(" + (actualDuration / 3600000) + " hours)");
        System.gc();
        System.gc();
        if (exit) {
            System.exit(exitValue);
        }
    }
}
Example 4
Project: openjdk-master  File: Main.java View source code
/**
     * Setup benchmark server.
     */
static void setupServer() {
    switch(runmode) {
        case SAMEVM:
            try {
                serverImpl = new BenchServerImpl();
                server = (BenchServer) RemoteObject.toStub(serverImpl);
            } catch (RemoteException e) {
                die("Error: failed to create local server: " + e);
            }
            if (verbose)
                System.out.println("Benchmark server created locally");
            break;
        case CLIENT:
            try {
                Registry reg = LocateRegistry.getRegistry(host, port);
                server = (BenchServer) reg.lookup(REGNAME);
            } catch (NotBoundExceptionRemoteException |  e) {
                die("Error: failed to connect to server: " + e);
            }
            if (server == null) {
                die("Error: server not found");
            }
            if (verbose) {
                System.out.println("Connected to benchmark server on " + host + ":" + port);
            }
            break;
        case SERVER:
            try {
                Registry reg = LocateRegistry.createRegistry(port);
                serverImpl = new BenchServerImpl();
                reg.bind(REGNAME, serverImpl);
            } catch (AlreadyBoundExceptionRemoteException |  e) {
                die("Error: failed to initialize server: " + e);
            }
            if (verbose) {
                System.out.println("Benchmark server started on port " + port);
            }
            break;
        default:
            throw new InternalError("illegal runmode");
    }
}
Example 5
Project: btpka3.github.com-master  File: MyServer.java View source code
public static void main(String[] args) throws Exception {
    // start RMI server
    // or CMD/> rmiregistry 9999
    LocateRegistry.createRegistry(9999);
    // setup MBeanServer
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    MyServer s = new MyServer();
    ObjectName objName = new ObjectName("MyServer:type=Hello");
    mbs.registerMBean(s, objName);
    // start JMXConnectorServer
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    System.out.println("MBeanServer start");
}
Example 6
Project: interface_sdk-master  File: ModuleRMIHelper.java View source code
@Override
protected ModuleManagerRemote getManager() throws ModuleManagerCommunicationException {
    Registry registry;
    try {
        registry = LocateRegistry.getRegistry("localhost", ModuleManagerRunner.RMI_REGISTRY_PORT);
        ModuleManagerRemote obj = (ModuleManagerRemote) registry.lookup(ModuleManagerRunner.RMI_SERVER_NAME);
        log.debug("Got an instance of ModuleManager via RMI?");
        return obj;
    } catch (RemoteException e) {
        throw new ModuleManagerCommunicationException();
    } catch (NotBoundException e) {
        throw new ModuleManagerCommunicationException();
    }
}
Example 7
Project: eclipselink.runtime-master  File: DistributedCacheMergeTest.java View source code
protected void setup() throws Exception {
    originalSession = getExecutor().getSession();
    originalSession.getIdentityMapAccessor().initializeAllIdentityMaps();
    createObject();
    try {
        LocateRegistry.createRegistry(41099);
    } catch (Exception e) {
    }
    cluster1Session = buildSession("cluster1");
    cluster1Session.login();
    cluster2Session = buildSession("cluster2");
    cluster2Session.login();
    // Let the Cache-sync get configured.
    Thread.sleep(5000);
    policy1 = disableOptimisticLocking(cluster1Session);
    policy2 = disableOptimisticLocking(cluster2Session);
}
Example 8
Project: JBossAS51-master  File: JMXConnectorServerService.java View source code
public void start() throws Exception {
    // the address to expose in the urls
    String host = System.getProperty("java.rmi.server.hostname");
    // check to see if registry already created
    rmiRegistry = LocateRegistry.getRegistry(host, registryPort);
    if (rmiRegistry != null) {
        try {
            rmiRegistry.list();
        } catch (RemoteException e) {
            log.debug("No registry running at host '" + host + "', port '" + registryPort + "'.  Will create one.");
            rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
        }
    } else {
        rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
    }
    String serviceURL = "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + registryPort + jndiPath;
    JMXServiceURL url = new JMXServiceURL(serviceURL);
    // create new connector server and start it
    final Map<String, Object> environment = new HashMap<String, Object>();
    final DefaultSocketFactory clientSocketFactory = new DefaultSocketFactory();
    clientSocketFactory.setBindAddress(bindAddress.getHostAddress());
    environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
    connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer);
    connectorServer.start();
    log.info("JMX Connector server: " + serviceURL);
}
Example 9
Project: org.ops4j.pax.swissbox-master  File: RemoteFrameworkImpl.java View source code
private void export() throws RemoteException, AccessException {
    String port = System.getProperty(RMI_PORT_KEY, "1099");
    name = System.getProperty(RMI_NAME_KEY);
    timeout = Long.parseLong(System.getProperty(TIMEOUT_KEY, "10000"));
    registry = LocateRegistry.getRegistry(Integer.parseInt(port));
    URL location1 = getClass().getProtectionDomain().getCodeSource().getLocation();
    URL location2 = Bundle.class.getProtectionDomain().getCodeSource().getLocation();
    URL location3 = ServiceLookup.class.getProtectionDomain().getCodeSource().getLocation();
    System.setProperty("java.rmi.server.codebase", location1 + " " + location2 + " " + location3);
    Remote remote = UnicastRemoteObject.exportObject(this, 0);
    registry.rebind(name, remote);
}
Example 10
Project: JBossAS_5_1_EDG-master  File: JMXConnectorServerService.java View source code
public void start() throws Exception {
    // the address to expose in the urls
    String host = System.getProperty("java.rmi.server.hostname");
    // check to see if registry already created
    rmiRegistry = LocateRegistry.getRegistry(host, registryPort);
    if (rmiRegistry != null) {
        try {
            rmiRegistry.list();
        } catch (RemoteException e) {
            log.debug("No registry running at host '" + host + "', port '" + registryPort + "'.  Will create one.");
            rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
        }
    } else {
        rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
    }
    String serviceURL = "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + registryPort + jndiPath;
    JMXServiceURL url = new JMXServiceURL(serviceURL);
    // create new connector server and start it
    final Map<String, Object> environment = new HashMap<String, Object>();
    final DefaultSocketFactory clientSocketFactory = new DefaultSocketFactory();
    clientSocketFactory.setBindAddress(bindAddress.getHostAddress());
    environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
    connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer);
    connectorServer.start();
    log.info("JMX Connector server: " + serviceURL);
}
Example 11
Project: spring-framework-2.5.x-master  File: RmiClientInterceptor.java View source code
/**
	 * Create the RMI stub, typically by looking it up.
	 * <p>Called on interceptor initialization if "cacheStub" is "true";
	 * else called for each invocation by [email protected] #getStub()}.
	 * <p>The default implementation looks up the service URL via
	 * <code>java.rmi.Naming</code>. This can be overridden in subclasses.
	 * @return the RMI stub to store in this interceptor
	 * @throws RemoteLookupFailureException if RMI stub creation failed
	 * @see #setCacheStub
	 * @see java.rmi.Naming#lookup
	 */
protected Remote lookupStub() throws RemoteLookupFailureException {
    try {
        Remote stub = null;
        if (this.registryClientSocketFactory != null) {
            // RMIClientSocketFactory specified for registry access.
            // Unfortunately, due to RMI API limitations, this means
            // that we need to parse the RMI URL ourselves and perform
            // straight LocateRegistry.getRegistry/Registry.lookup calls.
            URL url = new URL(null, getServiceUrl(), new DummyURLStreamHandler());
            String protocol = url.getProtocol();
            if (protocol != null && !"rmi".equals(protocol)) {
                throw new MalformedURLException("Invalid URL scheme '" + protocol + "'");
            }
            String host = url.getHost();
            int port = url.getPort();
            String name = url.getPath();
            if (name != null && name.startsWith("/")) {
                name = name.substring(1);
            }
            Registry registry = LocateRegistry.getRegistry(host, port, this.registryClientSocketFactory);
            stub = registry.lookup(name);
        } else {
            // Can proceed with standard RMI lookup API...
            stub = Naming.lookup(getServiceUrl());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Located RMI stub with URL [" + getServiceUrl() + "]");
        }
        return stub;
    } catch (MalformedURLException ex) {
        throw new RemoteLookupFailureException("Service URL [" + getServiceUrl() + "] is invalid", ex);
    } catch (NotBoundException ex) {
        throw new RemoteLookupFailureException("Could not find RMI service [" + getServiceUrl() + "] in RMI registry", ex);
    } catch (RemoteException ex) {
        throw new RemoteLookupFailureException("Lookup of RMI stub failed", ex);
    }
}
Example 12
Project: open-mika-master  File: Naming.java View source code
private static Registry getRegistry(String url, StringBuffer name) throws MalformedURLException, RemoteException {
    int port = Registry.REGISTRY_PORT;
    String host = "localhost";
    if (url.startsWith("rmi:")) {
        url = url.substring(4);
    }
    if (url.startsWith("//")) {
        int index = url.indexOf("/", 2);
        if (index == -1) {
            throw new MalformedURLException("no name specified in: " + url);
        }
        host = url.substring(2, index);
        url = url.substring(index + 1);
        index = host.indexOf(":");
        if (index != -1) {
            try {
                port = Integer.parseInt(host.substring(index + 1));
            } catch (NumberFormatException nfe) {
                throw new MalformedURLException("invalid port");
            }
            host = host.substring(0, index);
        }
    }
    name.append(url);
    if (host.length() == 0) {
        host = "localhost";
    }
    return LocateRegistry.getRegistry(host, port);
}
Example 13
Project: wso2-synapse-master  File: RMIRegistryController.java View source code
/**
     * Creates a RMI local registry with given port
     *
     * @param port The port of the RMI registry to be created
     */
public void createLocalRegistry(int port) {
    try {
        String key = toKey(port);
        synchronized (registriesCache) {
            if (registriesCache.containsKey(key)) {
                if (log.isDebugEnabled()) {
                    log.debug("There is an RMI registry bound to given port :" + port);
                }
                return;
            }
            Registry locateRegistry = LocateRegistry.createRegistry(port);
            if (locateRegistry == null) {
                handleException("Unable to create a RMI registry with port : " + port);
            }
            registriesCache.put(key, locateRegistry);
        }
    } catch (RemoteException e) {
        String msg = "Couldn't create a local registry(RMI) : port " + port + " already in use.";
        handleException(msg, e);
    }
}
Example 14
Project: classlib6-master  File: Main.java View source code
private void run(String[] args) {
    Parser p = initializeParser();
    p.parse(args);
    try {
        if (!stop) {
            // Start the system.
            File dataDirectory = new File(directory);
            if (!dataDirectory.exists())
                dataDirectory.mkdirs();
            ActivationSystem system;
            if (!persistent)
                system = ActivationSystemTransient.getInstance();
            else
                system = ActivationSystemImpl.getInstance(dataDirectory, cold);
            // We must export with the specific activation id that is only
            // possible when going into the gnu.java.rmi.activation.
            UnicastServerRef sref = new UnicastServerRef(new ObjID(ObjID.ACTIVATOR_ID), ACTIVATION_REGISTRY_PORT, ACTIVATION_REGISTY_SOCKET_FACTORY);
            Remote systemStub = sref.exportObject(system);
            // Start the naming system on the activation system port
            // (if not already running).
            Registry r;
            try {
                // Expect the naming service running first.
                // The local host may want to use the shared registry
                r = LocateRegistry.getRegistry(ACTIVATION_REGISTRY_PORT);
                r.rebind(ACTIVATION_SYSTEM_NAME, systemStub);
            } catch (Exception ex) {
                r = LocateRegistry.createRegistry(ACTIVATION_REGISTRY_PORT);
                r.rebind(ACTIVATION_SYSTEM_NAME, systemStub);
            }
            String host = InetAddress.getLocalHost().getCanonicalHostName();
            System.out.println("The RMI daemon is listening on " + host + " (port " + ACTIVATION_REGISTRY_PORT + ")");
        } else {
            // Stop the activation system.
            Registry r;
            try {
                System.out.print("Stopping RMI daemon at " + ACTIVATION_REGISTRY_PORT + " ... ");
                // Expect the naming service running first.
                // The local host may want to use the shared registry
                r = LocateRegistry.getRegistry(ACTIVATION_REGISTRY_PORT);
                ActivationSystem asys = (ActivationSystem) r.lookup(ACTIVATION_SYSTEM_NAME);
                asys.shutdown();
                System.out.println("OK.");
            } catch (Exception ex) {
                System.out.println("The RMI daemon seems not running at " + ACTIVATION_REGISTRY_PORT);
                if (ActivationSystemTransient.debug)
                    ex.printStackTrace();
            }
        }
    } catch (Exception e) {
        System.out.println("Failed to start the RMI daemon.");
        if (ActivationSystemTransient.debug)
            e.printStackTrace();
    }
}
Example 15
Project: Payara-master  File: EventListenerProxy.java View source code
public static synchronized EventListenerProxy getEventListenerProxy() {
    if (eventProxy == null) {
        EventListenerProxy newProxy = null;
        try {
            newProxy = new EventListenerProxy();
            Naming.rebind(newProxy.proxyAddress, newProxy);
            eventProxy = newProxy;
            if (debug)
                System.out.println(eventProxy.rmiName + " bound to existing registry at port " + portnum);
        } catch (RemoteException re) {
            if (debug)
                System.out.println("Naming.rebind(" + (newProxy != null ? newProxy.proxyAddress : "null") + ", eventProxy): " + re);
            try {
                newProxy = new EventListenerProxy();
                Registry r = LocateRegistry.createRegistry(portnum);
                r.bind(newProxy.rmiName, newProxy);
                eventProxy = newProxy;
                if (debug)
                    System.out.println(newProxy.rmiName + " bound to newly created registry at port " + portnum);
            } catch (Exception e) {
                eventProxy = null;
                if (debug)
                    e.printStackTrace();
            }
        } catch (Exception e) {
            if (debug)
                e.printStackTrace();
        }
    }
    return eventProxy;
}
Example 16
Project: glassfish-main-master  File: EventListenerProxy.java View source code
public static EventListenerProxy getEventListenerProxy() {
    if (eventProxy == null) {
        try {
            eventProxy = new EventListenerProxy();
            Naming.rebind(proxyAddress, eventProxy);
            if (debug)
                System.out.println(rmiName + " bound to existing registry at port " + portnum);
        } catch (RemoteException re) {
            if (debug)
                System.out.println("Naming.rebind(" + proxyAddress + ", eventProxy): " + re);
            try {
                eventProxy = new EventListenerProxy();
                Registry r = LocateRegistry.createRegistry(portnum);
                r.bind(rmiName, eventProxy);
                if (debug)
                    System.out.println(rmiName + " bound to newly created registry at port " + portnum);
            } catch (Exception e) {
                eventProxy = null;
                if (debug)
                    e.printStackTrace();
            }
        } catch (Exception e) {
            if (debug)
                e.printStackTrace();
        }
    }
    return eventProxy;
}
Example 17
Project: resin-master  File: RmiRegistry.java View source code
/**
   * Start the RMI registry in the local JVM, if it has not been started
   * already.
   */
private void startRegistry() throws ResourceAdapterInternalException {
    /**
     * Some tricks are required here, the RMI Registry needs to be
     * started from the system classloader.
     */
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
        try {
            Registry reg = LocateRegistry.getRegistry(_port);
            // Verify it's alive and well
            reg.list();
            if (log.isLoggable(Level.CONFIG))
                log.config(L.l("found RMI Registry on port `{0}'", _port));
        } catch (Exception e) {
            if (log.isLoggable(Level.CONFIG))
                log.config(L.l("creating RMI Registry on port `{0}'", _port));
            LocateRegistry.createRegistry(_port);
        }
    } catch (Exception ex) {
        throw new ResourceAdapterInternalException(ex);
    } finally {
        thread.setContextClassLoader(oldLoader);
    }
}
Example 18
Project: ikvm-openjdk-master  File: Jstatd.java View source code
static void bind(String name, RemoteHostImpl remoteHost) throws RemoteException, MalformedURLException, Exception {
    try {
        Naming.rebind(name, remoteHost);
    } catch (java.rmi.ConnectException e) {
        if (startRegistry && registry == null) {
            int localport = (port < 0) ? Registry.REGISTRY_PORT : port;
            registry = LocateRegistry.createRegistry(localport);
            bind(name, remoteHost);
        } else {
            System.out.println("Could not contact registry\n" + e.getMessage());
            e.printStackTrace();
        }
    } catch (RemoteException e) {
        System.err.println("Could not bind " + name + " to RMI Registry");
        e.printStackTrace();
    }
}
Example 19
Project: lucene-solr-master  File: TestJmxMonitoredMap.java View source code
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    String oldHost = System.getProperty("java.rmi.server.hostname");
    try {
        // this stupid sysprop thing is needed, because remote stubs use an
        // arbitrary local ip to connect
        // See: http://weblogs.java.net/blog/emcmanus/archive/2006/12/multihomed_comp.html
        System.setProperty("java.rmi.server.hostname", "127.0.0.1");
        class LocalhostRMIServerSocketFactory implements RMIServerSocketFactory {

            ServerSocket socket;

            @Override
            public ServerSocket createServerSocket(int port) throws IOException {
                return socket = new ServerSocket(port);
            }
        }
        ;
        LocalhostRMIServerSocketFactory factory = new LocalhostRMIServerSocketFactory();
        LocateRegistry.createRegistry(0, null, factory);
        port = factory.socket.getLocalPort();
        log.info("Using port: " + port);
        String url = "service:jmx:rmi:///jndi/rmi://127.0.0.1:" + port + "/solrjmx";
        JmxConfiguration config = new JmxConfiguration(true, null, url, null);
        monitoredMap = new JmxMonitoredMap<>("", "", config);
        JMXServiceURL u = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(u);
        mbeanServer = connector.getMBeanServerConnection();
    } finally {
        if (oldHost == null) {
            System.clearProperty("java.rmi.server.hostname");
        } else {
            System.setProperty("java.rmi.server.hostname", oldHost);
        }
    }
}
Example 20
Project: Rio-master  File: ServiceBeanExecutorImpl.java View source code
private void bootstrap(final String[] configArgs) throws Exception {
    ClassLoader cCL = Thread.currentThread().getContextClassLoader();
    Configuration config = new GroovyConfig(configArgs, cCL);
    logger.debug("Loaded config");
    container = new ServiceBeanContainerImpl(config);
    computeResource = new ComputeResource(config);
    /* Setup persistent provisioning attributes */
    boolean provisionEnabled = (Boolean) config.getEntry("org.rioproject.cybernode", "provisionEnabled", Boolean.class, true);
    computeResource.setPersistentProvisioning(provisionEnabled);
    String provisionRoot = Environment.setupProvisionRoot(provisionEnabled, config);
    computeResource.setPersistentProvisioningRoot(provisionRoot);
    MeasurableCapability[] mCaps = loadMeasurables(config);
    for (MeasurableCapability mCap : mCaps) {
        computeResource.addMeasurableCapability(mCap);
        mCap.start();
    }
    container.setComputeResource(computeResource);
    container.addListener(this);
    context = ServiceBeanActivation.getServiceBeanContext(CONFIG_COMPONENT, "Cybernode", configArgs, config, getClass().getClassLoader());
    registry = LocateRegistry.getRegistry(cybernodeRegistryPort);
    exporter = ExporterConfig.getExporter(config, "org.rioproject.cybernode", "exporter");
    int createdRegistryPort = RegistryUtil.getRegistry();
    if (createdRegistryPort > 0) {
        System.setProperty(Constants.REGISTRY_PORT, Integer.toString(createdRegistryPort));
    } else {
        throw new RuntimeException("Unable to create RMI Registry");
    }
    Remote proxy = exporter.export(this);
    registry.bind(execBindName, proxy);
    new Thread(new CreateFDH(config, this)).start();
}
Example 21
Project: google-web-toolkit-svnmirror-master  File: BrowserManagerServerLauncher.java View source code
/**
   * This method should be invoked after argument parsing completes.
   */
public void run() {
    Registry rmiRegistry = null;
    try {
        // Create an RMI registry so we don't need an external process.
        // Uses the default RMI port if no port is specified with the -port arg.
        rmiRegistry = LocateRegistry.createRegistry(portArg);
    } catch (RemoteException e) {
        logger.log(Level.SEVERE, "Couldn't bind RMI Registry to port " + portArg, e);
        System.exit(1);
    }
    logger.log(Level.ALL, "RMI registry ready on port " + portArg + ".");
    // Startup each of the registered servers on this machine.
    for (BMSEntry entry : bmsList) {
        BrowserManagerServer server = null;
        try {
            server = new BrowserManagerServer(entry.browserPath, serializeArg);
        } catch (RemoteException re) {
            logger.log(Level.SEVERE, entry.registrationKey + ": Error starting new BrowserManagerServer.", re);
            System.exit(2);
        }
        try {
            rmiRegistry.rebind(entry.registrationKey, server);
        } catch (RemoteException re) {
            logger.log(Level.SEVERE, entry.registrationKey + " server: " + server + " port: " + portArg + " Error on rebind to " + entry.registrationKey, re);
            System.exit(3);
        }
        logger.log(Level.INFO, "Server: " + entry.registrationKey + " started and awaiting connections.");
    }
    logger.log(Level.INFO, "All servers started.");
}
Example 22
Project: sqlpower-library-master  File: DBConnectionSpecServerImpl.java View source code
/**
	 * Basic server main.  This class is executable with a command line
	 * something like this:
	 * 
	 * java -Djava.rmi.server.codebase="base.of.classpath" \
	 *      -cp ".;../../../../common/lib/xerces.jar" \
	 *      -Djava.security.policy=rmi.policy \
	 *      -DdatabasesFile=../databases.xml \
	 *      ca.sqlpower.sql.DBConnectionSpecServerImpl
	 */
public static void main(String args[]) throws RemoteException {
    // Create and install a security manager
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new RMISecurityManager());
    }
    DBConnectionSpecServerImpl obj = new DBConnectionSpecServerImpl();
    obj.xmlFileName = System.getProperty("databasesFile");
    if (obj.xmlFileName == null) {
        System.out.println("no databases file specified.  Please add -DdatabaseFile=filename to the command line.");
    } else {
        try {
            java.rmi.registry.LocateRegistry.createRegistry(1099);
            Naming.rebind("///DBConnectionSpecServer", obj);
            System.out.println("DBConnectionSpecServer bound in registry");
        } catch (Exception e) {
            System.out.println("DBConnectionSpecImpl err: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Example 23
Project: oliot-fc-master  File: ALESettings.java View source code
private void initJConsole() {
    LOG.debug("initializing JConsole");
    try {
        // Ensure cryptographically strong random number generator used
        // to choose the object number - see java.rmi.server.ObjID
        //
        System.setProperty("java.rmi.server.randomIDs", "true");
        // Start an RMI registry on port 5001.
        //
        LOG.debug("Create RMI registry on port 5001");
        //LocateRegistry.createRegistry(5001);
        //int registryPort = org.fosstrak.llrp.adaptor.Constants.registryPort;
        // Retrieve the PlatformMBeanServer.
        //
        LOG.debug("Get the platform's MBean server");
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        // Environment map.
        //
        LOG.debug("Initialize the environment map");
        HashMap<String, Object> env = new HashMap<String, Object>();
        // Provide SSL-based RMI socket factories.
        //
        // The protocol and cipher suites to be enabled will be the ones
        // defined by the default JSSE implementation and only server
        // authentication will be required.
        //
        /*
	        SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
	        SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
	        env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
	        env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
	*/
        // Provide the password file used by the connector server to
        // perform user authentication. The password file is a properties
        // based text file specifying username/password pairs.
        //
        //env.put("jmx.remote.x.password.file", "password.properties");
        // Provide the access level file used by the connector server to
        // perform user authorization. The access level file is a properties
        // based text file specifying username/access level pairs where
        // access level is either "readonly" or "readwrite" access to the
        // MBeanServer operations.
        //
        //env.put("jmx.remote.x.access.file", "access.properties");
        // Create an RMI connector server.
        //
        // As specified in the JMXServiceURL the RMIServer stub will be
        // registered in the RMI registry running in the local host on
        // port 3000 with the name "jmxrmi". This is the same name the
        // out-of-the-box management agent uses to register the RMIServer
        // stub too.
        //
        //-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=5000
        env.put("com.sun.management.jmxremote.authenticate", "false");
        env.put("com.sun.management.jmxremote.ssl", "false");
        LOG.debug("Create an RMI connector server where RmiConnPort=5002, RmiRegistryPort=5001");
        //JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + 5002  + "/jndi/rmi://localhost:" + 5001 + "/jmxrmi");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + 5002 + "/jndi/rmi://localhost:" + 5556 + "/jmxrmi");
        JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        // Start the RMI connector server.
        //
        LOG.debug("Start the RMI connector server");
        cs.start();
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 24
Project: gluu-opendj-master  File: RmiConnector.java View source code
/**
   * Starts the common RMI registry. In order to provide RMI stub for
   * remote client, the JMX RMI connector should be register into an RMI
   * registry. Each server will maintain its own private one.
   *
   * @throws Exception
   *             if the registry cannot be started
   */
private void startCommonRegistry() throws Exception {
    int registryPort = jmxConnectionHandler.getListenPort();
    // create our local RMI registry if it does not exist already
    if (debugEnabled()) {
        TRACER.debugVerbose("start or reach an RMI registry on port %d", registryPort);
    }
    try {
        // TODO Not yet implemented: If the host has several interfaces
        if (registry == null) {
            rmiSsf = new OpendsRmiServerSocketFactory();
            registry = LocateRegistry.createRegistry(registryPort, null, rmiSsf);
        }
    } catch (RemoteException re) {
        if (debugEnabled()) {
            TRACER.debugWarning("cannot create the RMI registry -> already done ?");
        }
        try {
            Registry reg = LocateRegistry.getRegistry(registryPort);
            reg.list();
            registry = reg;
        } catch (Exception e) {
            if (debugEnabled()) {
                TRACER.debugError("exception thrown while pinging the RMI registry");
                TRACER.debugCaught(DebugLogLevel.ERROR, re);
            }
            throw re;
        }
        if (debugEnabled()) {
            TRACER.debugWarning("RMI was registry already started");
        }
    }
}
Example 25
Project: cids-server-master  File: StartProxy.java View source code
/**
     * DOCUMENT ME!
     *
     * @param   port  DOCUMENT ME!
     *
     * @return  DOCUMENT ME!
     *
     * @throws  ServerExitError  DOCUMENT ME!
     */
private Registry initRegistry(final int port) throws ServerExitError {
    try {
        if (LOG.isDebugEnabled()) {
            // NOI18N
            LOG.debug("<CS> DEBUG: getRMIRegistry on port " + port);
        }
        return LocateRegistry.getRegistry(port);
    } catch (final RemoteException e) {
        final String info = "<CS> INFO: no RMIRegistry on port " + port + " available";
        final String message = "<CS> INFO: create RMIRegistry on port " + port;
        System.out.println(e.getMessage() + " \n" + info);
        System.out.println(message);
        if (LOG.isInfoEnabled()) {
            LOG.info(info, e);
            LOG.info(message);
        }
        try {
            return LocateRegistry.createRegistry(port);
        } catch (final RemoteException ex) {
            final String fatal = "SEVERE: cannot create registry on port: " + port;
            LOG.fatal(fatal, ex);
            throw new ServerExitError(fatal, ex);
        }
    }
}

Java Examples for javax.swing.DefaultCellEditor

The following java examples will help you to understand the usage of javax.swing.DefaultCellEditor. These source code samples are taken from different open source projects.

Example 1
Project: jdk7u-jdk-master  File: javax_swing_DefaultCellEditor.java View source code
protected void validate(DefaultCellEditor before, DefaultCellEditor after) {
    String text = ((JTextComponent) after.getComponent()).getText();
    if (!text.equals(((JTextComponent) before.getComponent()).getText()))
        throw new Error("Invalid text in component: " + text);
}
Example 2
Project: ManagedRuntimeInitiative-master  File: javax_swing_DefaultCellEditor.java View source code
protected void validate(DefaultCellEditor before, DefaultCellEditor after) {
    String text = ((JTextComponent) after.getComponent()).getText();
    if (!text.equals(((JTextComponent) before.getComponent()).getText()))
        throw new Error("Invalid text in component: " + text);
}
Example 3
Project: openjdk8-jdk-master  File: javax_swing_DefaultCellEditor.java View source code
protected void validate(DefaultCellEditor before, DefaultCellEditor after) {
    String text = ((JTextComponent) after.getComponent()).getText();
    if (!text.equals(((JTextComponent) before.getComponent()).getText()))
        throw new Error("Invalid text in component: " + text);
}
Example 4
Project: openjdk-master  File: TAB.java View source code
static void initTest(Container contentPane) {
    // Take the dummy data from SwingSet.
    final String[] names = { "First Name", "Last Name", "Favorite Color", "Favorite Number", "Vegetarian" };
    final Object[][] data = { { "Mark", "Andrews", "Red", new Integer(2), new Boolean(true) }, { "Tom", "Ball", "Blue", new Integer(99), new Boolean(false) }, { "Alan", "Chung", "Green", new Integer(838), new Boolean(false) }, { "Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true) }, { "Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false) }, { "Brian", "Gerhold", "Green", new Integer(0), new Boolean(false) }, { "James", "Gosling", "Pink", new Integer(21), new Boolean(false) }, { "David", "Karlton", "Red", new Integer(1), new Boolean(false) }, { "Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false) }, { "Peter", "Korn", "Purple", new Integer(12), new Boolean(false) }, { "Phil", "Milne", "Purple", new Integer(3), new Boolean(false) }, { "Dave", "Moore", "Green", new Integer(88), new Boolean(false) }, { "Hans", "Muller", "Maroon", new Integer(5), new Boolean(false) }, { "Rick", "Levenson", "Blue", new Integer(2), new Boolean(false) }, { "Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false) }, { "Chester", "Rose", "Black", new Integer(0), new Boolean(false) }, { "Ray", "Ryan", "Gray", new Integer(77), new Boolean(false) }, { "Georges", "Saab", "Red", new Integer(4), new Boolean(false) }, { "Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false) }, { "Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false) }, { "Arnaud", "Weber", "Green", new Integer(44), new Boolean(false) } };
    // Create a model of the data.
    TableModel dataModel = new AbstractTableModel() {

        // These methods always need to be implemented.
        public int getColumnCount() {
            return names.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        // The default implementations of these methods in
        // AbstractTableModel would work, but we can refine them.
        public String getColumnName(int column) {
            return names[column];
        }

        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        public boolean isCellEditable(int row, int col) {
            return true;
        }

        public void setValueAt(Object aValue, int row, int column) {
            System.out.println("Setting value to: " + aValue);
            data[row][column] = aValue;
        }
    };
    // Create the table
    JTable tableView = new JTable(dataModel);
    // Turn off auto-resizing so that we can set column sizes programmatically.
    // In this mode, all columns will get their preferred widths, as set blow.
    tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // Create a combo box to show that you can use one in a table.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Red");
    comboBox.addItem("Orange");
    comboBox.addItem("Yellow");
    comboBox.addItem("Green");
    comboBox.addItem("Blue");
    comboBox.addItem("Indigo");
    comboBox.addItem("Violet");
    TableColumn colorColumn = tableView.getColumn("Favorite Color");
    // Use the combo box as the editor in the "Favorite Color" column.
    colorColumn.setCellEditor(new DefaultCellEditor(comboBox));
    // Set a pink background and tooltip for the Color column renderer.
    DefaultTableCellRenderer colorColumnRenderer = new DefaultTableCellRenderer();
    colorColumnRenderer.setBackground(Color.pink);
    colorColumnRenderer.setToolTipText("Click for combo box");
    colorColumn.setCellRenderer(colorColumnRenderer);
    // Set a tooltip for the header of the colors column.
    TableCellRenderer headerRenderer = colorColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
        ((DefaultTableCellRenderer) headerRenderer).setToolTipText("Hi Mom!");
    // Set the width of the "Vegetarian" column.
    TableColumn vegetarianColumn = tableView.getColumn("Vegetarian");
    vegetarianColumn.setPreferredWidth(100);
    // Show the values in the "Favorite Number" column in different colors.
    TableColumn numbersColumn = tableView.getColumn("Favorite Number");
    DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() {

        public void setValue(Object value) {
            int cellValue = (value instanceof Number) ? ((Number) value).intValue() : 0;
            setForeground((cellValue > 30) ? Color.black : Color.red);
            setText((value == null) ? "" : value.toString());
        }
    };
    numberColumnRenderer.setHorizontalAlignment(JLabel.RIGHT);
    numbersColumn.setCellRenderer(numberColumnRenderer);
    numbersColumn.setPreferredWidth(110);
    // Finish setting up the table.
    JScrollPane scrollpane = new JScrollPane(tableView);
    scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
    scrollpane.setPreferredSize(new Dimension(430, 200));
    contentPane.add(scrollpane);
}
Example 5
Project: statalign-master  File: VueBPList.java View source code
private void init() {
    Object[] col = { "Sec.Str.", "5' partner", "3' partner", "5' edge", "3' edge", "Orientation", "Remove" };
    columns = new ArrayList<Object>();
    for (int i = 0; i < col.length; i++) {
        columns.add(col[i]);
    }
    _backup = new ArrayList<Double>();
    data = new ArrayList<ModeleBP>();
    for (ModeleBP ms : _vp.getRNA().getAllBPs()) {
        data.add(ms);
    }
    Collections.sort(data);
    _tm = new BPTableModel();
    table = new JTable(_tm);
    table.setDefaultRenderer(Color.class, new ColorRenderer(true));
    table.setDefaultRenderer(Actions.class, new ActionRenderer());
    table.setDefaultEditor(ModeleBP.Edge.class, new DefaultCellEditor(new JComboBox(ModeleBP.Edge.values())));
    table.setDefaultEditor(ModeleBP.Stericity.class, new DefaultCellEditor(new JComboBox(ModeleBP.Stericity.values())));
    table.setDefaultEditor(Actions.class, new ActionEditor(this));
    table.setPreferredScrollableViewportSize(new Dimension(500, 500));
    table.getModel().addTableModelListener(this);
    table.setRowHeight(25);
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
    // content panes must be opaque
    setOpaque(true);
    this.doLayout();
    JOptionPane.showMessageDialog(_vp, this, "Base pairs Edition", JOptionPane.PLAIN_MESSAGE);
}
Example 6
Project: GdxStudio-master  File: PropertyPanel.java View source code
@Override
public void update(String... names) {
    rowCount = 0;
    super.update("Name", "" + SceneEditor.selectedActor.getName(), "X", "" + SceneEditor.selectedActor.getX(), "Y", "" + SceneEditor.selectedActor.getY(), "Width", "" + SceneEditor.selectedActor.getWidth(), "Height", "" + SceneEditor.selectedActor.getHeight(), "OriginX", "" + SceneEditor.selectedActor.getOriginX(), "OriginY", "" + SceneEditor.selectedActor.getOriginY(), "Rotation", "" + SceneEditor.selectedActor.getRotation(), "Z-Index", "" + SceneEditor.selectedActor.getZIndex(), "Color", "" + SceneEditor.selectedActor.getColor().toString(), "Touchable", "" + SceneEditor.selectedActor.getTouchable().toString(), "Visible", "" + SceneEditor.selectedActor.isVisible());
    editors.set(12, createTextFieldEditor());
    editors.set(13, createTextFieldEditor());
    editors.set(14, createTextFieldEditor());
    editors.set(15, createTextFieldEditor());
    /* From here it varies for each type */
    if (SceneEditor.selectedActor instanceof ImageJson) {
        addRow("Texture", "" + // row 7
        ((ImageJson) SceneEditor.selectedActor).getTexName());
        texcombo.removeAllItems();
        for (String tex : Asset.texMap.keys()) texcombo.addItem(tex);
        editors.set(12, new DefaultCellEditor(texcombo));
    }
    /* FONTS */
    if (SceneEditor.selectedActor instanceof Label) {
        addRow("Font", "" + // row 7
        Asset.fontMap.getKey(// row 7
        ((Label) SceneEditor.selectedActor).getStyle().font, // row 7
        false));
        addRow("Text", "" + ((Label) SceneEditor.selectedActor).getText());
        fontcombo.removeAllItems();
        for (String font : Asset.fontMap.keys()) fontcombo.addItem(font);
        editors.set(12, new DefaultCellEditor(fontcombo));
    }
    if (SceneEditor.selectedActor instanceof TextButton) {
        addRow("Text", "" + ((TextButton) SceneEditor.selectedActor).getText());
    }
    if (SceneEditor.selectedActor instanceof TextField) {
        addRow("Text", "" + ((TextField) SceneEditor.selectedActor).getText());
        addRow("MessageText", "" + ((TextField) SceneEditor.selectedActor).getMessageText());
    //addRow("Password", ""+((TextFieldJson)Sink.selectedActor).getPasswordMode()});
    }
    if (SceneEditor.selectedActor instanceof CheckBox)
        addRow("Text", "" + ((CheckBox) SceneEditor.selectedActor).getText());
    if (SceneEditor.selectedActor instanceof Dialog) {
        editors.set(12, createBooleanEditor());
        editors.set(13, createBooleanEditor());
        editors.set(14, createBooleanEditor());
        addRow("Modal", "" + //7
        ((Dialog) SceneEditor.selectedActor).isModal());
        addRow("Moveble", "" + //8
        ((Dialog) SceneEditor.selectedActor).isMovable());
        addRow("Resizable", "" + //9
        ((Dialog) SceneEditor.selectedActor).isResizable());
        addRow("Text", "" + ((Dialog) SceneEditor.selectedActor).getTitle());
    }
    if (SceneEditor.selectedActor instanceof Touchpad) {
        addRow("Deadzone", "" + Serializer.TouchpadSerializer.deadZoneRadius);
    }
    if (SceneEditor.selectedActor instanceof Slider) {
        Slider slider = ((Slider) SceneEditor.selectedActor);
        addRow("Min", "" + slider.getMinValue());
        addRow("Max", "" + slider.getMaxValue());
        addRow("Step", "" + slider.getStepSize());
        addRow("Value", "" + slider.getValue());
    }
    if (SceneEditor.selectedActor instanceof Sprite) {
        Sprite sprite = ((Sprite) SceneEditor.selectedActor);
        editors.set(12, createBooleanEditor());
        editors.set(13, createBooleanEditor());
        addRow("Active", "" + sprite.isAnimationActive);
        addRow("Looping", "" + sprite.isAnimationLooping);
        addRow("Duration", "" + sprite.getDuration());
        addRow("Textures", "" + sprite.toString());
    }
    int value = getRowCount();
    for (int i = 0; i < noOfRows - value; i++) addRow("", "");
}
Example 7
Project: eclipselink.runtime-master  File: ComboBoxTableCellRenderer.java View source code
protected JComboBox buildComboBox() {
    final JComboBox result = new JComboBox() {

        private boolean fakeFocus;

        public boolean hasFocus() {
            return fakeFocus || super.hasFocus();
        }

        public void paint(Graphics g) {
            fakeFocus = ComboBoxTableCellRenderer.this.fakeFocusFlag;
            super.paint(g);
            fakeFocus = false;
        }

        //wrap the renderer to deal with the prototypeDisplayValue
        public void setRenderer(final ListCellRenderer aRenderer) {
            super.setRenderer(new ListCellRenderer() {

                public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                    if (value == prototypeLabel) {
                        return prototypeLabel;
                    }
                    return aRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                }
            });
        }

        public int getSelectedIndex() {
            boolean listNotCached = !listIsCached();
            if (listNotCached) {
                cacheList();
            }
            int index = super.getSelectedIndex();
            if (listNotCached) {
                uncacheList();
            }
            return index;
        }
    };
    // see javax.swing.DefaultCellEditor for usage
    result.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
    result.addActionListener(this.buildActionListener());
    result.addPopupMenuListener(this.buildPopupMenuListener());
    //These are used to workaround problems with Swing trying to
    //determine the size of a comboBox with a large model
    result.setPrototypeDisplayValue(prototypeLabel);
    getListBox(result).setPrototypeCellValue(prototypeLabel);
    return result;
}
Example 8
Project: snap-desktop-master  File: SpectrumChooser.java View source code
private JTable createBandsTable(int index) {
    DisplayableSpectrum spectrum = spectra[index];
    final Band[] spectralBands = spectrum.getSpectralBands();
    Object[][] spectrumData = new Object[spectralBands.length][band_columns.length];
    for (int i = 0; i < spectralBands.length; i++) {
        Band spectralBand = spectralBands[i];
        final boolean selected = spectrum.isBandSelected(i) && spectrum.isSelected();
        spectrumData[i][band_selected_index] = selected;
        spectrumData[i][band_name_index] = spectralBand.getName();
        spectrumData[i][band_description_index] = spectralBand.getDescription();
        spectrumData[i][band_wavelength_index] = spectralBand.getSpectralWavelength();
        spectrumData[i][band_bandwidth_ndex] = spectralBand.getSpectralBandwidth();
        spectrumData[i][band_unit_index] = spectralBand.getUnit();
    }
    final BandTableModel bandTableModel = new BandTableModel(spectrumData, band_columns);
    bandTableModel.addTableModelListener( e -> {
        e.getSource();
        if (e.getColumn() == band_selected_index) {
            final DisplayableSpectrum spectrum1 = spectra[index];
            final int bandRow = e.getFirstRow();
            final Boolean selected = (Boolean) bandTableModel.getValueAt(bandRow, e.getColumn());
            spectrum1.setBandSelected(bandRow, selected);
            if (!selectionChangeLock) {
                selectionChangeLock = true;
                selectionAdmin.setBandSelected(index, bandRow, selected);
                selectionAdmin.updateSpectrumSelectionState(index, selectionAdmin.getState(index));
                tristateCheckBoxes[index].setState(selectionAdmin.getState(index));
                spectrum1.setSelected(selectionAdmin.isSpectrumSelected(index));
                selectionChangeLock = false;
            }
        }
    });
    JTable bandsTable = new JTable(bandTableModel);
    bandsTable.setRowSorter(new TableRowSorter<>(bandTableModel));
    final TableColumn selectionColumn = bandsTable.getColumnModel().getColumn(band_selected_index);
    final JCheckBox selectionCheckBox = new JCheckBox();
    selectionColumn.setCellEditor(new DefaultCellEditor(selectionCheckBox));
    selectionColumn.setMinWidth(20);
    selectionColumn.setMaxWidth(20);
    BooleanRenderer booleanRenderer = new BooleanRenderer();
    selectionColumn.setCellRenderer(booleanRenderer);
    final TableColumn wavelengthColumn = bandsTable.getColumnModel().getColumn(band_wavelength_index);
    wavelengthColumn.setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("###0.0##")));
    final TableColumn bandwidthColumn = bandsTable.getColumnModel().getColumn(band_bandwidth_ndex);
    bandwidthColumn.setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("###0.0##")));
    return bandsTable;
}
Example 9
Project: freemind-mmx-master  File: AttributeTable.java View source code
/**
     * 
     */
public Component prepareEditor(TableCellEditor tce, int row, int col) {
    ComboBoxModel model;
    JComboBox comboBox = (JComboBox) ((DefaultCellEditor) tce).getComponent();
    MindMapNode node = getAttributeTableModel().getNode();
    AttributeRegistry attributes = node.getMap().getRegistry().getAttributes();
    switch(col) {
        case 0:
            model = attributes.getComboBoxModel();
            comboBox.setEditable(!attributes.isRestricted());
            break;
        case 1:
            String attrName = getAttributeTableModel().getValueAt(row, 0).toString();
            model = attributes.getDefaultComboBoxModel(attrName);
            comboBox.setEditable(!attributes.isRestricted(attrName));
            break;
        default:
            model = getDefaultComboBoxModel();
    }
    comboBox.setModel(model);
    model.setSelectedItem(getValueAt(row, col));
    comboBox.addFocusListener(focusListener);
    comboBox.getEditor().getEditorComponent().addFocusListener(focusListener);
    Component editor = super.prepareEditor(tce, row, col);
    updateFontSize(editor, getZoom());
    return editor;
}
Example 10
Project: slumdroid-master  File: GuiAnalyzer.java View source code
/**
	 * Creates the layout.
	 */
private void createLayout() {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    resetAll();
    try {
        processGuiTree = new ProcessGuiTree(theFile.toString());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }
    int numWidgets = processGuiTree.getNumWidgets();
    colId = new Object[numWidgets];
    Object[] colWidgets = new Object[numWidgets];
    Object[] colName = new Object[numWidgets];
    Object[] colValue = new Object[numWidgets];
    colType = new Object[numWidgets];
    Object[] colScreen = new Object[numWidgets];
    Object[] colInteraction = new Object[numWidgets];
    Object[] colSimpleType = new Object[numWidgets];
    int item = 0;
    Collection<WidgetState> WidgetsColl = processGuiTree.getWidgets().values();
    for (WidgetState widget : WidgetsColl) {
        colId[item] = widget.getId();
        colWidgets[item] = widget.getType();
        colName[item] = widget.getName();
        colValue[item] = widget.getValue();
        colType[item] = widget.getTextType();
        colInteraction[item] = processGuiTree.getInteractions().get(widget.getId());
        colSimpleType[item] = widget.getSimpleType();
        colScreen[item] = new JButton(processGuiTree.getScreens().get(widget.getId()));
        item++;
    }
    tabelModel.addColumn("Id", colId);
    tabelModel.addColumn("Widgets Type", colWidgets);
    tabelModel.addColumn("Simple Type", colSimpleType);
    tabelModel.addColumn("Name", colName);
    tabelModel.addColumn("Valid Input", colValue);
    tabelModel.addColumn("Text Type", colType);
    tabelModel.addColumn("Interactions", colInteraction);
    tabelModel.addColumn("Perturbation", new String[] { "" });
    tabelModel.addColumn("Screenshot", colScreen);
    // ComboBox
    JComboBox<String> comboBox = new JComboBox<String>(comboValues);
    jTableInfo.getColumnModel().getColumn(7).setCellEditor(new DefaultCellEditor(comboBox));
    jTableInfo.getColumnModel().getColumn(7).setCellRenderer(new ComboBoxRenderer(comboValues));
    comboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent event) {
            changeWidgetInfo();
        }
    });
    jTableInfo.setRowHeight(20);
    jTableInfo.getColumnModel().getColumn(8).setMinWidth(0);
    jTableInfo.getColumnModel().getColumn(8).setMaxWidth(0);
    jTableInfo.getColumnModel().getColumn(8).setWidth(0);
    jTableInfo.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            changeWidgetInfo();
        }
    });
    firstImage();
}
Example 11
Project: ProjectLibre-master  File: ResourceMappingDialog.java View source code
public void addColumn(TableColumn tc) {
    if (columnIndex == 0) {
        //$NON-NLS-1$
        tc.setHeaderValue(//$NON-NLS-1$
        Messages.getString("ResourceMappingDialog.ImportedResources"));
        tc.setPreferredWidth(150);
    } else {
        //$NON-NLS-1$
        tc.setHeaderValue(//$NON-NLS-1$
        Messages.getString("ResourceMappingDialog.ServerResources"));
        tc.setPreferredWidth(150);
        //				tc.setCellEditor(new ListComboBoxCellEditor(new DefaultComboBoxModel(form.getResources())));
        tc.setCellEditor(new DefaultCellEditor(editorCombo));
    }
    tc.setCellRenderer(new DefaultTableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focused, int row, int column) {
            setEnabled(table == null || table.isEnabled());
            super.getTableCellRendererComponent(table, value, selected, focused, row, column);
            return this;
        }
    });
    super.addColumn(tc);
    columnIndex++;
}
Example 12
Project: compomics-utilities-master  File: MsConvertParametersDialog.java View source code
/**
     * Sets up the GUI components.
     *
     * @param msConvertParameters parameters to display on the interface,
     * ignored if null
     */
private void setUpGUI(MsConvertParameters msConvertParameters) {
    filtersTableScrollPane.getViewport().setOpaque(false);
    filtersTable.getTableHeader().setReorderingAllowed(false);
    if (msConvertParameters != null) {
        outputFormatCmb.setSelectedItem(msConvertParameters.getMsFormat());
        filters = (HashMap<Integer, String>) msConvertParameters.getFiltersMap().clone();
    } else {
        outputFormatCmb.setSelectedItem(MsFormat.mzML);
        filters = new HashMap<Integer, String>(2);
    }
    filterIndexes = new ArrayList<Integer>(filters.keySet());
    Collections.sort(filterIndexes);
    DefaultTableModel tableModel = new FiltersTableModel();
    filtersTable.setModel(tableModel);
    TableColumnModel tableColumnModel = filtersTable.getColumnModel();
    tableColumnModel.getColumn(0).setMinWidth(50);
    tableColumnModel.getColumn(0).setMaxWidth(50);
    TableColumn filterColumn = tableColumnModel.getColumn(1);
    filterColumn.setMinWidth(200);
    filterColumn.setMaxWidth(200);
    JComboBox comboBox = new JComboBox(ProteoWizardFilter.values());
    filterColumn.setCellEditor(new DefaultCellEditor(comboBox));
    for (final ProteoWizardFilter tempFilter : ProteoWizardFilter.values()) {
        JMenuItem tempFilterMenuItem = new javax.swing.JMenuItem(tempFilter.name);
        tempFilterMenuItem.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                if (!filters.containsKey(tempFilter.number)) {
                    filters.put(tempFilter.number, "");
                    updateTable();
                }
            }
        });
        addFilterMenu.add(tempFilterMenuItem);
    }
    outputFormatCmb.setRenderer(new AlignedListCellRenderer(SwingConstants.CENTER));
    utilitiesUserPreferences = UtilitiesUserPreferences.loadUserPreferences();
    if (utilitiesUserPreferences.getProteoWizardPath() == null) {
        int option = JOptionPane.showConfirmDialog(this, "Cannot find ProteoWizard. Do you want to download it now?", "Download ProteoWizard?", JOptionPane.YES_NO_OPTION);
        if (option == JOptionPane.YES_OPTION) {
            openWebPage();
        }
    }
    // display the current path
    if (utilitiesUserPreferences != null) {
        installationJTextField.setText(utilitiesUserPreferences.getProteoWizardPath());
        lastSelectedFolder = utilitiesUserPreferences.getProteoWizardPath();
    }
}
Example 13
Project: breakout-master  File: ObjectTreeTable.java View source code
@Override
public TableCellEditor getCellEditor(int row, int column) {
    Node node = getNodeAt(row);
    Class<?> valueClass = node.getValue() == null ? null : node.getValue().getClass();
    Class<?> storageClass = node.getStorageClass();
    if (node.getValue() instanceof Enum) {
        DefaultSelector<Object> selector = new DefaultSelector<Object>();
        selector.setAvailableValues(Arrays.asList(valueClass.getEnumConstants()));
        selector.comboBox().setRenderer(new ComboBoxCellRenderer());
        return new DefaultCellEditor(selector.comboBox());
    } else if (storageClass.isEnum()) {
        DefaultSelector<Object> selector = new DefaultSelector<Object>();
        selector.setAvailableValues(Arrays.asList(storageClass.getEnumConstants()));
        selector.comboBox().setRenderer(new ComboBoxCellRenderer());
        return new DefaultCellEditor(selector.comboBox());
    } else if (enumlikeTypes.containsKey(valueClass)) {
        DefaultSelector<Object> selector = new DefaultSelector<Object>();
        selector.setAvailableValues(enumlikeTypes.get(valueClass));
        selector.comboBox().setRenderer(new ComboBoxCellRenderer());
        return new DefaultCellEditor(selector.comboBox());
    } else if (enumlikeTypes.containsKey(storageClass)) {
        DefaultSelector<Object> selector = new DefaultSelector<Object>();
        selector.setAvailableValues(enumlikeTypes.get(storageClass));
        selector.comboBox().setRenderer(new ComboBoxCellRenderer());
        return new DefaultCellEditor(selector.comboBox());
    } else if (valueClass == boolean.class || valueClass == Boolean.class || storageClass == boolean.class || storageClass == Boolean.class) {
        return new DefaultCellEditor(new JCheckBox());
    } else if (valueClass == Date.class || storageClass == Date.class) {
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DatePickerCellEditor datePicker = new DatePickerCellEditor(format);
        datePicker.setClickCountToStart(0);
        return datePicker;
    }
    return super.getCellEditor(row, column);
}
Example 14
Project: Desktop-master  File: AttributeTable.java View source code
@SuppressWarnings("serial")
public TableCellEditor getCellEditor(final int row, final int col, EventObject e) {
    if (dce != null) {
        dce.stopCellEditing();
    }
    if (col == 1) {
        final MTextController textController = (MTextController) TextController.getController();
        if (e instanceof KeyEvent) {
            final KeyEvent kev = (KeyEvent) e;
            textController.getEventQueue().setFirstEvent(kev);
        }
        final IAttributeTableModel model = (IAttributeTableModel) getModel();
        final String text = getValueForEdit(row, col);
        final DialogTableCellEditor dialogTableCellEditor = new DialogTableCellEditor();
        EditNodeBase base = textController.getEditNodeBase(model.getNode(), text, dialogTableCellEditor.getEditControl(), false);
        if (base != null) {
            dialogTableCellEditor.setEditBase(base);
            return dialogTableCellEditor;
        }
    }
    final JComboBox comboBox;
    if (dce == null) {
        comboBox = new JComboBox();
        comboBox.addFocusListener(AttributeTable.focusListener);
        comboBox.getEditor().getEditorComponent().addFocusListener(AttributeTable.focusListener);
        comboBox.setRenderer(new TypedListCellRenderer());
        dce = new DefaultCellEditor(comboBox) {

            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) {
                return super.getTableCellEditorComponent(table, ((AttributeTable) table).getValueForEdit(row, col), isSelected, row, col);
            }
        };
        dce.setClickCountToStart(CLICK_COUNT_TO_START);
    }
    return dce;
}
Example 15
Project: geotoolkit-master  File: JColorMapPane.java View source code
private void postParse() {
    guiTable.setModel(model);
    guiInvert.setEnabled(true);
    guiMinSpinner.setEnabled(true);
    guiMaxSpinner.setEnabled(true);
    if (model instanceof InterpolateColorModel) {
        guiMethod.setSelectedItem(Interpolate.class);
        setPalettes(PALETTES);
        guiTable.getColumnModel().getColumn(0).setCellRenderer(new NumberAlignRenderer());
        guiTable.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JTextField()));
        guiTable.getColumnModel().getColumn(1).setCellRenderer(new ColorCellRenderer());
        guiTable.getColumnModel().getColumn(1).setCellEditor(new ColorCellEditor());
        guiTable.getColumnModel().getColumn(2).setCellRenderer(new DeleteRenderer());
        guiTable.getColumnModel().getColumn(2).setCellEditor(new DeleteEditor());
        guiTable.getColumnExt(2).setMaxWidth(20);
        final InterpolateColorModel icm = (InterpolateColorModel) model;
        //restore NaN and min/max values
        boolean hasNaN = false;
        double min = Double.NaN;
        double max = Double.NaN;
        for (int i = 0, n = icm.points.size(); i < n; i++) {
            final double v = icm.points.get(i).getData().doubleValue();
            if (!Double.isNaN(v)) {
                min = Double.isNaN(min) ? v : Math.min(v, min);
                max = Double.isNaN(max) ? v : Math.max(v, max);
            } else {
                hasNaN = true;
            }
        }
        if (!Double.isNaN(min)) {
            guiMinSpinner.setValue(min);
            guiMaxSpinner.setValue(max);
        }
        guiNbStep.setValue(icm.points.size() - (hasNaN ? 1 : 0));
        guiNaN.setSelected(hasNaN);
    } else if (model instanceof CategorizeColorModel) {
        guiMethod.setSelectedItem(Categorize.class);
        setPalettes(PALETTES);
        guiTable.getColumnModel().getColumn(0).setCellRenderer(new NumberAlignRenderer());
        guiTable.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JTextField()));
        guiTable.getColumnModel().getColumn(1).setCellRenderer(new ColorCellRenderer());
        guiTable.getColumnModel().getColumn(1).setCellEditor(new ColorCellEditor());
        guiTable.getColumnModel().getColumn(2).setCellRenderer(new NumberAlignRenderer());
        guiTable.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(new JTextField()));
        guiTable.getColumnModel().getColumn(3).setCellRenderer(new DeleteRenderer());
        guiTable.getColumnModel().getColumn(3).setCellEditor(new DeleteEditor());
        guiTable.getColumnExt(3).setMaxWidth(20);
        final CategorizeColorModel ccm = (CategorizeColorModel) model;
        //restore NaN and min/max values
        boolean hasNaN = false;
        double min = Double.NaN;
        double max = Double.NaN;
        for (int i = 0, n = ccm.ths.size(); i < n; i++) {
            final Entry<Expression, Expression> exps = ccm.ths.get(i);
            Object val = exps.getKey().evaluate(n, Number.class);
            if (val instanceof Number) {
                final double v = ((Number) val).doubleValue();
                if (!Double.isNaN(v)) {
                    if (!Double.isInfinite(v)) {
                        min = Double.isNaN(min) ? v : Math.min(v, min);
                        max = Double.isNaN(max) ? v : Math.max(v, max);
                    }
                } else {
                    hasNaN = true;
                }
            }
        }
        if (!Double.isNaN(min)) {
            guiMinSpinner.setValue(min);
            guiMaxSpinner.setValue(max);
        }
        guiNbStep.setValue(ccm.ths.size() - (hasNaN ? 2 : 1));
        guiNaN.setSelected(hasNaN);
    } else if (model instanceof JenksColorModel) {
        guiMethod.setSelectedItem(Jenks.class);
        final JenksColorModel jcm = (JenksColorModel) model;
        setPalettes(PALETTES_NAMED);
        if (jcm.getPaletteName() != null) {
            guiPalette.setSelectedItem(jcm.getPaletteName());
        } else {
            guiPalette.setSelectedItem(0);
        }
        guiNbStep.setValue(jcm.getNbSteps());
        guiInvert.setEnabled(false);
        guiMinSpinner.setEnabled(false);
        guiMaxSpinner.setEnabled(false);
    }
    //disable and hide value table for jenks method
    guiAddOne.setVisible(!(model instanceof JenksColorModel));
    guiRemoveAll.setVisible(!(model instanceof JenksColorModel));
    guiTableScroll.setVisible(!(model instanceof JenksColorModel));
    guiJenksMessage.setVisible(model instanceof JenksColorModel);
    guiNoDataLabel.setVisible(model instanceof JenksColorModel);
    noDataContainer.setVisible(model instanceof JenksColorModel);
    if (layer instanceof CoverageMapLayer) {
        guiLblPalette.setVisible(true);
        guiPalette.setVisible(true);
        guiBand.setVisible(true);
        guiLblBand.setVisible(true);
        guiNaN.setVisible(true);
        guiInvert.setVisible(true);
        guiGenerate.setVisible(true);
        guiLblStep.setVisible(true);
        guiNbStep.setVisible(true);
    } else {
        guiLblPalette.setVisible(false);
        guiPalette.setVisible(false);
        guiBand.setVisible(false);
        guiLblBand.setVisible(false);
        guiNaN.setVisible(false);
        guiInvert.setVisible(false);
        guiGenerate.setVisible(false);
        guiLblStep.setVisible(false);
        guiNbStep.setVisible(false);
    }
    revalidate();
    repaint();
    //add a listener on the model to propage even
    model.addTableModelListener(new TableModelListener() {

        @Override
        public void tableChanged(TableModelEvent e) {
            firePropertyChange(PROPERTY_UPDATED, null, create());
        }
    });
}